blob: 07790b85cda31b5d94de1101a8102ee7464cc20a [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070016
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070018
Brian Carlstromdbc05252011-09-09 01:59:59 -070019#include <deque>
Ian Rogerscf7f1912014-10-22 22:06:39 -070020#include <iostream>
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Fred Shih381e4ca2014-08-25 17:24:27 -070022#include <queue>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070023#include <string>
Andreas Gampea696c0a2014-12-10 20:51:45 -080024#include <unistd.h>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070027
Mathieu Chartierc7853442015-03-27 14:35:38 -070028#include "art_field-inl.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080029#include "base/casts.h"
Elliott Hughes07ed66b2012-12-12 18:34:25 -080030#include "base/logging.h"
Narayan Kamathd1c606f2014-06-09 16:50:19 +010031#include "base/scoped_flock.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080032#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080033#include "base/unix_file/fd_file.h"
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070034#include "base/value_object.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "class_linker-inl.h"
Vladimir Marko2b5eaa22013-12-13 13:59:30 +000036#include "compiler_callbacks.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080037#include "debugger.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070038#include "dex_file-inl.h"
Ian Rogers6f3dbba2014-10-14 17:41:57 -070039#include "entrypoints/runtime_asm_entrypoints.h"
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -070040#include "gc_root-inl.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070041#include "gc/accounting/card_table-inl.h"
42#include "gc/accounting/heap_bitmap.h"
43#include "gc/heap.h"
44#include "gc/space/image_space.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070045#include "handle_scope.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070046#include "intern_table.h"
Ian Rogers64b6d142012-10-29 16:34:15 -070047#include "interpreter/interpreter.h"
Mathieu Chartiere5f13e52015-02-24 09:37:21 -080048#include "jit/jit.h"
49#include "jit/jit_code_cache.h"
Ian Rogers0571d352011-11-03 19:51:38 -070050#include "leb128.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070051#include "linear_alloc.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080052#include "oat.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070053#include "oat_file.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080054#include "oat_file_assistant.h"
Ian Rogers22d5e732014-07-15 22:23:51 -070055#include "object_lock.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070056#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "mirror/class.h"
58#include "mirror/class-inl.h"
59#include "mirror/class_loader.h"
Ian Rogers39ebcb82013-05-30 16:57:23 -070060#include "mirror/dex_cache-inl.h"
Mathieu Chartierdaaf3262015-03-24 13:30:28 -070061#include "mirror/field.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080062#include "mirror/iftable-inl.h"
Mathieu Chartierfc58af42015-04-16 18:00:39 -070063#include "mirror/method.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/object-inl.h"
65#include "mirror/object_array-inl.h"
66#include "mirror/proxy.h"
Fred Shih4ee7a662014-07-11 09:59:27 -070067#include "mirror/reference-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080068#include "mirror/stack_trace_element.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070069#include "mirror/string-inl.h"
Brian Carlstrom5b332c82012-02-01 15:02:31 -080070#include "os.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070071#include "runtime.h"
Ian Rogers7655f292013-07-29 11:07:13 -070072#include "entrypoints/entrypoint_utils.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070073#include "ScopedLocalRef.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070074#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070075#include "handle_scope-inl.h"
Ian Rogers7b078e82014-09-10 14:44:24 -070076#include "thread-inl.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070077#include "utils.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080078#include "verifier/method_verifier.h"
Elliott Hugheseac76672012-05-24 21:56:51 -070079#include "well_known_classes.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070080
81namespace art {
82
Mathieu Chartierc7853442015-03-27 14:35:38 -070083static constexpr bool kSanityCheckObjects = kIsDebugBuild;
84
Andreas Gampeb9aec2c2015-04-23 22:23:47 -070085// Do a simple class redefinition check in OpenDexFilesFromOat. This is a conservative check to
86// avoid problems with compile-time class-path != runtime class-path.
87static constexpr bool kCheckForDexCollisions = true;
88
Ian Rogers00f7d0e2012-07-19 15:28:27 -070089static void ThrowNoClassDefFoundError(const char* fmt, ...)
90 __attribute__((__format__(__printf__, 1, 2)))
Ian Rogersb726dcb2012-09-05 08:57:23 -070091 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
Elliott Hughes0512f022012-03-15 22:10:52 -070092static void ThrowNoClassDefFoundError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070093 va_list args;
94 va_start(args, fmt);
Ian Rogers62d6c772013-02-27 08:32:07 -080095 Thread* self = Thread::Current();
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +000096 self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
Ian Rogerscab01012012-01-10 17:35:46 -080097 va_end(args);
98}
99
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700100static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
Ian Rogersb726dcb2012-09-05 08:57:23 -0700101 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700102 mirror::ArtMethod* method = self->GetCurrentMethod(nullptr);
103 StackHandleScope<1> hs(self);
104 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
105 method->GetDeclaringClass()->GetClassLoader()
106 : nullptr));
107 mirror::Class* exception_class = class_linker->FindClass(self, descriptor, class_loader);
108
109 if (exception_class == nullptr) {
110 // No exc class ~ no <init>-with-string.
111 CHECK(self->IsExceptionPending());
112 self->ClearException();
113 return false;
114 }
115
116 mirror::ArtMethod* exception_init_method =
117 exception_class->FindDeclaredDirectMethod("<init>", "(Ljava/lang/String;)V");
118 return exception_init_method != nullptr;
119}
120
121void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c) {
Elliott Hughes5c599942012-06-13 16:45:05 -0700122 // The class failed to initialize on a previous attempt, so we want to throw
123 // a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
124 // failed in verification, in which case v2 5.4.1 says we need to re-throw
125 // the previous error.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800126 Runtime* const runtime = Runtime::Current();
127 if (!runtime->IsAotCompiler()) { // Give info if this occurs at runtime.
Ian Rogers87e552d2012-08-31 15:54:48 -0700128 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
129 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700130
Elliott Hughes5c599942012-06-13 16:45:05 -0700131 CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
Ian Rogers62d6c772013-02-27 08:32:07 -0800132 Thread* self = Thread::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800133 if (runtime->IsAotCompiler()) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700134 // At compile time, accurate errors and NCDFE are disabled to speed compilation.
135 mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000136 self->SetException(pre_allocated);
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700137 } else {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700138 if (c->GetVerifyErrorClass() != nullptr) {
Ian Rogers7b078e82014-09-10 14:44:24 -0700139 // TODO: change the verifier to store an _instance_, with a useful detail message?
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700140 // It's possible the exception doesn't have a <init>(String).
Ian Rogers7b078e82014-09-10 14:44:24 -0700141 std::string temp;
Andreas Gampebfdcdc12015-04-22 18:10:36 -0700142 const char* descriptor = c->GetVerifyErrorClass()->GetDescriptor(&temp);
143
144 if (HasInitWithString(self, this, descriptor)) {
145 self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str());
146 } else {
147 self->ThrowNewException(descriptor, nullptr);
148 }
Ian Rogers7b078e82014-09-10 14:44:24 -0700149 } else {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000150 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
Ian Rogers7b078e82014-09-10 14:44:24 -0700151 PrettyDescriptor(c).c_str());
152 }
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700153 }
154}
155
Brian Carlstromb23eab12014-10-08 17:55:21 -0700156static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
157 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
158 if (VLOG_IS_ON(class_linker)) {
159 std::string temp;
160 LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
Nicolas Geoffray14691c52015-03-05 10:40:17 +0000161 << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
Brian Carlstromb23eab12014-10-08 17:55:21 -0700162 }
163}
164
165static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
166 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughesa4f94742012-05-29 16:28:38 -0700167 Thread* self = Thread::Current();
168 JNIEnv* env = self->GetJniEnv();
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700169
170 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700171 CHECK(cause.get() != nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700172
173 env->ExceptionClear();
Elliott Hughesa4f94742012-05-29 16:28:38 -0700174 bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
175 env->Throw(cause.get());
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700176
Elliott Hughesa4f94742012-05-29 16:28:38 -0700177 // We only wrap non-Error exceptions; an Error can just be used as-is.
178 if (!is_error) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000179 self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700180 }
Brian Carlstromb23eab12014-10-08 17:55:21 -0700181 VlogClassInitializationFailure(klass);
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700182}
183
Fred Shih381e4ca2014-08-25 17:24:27 -0700184// Gap between two fields in object layout.
185struct FieldGap {
186 uint32_t start_offset; // The offset from the start of the object.
187 uint32_t size; // The gap size of 1, 2, or 4 bytes.
188};
189struct FieldGapsComparator {
190 explicit FieldGapsComparator() {
191 }
192 bool operator() (const FieldGap& lhs, const FieldGap& rhs)
193 NO_THREAD_SAFETY_ANALYSIS {
Andreas Gampef52857f2015-02-18 15:38:57 -0800194 // Sort by gap size, largest first. Secondary sort by starting offset.
195 return lhs.size > rhs.size || (lhs.size == rhs.size && lhs.start_offset < rhs.start_offset);
Fred Shih381e4ca2014-08-25 17:24:27 -0700196 }
197};
198typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
199
200// Adds largest aligned gaps to queue of gaps.
Andreas Gampe277ccbd2014-11-03 21:36:10 -0800201static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
Fred Shih381e4ca2014-08-25 17:24:27 -0700202 DCHECK(gaps != nullptr);
203
204 uint32_t current_offset = gap_start;
205 while (current_offset != gap_end) {
206 size_t remaining = gap_end - current_offset;
207 if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
208 gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
209 current_offset += sizeof(uint32_t);
210 } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
211 gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
212 current_offset += sizeof(uint16_t);
213 } else {
214 gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
215 current_offset += sizeof(uint8_t);
216 }
217 DCHECK_LE(current_offset, gap_end) << "Overran gap";
218 }
219}
220// Shuffle fields forward, making use of gaps whenever possible.
221template<int n>
Vladimir Marko76649e82014-11-10 18:32:59 +0000222static void ShuffleForward(size_t* current_field_idx,
Fred Shih381e4ca2014-08-25 17:24:27 -0700223 MemberOffset* field_offset,
Mathieu Chartierc7853442015-03-27 14:35:38 -0700224 std::deque<ArtField*>* grouped_and_sorted_fields,
Fred Shih381e4ca2014-08-25 17:24:27 -0700225 FieldGaps* gaps)
226 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
227 DCHECK(current_field_idx != nullptr);
228 DCHECK(grouped_and_sorted_fields != nullptr);
Fred Shih381e4ca2014-08-25 17:24:27 -0700229 DCHECK(gaps != nullptr);
230 DCHECK(field_offset != nullptr);
231
232 DCHECK(IsPowerOfTwo(n));
233 while (!grouped_and_sorted_fields->empty()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700234 ArtField* field = grouped_and_sorted_fields->front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700235 Primitive::Type type = field->GetTypeAsPrimitiveType();
236 if (Primitive::ComponentSize(type) < n) {
237 break;
238 }
239 if (!IsAligned<n>(field_offset->Uint32Value())) {
240 MemberOffset old_offset = *field_offset;
241 *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
242 AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
243 }
244 CHECK(type != Primitive::kPrimNot) << PrettyField(field); // should be primitive types
245 grouped_and_sorted_fields->pop_front();
Fred Shih381e4ca2014-08-25 17:24:27 -0700246 if (!gaps->empty() && gaps->top().size >= n) {
247 FieldGap gap = gaps->top();
248 gaps->pop();
249 DCHECK(IsAligned<n>(gap.start_offset));
250 field->SetOffset(MemberOffset(gap.start_offset));
251 if (gap.size > n) {
252 AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
253 }
254 } else {
255 DCHECK(IsAligned<n>(field_offset->Uint32Value()));
256 field->SetOffset(*field_offset);
257 *field_offset = MemberOffset(field_offset->Uint32Value() + n);
258 }
259 ++(*current_field_idx);
260 }
261}
262
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800263ClassLinker::ClassLinker(InternTable* intern_table)
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700264 // dex_lock_ is recursive as it may be used in stack dumping.
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700265 : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700266 dex_cache_image_class_lookup_required_(false),
267 failed_dex_cache_class_lookups_(0),
Ian Rogers98379392014-02-24 16:53:16 -0800268 class_roots_(nullptr),
269 array_iftable_(nullptr),
270 find_array_class_cache_next_victim_(0),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700271 init_done_(false),
Mathieu Chartier893263b2014-03-04 11:07:42 -0800272 log_new_dex_caches_roots_(false),
273 log_new_class_table_roots_(false),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700274 intern_table_(intern_table),
Ian Rogers98379392014-02-24 16:53:16 -0800275 quick_resolution_trampoline_(nullptr),
Andreas Gampe2da88232014-02-27 12:26:20 -0800276 quick_imt_conflict_trampoline_(nullptr),
Vladimir Marko8a630572014-04-09 18:45:35 +0100277 quick_generic_jni_trampoline_(nullptr),
Mathieu Chartier2d721012014-11-10 11:08:06 -0800278 quick_to_interpreter_bridge_trampoline_(nullptr),
279 image_pointer_size_(sizeof(void*)) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700280 CHECK(intern_table_ != nullptr);
281 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
282 find_array_class_cache_[i] = GcRoot<mirror::Class>(nullptr);
283 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700284}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700285
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800286void ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path) {
Brian Carlstroma004aa92012-02-08 18:05:09 -0800287 VLOG(startup) << "ClassLinker::Init";
Alex Light64ad14d2014-08-19 14:23:13 -0700288 CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700289
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700290 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700291
Elliott Hughes30646832011-10-13 16:59:46 -0700292 // java_lang_Class comes first, it's needed for AllocClass
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700293 Thread* const self = Thread::Current();
294 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700295 // The GC can't handle an object with a null class since we can't get the size of this object.
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800296 heap->IncrementDisableMovingGC(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700297 StackHandleScope<64> hs(self); // 64 is picked arbitrarily.
298 Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700299 heap->AllocNonMovableObject<true>(self, nullptr,
300 mirror::Class::ClassClassSize(),
Brian Carlstromf3632832014-05-20 15:36:53 -0700301 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700302 CHECK(java_lang_Class.Get() != nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700303 mirror::Class::SetClassClass(java_lang_Class.Get());
304 java_lang_Class->SetClass(java_lang_Class.Get());
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700305 if (kUseBakerOrBrooksReadBarrier) {
306 java_lang_Class->AssertReadBarrierPointer();
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800307 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700308 java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700309 java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
Mathieu Chartier1d27b342014-01-28 12:51:09 -0800310 heap->DecrementDisableMovingGC(self);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800311 // AllocClass(mirror::Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700312
Elliott Hughes418d20f2011-09-22 14:00:39 -0700313 // Class[] is used for reflection support.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700314 Handle<mirror::Class> class_array_class(hs.NewHandle(
315 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700316 class_array_class->SetComponentType(java_lang_Class.Get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700317
Ian Rogers23435d02012-09-24 11:23:12 -0700318 // java_lang_Object comes next so that object_array_class can be created.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700319 Handle<mirror::Class> java_lang_Object(hs.NewHandle(
320 AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700321 CHECK(java_lang_Object.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700322 // backfill Object as the super class of Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700323 java_lang_Class->SetSuperClass(java_lang_Object.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700324 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
Brian Carlstroma0808032011-07-18 00:39:23 -0700325
Ian Rogers23435d02012-09-24 11:23:12 -0700326 // Object[] next to hold class roots.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700327 Handle<mirror::Class> object_array_class(hs.NewHandle(
328 AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700329 object_array_class->SetComponentType(java_lang_Object.Get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700330
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700331 // Setup the char (primitive) class to be used for char[].
332 Handle<mirror::Class> char_class(hs.NewHandle(
333 AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
Hiroshi Yamauchif0edfc32014-09-25 11:46:46 -0700334 // The primitive char class won't be initialized by
335 // InitializePrimitiveClass until line 459, but strings (and
336 // internal char arrays) will be allocated before that and the
337 // component size, which is computed from the primitive type, needs
338 // to be set here.
339 char_class->SetPrimitiveType(Primitive::kPrimChar);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700340
Ian Rogers23435d02012-09-24 11:23:12 -0700341 // Setup the char[] class to be used for String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700342 Handle<mirror::Class> char_array_class(hs.NewHandle(
343 AllocClass(self, java_lang_Class.Get(),
344 mirror::Array::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700345 char_array_class->SetComponentType(char_class.Get());
346 mirror::CharArray::SetArrayClass(char_array_class.Get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700347
Ian Rogers23435d02012-09-24 11:23:12 -0700348 // Setup String.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700349 Handle<mirror::Class> java_lang_String(hs.NewHandle(
350 AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700351 mirror::String::SetClass(java_lang_String.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700352 java_lang_String->SetObjectSize(mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700353 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
Jesse Wilson14150742011-07-29 19:04:44 -0400354
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700355 // Setup java.lang.ref.Reference.
Fred Shih4ee7a662014-07-11 09:59:27 -0700356 Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
357 AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
358 mirror::Reference::SetClass(java_lang_ref_Reference.Get());
359 java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700360 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
Fred Shih4ee7a662014-07-11 09:59:27 -0700361
Ian Rogers23435d02012-09-24 11:23:12 -0700362 // Create storage for root classes, save away our work so far (requires descriptors).
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700363 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700364 mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
365 kClassRootsMax));
366 CHECK(!class_roots_.IsNull());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700367 SetClassRoot(kJavaLangClass, java_lang_Class.Get());
368 SetClassRoot(kJavaLangObject, java_lang_Object.Get());
369 SetClassRoot(kClassArrayClass, class_array_class.Get());
370 SetClassRoot(kObjectArrayClass, object_array_class.Get());
371 SetClassRoot(kCharArrayClass, char_array_class.Get());
372 SetClassRoot(kJavaLangString, java_lang_String.Get());
Fred Shih4ee7a662014-07-11 09:59:27 -0700373 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374
375 // Setup the primitive type classes.
Ian Rogers50b35e22012-10-04 10:09:15 -0700376 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
377 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
378 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
379 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
380 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
381 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
382 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
383 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384
Ian Rogers23435d02012-09-24 11:23:12 -0700385 // Create array interface entries to populate once we can load system classes.
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700386 array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700387
Ian Rogers23435d02012-09-24 11:23:12 -0700388 // Create int array type for AllocDexCache (done in AppendToBootClassPath).
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700389 Handle<mirror::Class> int_array_class(hs.NewHandle(
390 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700391 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700392 mirror::IntArray::SetArrayClass(int_array_class.Get());
393 SetClassRoot(kIntArrayClass, int_array_class.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700394
Mathieu Chartierc7853442015-03-27 14:35:38 -0700395 // Create long array type for AllocDexCache (done in AppendToBootClassPath).
396 Handle<mirror::Class> long_array_class(hs.NewHandle(
397 AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
398 long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
399 mirror::LongArray::SetArrayClass(long_array_class.Get());
400 SetClassRoot(kLongArrayClass, long_array_class.Get());
401
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700402 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700403
Ian Rogers52813c92012-10-11 11:50:38 -0700404 // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700405 Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
406 AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700407 SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700408 java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700409 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410
Mathieu Chartierc7853442015-03-27 14:35:38 -0700411 // Constructor, Method, and AbstractMethod are necessary so
Brian Carlstromf3632832014-05-20 15:36:53 -0700412 // that FindClass can link members.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700414 Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
415 AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700416 CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800417 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
418 java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700419 SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700420 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusResolved, self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700421 mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700422
423 // Set up array classes for string, field, method
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700424 Handle<mirror::Class> object_array_string(hs.NewHandle(
425 AllocClass(self, java_lang_Class.Get(),
426 mirror::ObjectArray<mirror::String>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700427 object_array_string->SetComponentType(java_lang_String.Get());
428 SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
Mathieu Chartier66f19252012-09-18 08:57:04 -0700429
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700430 Handle<mirror::Class> object_array_art_method(hs.NewHandle(
431 AllocClass(self, java_lang_Class.Get(),
432 mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700433 object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
434 SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
Ian Rogers4445a7e2012-10-05 17:19:13 -0700435
Ian Rogers23435d02012-09-24 11:23:12 -0700436 // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
437 // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
438 // these roots.
Mathieu Chartier66f19252012-09-18 08:57:04 -0700439 CHECK_NE(0U, boot_class_path.size());
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800440 for (auto& dex_file : boot_class_path) {
441 CHECK(dex_file.get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -0700442 AppendToBootClassPath(self, *dex_file);
Richard Uhlerfbef44d2014-12-23 09:48:51 -0800443 opened_dex_files_.push_back(std::move(dex_file));
Mathieu Chartier66f19252012-09-18 08:57:04 -0700444 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700445
446 // now we can use FindSystemClass
447
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700448 // run char class through InitializePrimitiveClass to finish init
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700449 InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
450 SetClassRoot(kPrimitiveChar, char_class.Get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700451
Jeff Hao88474b42013-10-23 16:24:40 -0700452 // Create runtime resolution and imt conflict methods. Also setup the default imt.
453 Runtime* runtime = Runtime::Current();
454 runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
455 runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700456 runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod());
Jeff Hao88474b42013-10-23 16:24:40 -0700457 runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
458
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700459 // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
460 // we do not need friend classes or a publicly exposed setter.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700461 quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800462 if (!runtime->IsAotCompiler()) {
Alex Light64ad14d2014-08-19 14:23:13 -0700463 // We need to set up the generic trampolines since we don't have an image.
Ian Rogers6f3dbba2014-10-14 17:41:57 -0700464 quick_resolution_trampoline_ = GetQuickResolutionStub();
465 quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
466 quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
Alex Light64ad14d2014-08-19 14:23:13 -0700467 }
Dmitry Petrochenkof0972a42014-05-16 17:43:39 +0700468
Mathieu Chartier66f19252012-09-18 08:57:04 -0700469 // Object, String and DexCache need to be rerun through FindSystemClass to finish init
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700470 mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700471 CHECK_EQ(java_lang_Object.Get(), FindSystemClass(self, "Ljava/lang/Object;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700472 CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700473 mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
Ian Rogers98379392014-02-24 16:53:16 -0800474 mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700475 if (java_lang_String.Get() != String_class) {
476 std::ostringstream os1, os2;
477 java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
478 String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
479 LOG(FATAL) << os1.str() << "\n\n" << os2.str();
480 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700481 CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700482 mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700483 CHECK_EQ(java_lang_DexCache.Get(), FindSystemClass(self, "Ljava/lang/DexCache;"));
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700484 CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700485
Ian Rogers23435d02012-09-24 11:23:12 -0700486 // Setup the primitive array type classes - can't be done until Object has a vtable.
Ian Rogers98379392014-02-24 16:53:16 -0800487 SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800488 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700489
Ian Rogers98379392014-02-24 16:53:16 -0800490 SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800491 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700492
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700493 CHECK_EQ(char_array_class.Get(), FindSystemClass(self, "[C"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700494
Ian Rogers98379392014-02-24 16:53:16 -0800495 SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800496 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700497
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700498 CHECK_EQ(int_array_class.Get(), FindSystemClass(self, "[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700499
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700500 CHECK_EQ(long_array_class.Get(), FindSystemClass(self, "[J"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700501
Ian Rogers98379392014-02-24 16:53:16 -0800502 SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800503 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700504
Ian Rogers98379392014-02-24 16:53:16 -0800505 SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800506 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700508 CHECK_EQ(class_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Class;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700509
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700510 CHECK_EQ(object_array_class.Get(), FindSystemClass(self, "[Ljava/lang/Object;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511
Ian Rogers23435d02012-09-24 11:23:12 -0700512 // Setup the single, global copy of "iftable".
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700513 auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
514 CHECK(java_lang_Cloneable.Get() != nullptr);
515 auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
516 CHECK(java_io_Serializable.Get() != nullptr);
Ian Rogers23435d02012-09-24 11:23:12 -0700517 // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
518 // crawl up and explicitly list all of the supers as well.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700519 array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
520 array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700521
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700522 // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
523 // suspension.
524 CHECK_EQ(java_lang_Cloneable.Get(),
525 mirror::Class::GetDirectInterface(self, class_array_class, 0));
526 CHECK_EQ(java_io_Serializable.Get(),
527 mirror::Class::GetDirectInterface(self, class_array_class, 1));
528 CHECK_EQ(java_lang_Cloneable.Get(),
529 mirror::Class::GetDirectInterface(self, object_array_class, 0));
530 CHECK_EQ(java_io_Serializable.Get(),
531 mirror::Class::GetDirectInterface(self, object_array_class, 1));
Brian Carlstromea46f952013-07-30 01:26:50 -0700532 // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700533 // dex_cache_ fields and register them in class_table_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700534 CHECK_EQ(java_lang_Class.Get(), FindSystemClass(self, "Ljava/lang/Class;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700535
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700536 mirror::Class::SetStatus(java_lang_reflect_ArtMethod, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700537 CHECK_EQ(java_lang_reflect_ArtMethod.Get(),
538 FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;"));
539 CHECK_EQ(object_array_string.Get(),
540 FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
541 CHECK_EQ(object_array_art_method.Get(),
542 FindSystemClass(self, GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700543
Ian Rogers23435d02012-09-24 11:23:12 -0700544 // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
Ian Rogers466bb252011-10-14 03:29:56 -0700545
Ian Rogers23435d02012-09-24 11:23:12 -0700546 // Create java.lang.reflect.Proxy root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700547 SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
Ian Rogers466bb252011-10-14 03:29:56 -0700548
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700549 // Create java.lang.reflect.Field.class root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700550 auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
551 CHECK(class_root != nullptr);
552 SetClassRoot(kJavaLangReflectField, class_root);
553 mirror::Field::SetClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700554
555 // Create java.lang.reflect.Field array root.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700556 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
557 CHECK(class_root != nullptr);
558 SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
559 mirror::Field::SetArrayClass(class_root);
560
561 // Create java.lang.reflect.Constructor.class root and array root.
562 class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
563 CHECK(class_root != nullptr);
564 SetClassRoot(kJavaLangReflectConstructor, class_root);
565 mirror::Constructor::SetClass(class_root);
566 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
567 CHECK(class_root != nullptr);
568 SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
569 mirror::Constructor::SetArrayClass(class_root);
570
571 // Create java.lang.reflect.Method.class root and array root.
572 class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
573 CHECK(class_root != nullptr);
574 SetClassRoot(kJavaLangReflectMethod, class_root);
575 mirror::Method::SetClass(class_root);
576 class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
577 CHECK(class_root != nullptr);
578 SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
579 mirror::Method::SetArrayClass(class_root);
Mathieu Chartierdaaf3262015-03-24 13:30:28 -0700580
Brian Carlstrom1f870082011-08-23 16:02:11 -0700581 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Fred Shih4ee7a662014-07-11 09:59:27 -0700582 // finish initializing Reference class
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -0700583 mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700584 CHECK_EQ(java_lang_ref_Reference.Get(), FindSystemClass(self, "Ljava/lang/ref/Reference;"));
Fred Shih4ee7a662014-07-11 09:59:27 -0700585 CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
586 CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700587 class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
588 class_root->SetAccessFlags(class_root->GetAccessFlags() |
589 kAccClassIsReference | kAccClassIsFinalizerReference);
590 class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
591 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference |
592 kAccClassIsPhantomReference);
593 class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
594 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference);
595 class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
596 class_root->SetAccessFlags(class_root->GetAccessFlags() | kAccClassIsReference |
597 kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700598
Ian Rogers23435d02012-09-24 11:23:12 -0700599 // Setup the ClassLoader, verifying the object_size_.
Mathieu Chartierfc58af42015-04-16 18:00:39 -0700600 class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
601 CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
602 SetClassRoot(kJavaLangClassLoader, class_root);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700603
jeffhao8cd6dda2012-02-22 10:15:34 -0800604 // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
Ian Rogers23435d02012-09-24 11:23:12 -0700605 // java.lang.StackTraceElement as a convenience.
Ian Rogers98379392014-02-24 16:53:16 -0800606 SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800607 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
Brian Carlstromf3632832014-05-20 15:36:53 -0700608 SetClassRoot(kJavaLangClassNotFoundException,
609 FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
Ian Rogers98379392014-02-24 16:53:16 -0800610 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
Brian Carlstromf3632832014-05-20 15:36:53 -0700611 SetClassRoot(kJavaLangStackTraceElementArrayClass,
612 FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800613 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700614
Andreas Gampe76bd8802014-12-10 16:43:58 -0800615 // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
616 // initialized.
617 {
618 const DexFile& dex_file = java_lang_Object->GetDexFile();
619 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
620 CHECK(void_string_id != nullptr);
621 uint32_t void_string_index = dex_file.GetIndexForStringId(*void_string_id);
622 const DexFile::TypeId* void_type_id = dex_file.FindTypeId(void_string_index);
623 CHECK(void_type_id != nullptr);
624 uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
625 // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
626 // as referrer so the used dex cache is core's one.
627 mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
628 CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
629 self->AssertNoPendingException();
630 }
631
Ian Rogers98379392014-02-24 16:53:16 -0800632 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700633
Brian Carlstroma004aa92012-02-08 18:05:09 -0800634 VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700635}
636
Ian Rogers98379392014-02-24 16:53:16 -0800637void ClassLinker::FinishInit(Thread* self) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800638 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700639
640 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700641 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700642 // as the types of the field can't be resolved prior to the runtime being
643 // fully initialized
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800644 mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Ian Rogers8b2c0b92013-09-19 02:56:49 -0700645 mirror::Class* java_lang_ref_FinalizerReference =
Ian Rogers98379392014-02-24 16:53:16 -0800646 FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800647
Mathieu Chartierc7853442015-03-27 14:35:38 -0700648 ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700649 CHECK_STREQ(pendingNext->GetName(), "pendingNext");
650 CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700651
Mathieu Chartierc7853442015-03-27 14:35:38 -0700652 ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700653 CHECK_STREQ(queue->GetName(), "queue");
654 CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700655
Mathieu Chartierc7853442015-03-27 14:35:38 -0700656 ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700657 CHECK_STREQ(queueNext->GetName(), "queueNext");
658 CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700659
Mathieu Chartierc7853442015-03-27 14:35:38 -0700660 ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700661 CHECK_STREQ(referent->GetName(), "referent");
662 CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700663
Mathieu Chartierc7853442015-03-27 14:35:38 -0700664 ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -0700665 CHECK_STREQ(zombie->GetName(), "zombie");
666 CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700667
Brian Carlstroma663ea52011-08-19 23:33:41 -0700668 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700669 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700670 ClassRoot class_root = static_cast<ClassRoot>(i);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800671 mirror::Class* klass = GetClassRoot(class_root);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700672 CHECK(klass != nullptr);
673 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700674 // note SetClassRoot does additional validation.
675 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700676 }
677
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -0700678 CHECK(!array_iftable_.IsNull());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700679
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700680 // disable the slow paths in FindClass and CreatePrimitiveClass now
681 // that Object, Class, and Object[] are setup
682 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700683
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800684 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700685}
686
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700687void ClassLinker::RunRootClinits() {
688 Thread* self = Thread::Current();
689 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -0800690 mirror::Class* c = GetClassRoot(ClassRoot(i));
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700691 if (!c->IsArrayClass() && !c->IsPrimitive()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700692 StackHandleScope<1> hs(self);
693 Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
Ian Rogers7b078e82014-09-10 14:44:24 -0700694 EnsureInitialized(self, h_class, true, true);
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700695 self->AssertNoPendingException();
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700696 }
697 }
698}
699
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700700const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700701 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -0800702 if (kIsDebugBuild) {
703 for (size_t i = 0; i < oat_files_.size(); ++i) {
704 CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
Ian Rogers1bf8d4d2013-05-30 00:18:49 -0700705 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -0800706 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700707 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
708 oat_files_.push_back(oat_file);
709 return oat_file;
Brian Carlstrom866c8622012-01-06 16:35:13 -0800710}
711
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700712OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
713 VLOG(startup) << "ClassLinker::GetImageOatFile entering";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700714 OatFile* oat_file = space->ReleaseOatFile();
715 CHECK_EQ(RegisterOatFile(oat_file), oat_file);
Brian Carlstrom56d947f2013-07-15 13:14:23 -0700716 VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700717 return *oat_file;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700718}
719
Andreas Gampeb9aec2c2015-04-23 22:23:47 -0700720class DexFileAndClassPair : ValueObject {
721 public:
722 DexFileAndClassPair(const DexFile* dex_file, size_t current_class_index, bool from_loaded_oat)
723 : cached_descriptor_(GetClassDescriptor(dex_file, current_class_index)),
724 dex_file_(dex_file),
725 current_class_index_(current_class_index),
726 from_loaded_oat_(from_loaded_oat) {}
727
728 DexFileAndClassPair(const DexFileAndClassPair&) = default;
729
730 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) {
731 cached_descriptor_ = rhs.cached_descriptor_;
732 dex_file_ = rhs.dex_file_;
733 current_class_index_ = rhs.current_class_index_;
734 from_loaded_oat_ = rhs.from_loaded_oat_;
735 return *this;
736 }
737
738 const char* GetCachedDescriptor() const {
739 return cached_descriptor_;
740 }
741
742 bool operator<(const DexFileAndClassPair& rhs) const {
743 const char* lhsDescriptor = cached_descriptor_;
744 const char* rhsDescriptor = rhs.cached_descriptor_;
745 int cmp = strcmp(lhsDescriptor, rhsDescriptor);
746 if (cmp != 0) {
747 return cmp > 0;
748 }
749 return dex_file_ < rhs.dex_file_;
750 }
751
752 bool DexFileHasMoreClasses() const {
753 return current_class_index_ + 1 < dex_file_->NumClassDefs();
754 }
755
756 DexFileAndClassPair GetNext() const {
757 return DexFileAndClassPair(dex_file_, current_class_index_ + 1, from_loaded_oat_);
758 }
759
760 size_t GetCurrentClassIndex() const {
761 return current_class_index_;
762 }
763
764 bool FromLoadedOat() const {
765 return from_loaded_oat_;
766 }
767
768 const DexFile* GetDexFile() const {
769 return dex_file_;
770 }
771
772 private:
773 static const char* GetClassDescriptor(const DexFile* dex_file, size_t index) {
774 const DexFile::ClassDef& class_def = dex_file->GetClassDef(static_cast<uint16_t>(index));
775 return dex_file->StringByTypeIdx(class_def.class_idx_);
776 }
777
778 const char* cached_descriptor_;
779 const DexFile* dex_file_;
780 size_t current_class_index_;
781 bool from_loaded_oat_; // We only need to compare mismatches between what we load now
782 // and what was loaded before. Any old duplicates must have been
783 // OK, and any new "internal" duplicates are as well (they must
784 // be from multidex, which resolves correctly).
785};
786
787static void AddDexFilesFromOat(const OatFile* oat_file, bool already_loaded,
788 std::priority_queue<DexFileAndClassPair>* heap) {
789 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
790 for (const OatDexFile* oat_dex_file : oat_dex_files) {
791 std::string error;
792 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
793 if (dex_file.get() == nullptr) {
794 LOG(WARNING) << "Could not create dex file from oat file: " << error;
795 } else {
796 if (dex_file->NumClassDefs() > 0U) {
797 heap->emplace(dex_file.release(), 0U, already_loaded);
798 }
799 }
800 }
801}
802
803static void AddNext(const DexFileAndClassPair& original,
804 std::priority_queue<DexFileAndClassPair>* heap) {
805 if (original.DexFileHasMoreClasses()) {
806 heap->push(original.GetNext());
807 } else {
808 // Need to delete the dex file.
809 delete original.GetDexFile();
810 }
811}
812
813static void FreeDexFilesInHeap(std::priority_queue<DexFileAndClassPair>* heap) {
814 while (!heap->empty()) {
815 delete heap->top().GetDexFile();
816 heap->pop();
817 }
818}
819
820bool ClassLinker::HasCollisions(const OatFile* oat_file, std::string* error_msg) {
821 if (!kCheckForDexCollisions) {
822 return false;
823 }
824
825 // Dex files are registered late - once a class is actually being loaded. We have to compare
826 // against the open oat files.
827 ReaderMutexLock mu(Thread::Current(), dex_lock_);
828
829 std::priority_queue<DexFileAndClassPair> heap;
830
831 // Add dex files from already loaded oat files, but skip boot.
832 {
833 // To grab the boot oat, look at the dex files in the boot classpath.
834 const OatFile* boot_oat = nullptr;
835 if (!boot_class_path_.empty()) {
836 const DexFile* boot_dex_file = boot_class_path_[0];
837 // Is it from an oat file?
838 if (boot_dex_file->GetOatDexFile() != nullptr) {
839 boot_oat = boot_dex_file->GetOatDexFile()->GetOatFile();
840 }
841 }
842
843 for (const OatFile* loaded_oat_file : oat_files_) {
844 if (loaded_oat_file == boot_oat) {
845 continue;
846 }
847 AddDexFilesFromOat(loaded_oat_file, true, &heap);
848 }
849 }
850
851 if (heap.empty()) {
852 // No other oat files, return early.
853 return false;
854 }
855
856 // Add dex files from the oat file to check.
857 AddDexFilesFromOat(oat_file, false, &heap);
858
859 // Now drain the heap.
860 while (!heap.empty()) {
861 DexFileAndClassPair compare_pop = heap.top();
862 heap.pop();
863
864 // Compare against the following elements.
865 while (!heap.empty()) {
866 DexFileAndClassPair top = heap.top();
867
868 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
869 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
870 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
871 *error_msg =
872 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s",
873 compare_pop.GetCachedDescriptor(),
874 compare_pop.GetDexFile()->GetLocation().c_str(),
875 top.GetDexFile()->GetLocation().c_str());
876 FreeDexFilesInHeap(&heap);
877 return true;
878 }
879 // Pop it.
880 heap.pop();
881 AddNext(top, &heap);
882 } else {
883 // Something else. Done here.
884 break;
885 }
886 }
887 AddNext(compare_pop, &heap);
888 }
889
890 return false;
891}
892
Richard Uhler66d874d2015-01-15 09:37:19 -0800893std::vector<std::unique_ptr<const DexFile>> ClassLinker::OpenDexFilesFromOat(
894 const char* dex_location, const char* oat_location,
895 std::vector<std::string>* error_msgs) {
896 CHECK(error_msgs != nullptr);
Calin Juravle621962a2014-09-02 15:53:55 +0100897
Richard Uhler66d874d2015-01-15 09:37:19 -0800898 // Verify we aren't holding the mutator lock, which could starve GC if we
899 // have to generate or relocate an oat file.
900 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
901
902 OatFileAssistant oat_file_assistant(dex_location, oat_location, kRuntimeISA,
903 !Runtime::Current()->IsAotCompiler());
904
905 // Lock the target oat location to avoid races generating and loading the
906 // oat file.
907 std::string error_msg;
908 if (!oat_file_assistant.Lock(&error_msg)) {
909 // Don't worry too much if this fails. If it does fail, it's unlikely we
910 // can generate an oat file anyway.
911 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700912 }
913
Richard Uhler66d874d2015-01-15 09:37:19 -0800914 // Check if we already have an up-to-date oat file open.
915 const OatFile* source_oat_file = nullptr;
916 {
917 ReaderMutexLock mu(Thread::Current(), dex_lock_);
918 for (const OatFile* oat_file : oat_files_) {
919 CHECK(oat_file != nullptr);
920 if (oat_file_assistant.GivenOatFileIsUpToDate(*oat_file)) {
921 source_oat_file = oat_file;
922 break;
Andreas Gampe833a4852014-05-21 18:46:59 -0700923 }
924 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700925 }
926
Richard Uhler66d874d2015-01-15 09:37:19 -0800927 // If we didn't have an up-to-date oat file open, try to load one from disk.
928 if (source_oat_file == nullptr) {
929 // Update the oat file on disk if we can. This may fail, but that's okay.
930 // Best effort is all that matters here.
931 if (!oat_file_assistant.MakeUpToDate(&error_msg)) {
932 LOG(WARNING) << error_msg;
Andreas Gampe833a4852014-05-21 18:46:59 -0700933 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700934
Richard Uhler66d874d2015-01-15 09:37:19 -0800935 // Get the oat file on disk.
936 std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
937 if (oat_file.get() != nullptr) {
Andreas Gampeb9aec2c2015-04-23 22:23:47 -0700938 // Take the file only if it has no collisions.
939 if (!HasCollisions(oat_file.get(), &error_msg)) {
940 source_oat_file = oat_file.release();
941 RegisterOatFile(source_oat_file);
942 } else {
943 LOG(WARNING) << "Found duplicate classes, falling back to interpreter mode (if enabled):";
944 LOG(WARNING) << error_msg;
945 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700946 }
947 }
948
Richard Uhler66d874d2015-01-15 09:37:19 -0800949 std::vector<std::unique_ptr<const DexFile>> dex_files;
Andreas Gampe833a4852014-05-21 18:46:59 -0700950
Richard Uhler66d874d2015-01-15 09:37:19 -0800951 // Load the dex files from the oat file.
952 if (source_oat_file != nullptr) {
953 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
954 if (dex_files.empty()) {
955 error_msgs->push_back("Failed to open dex files from "
956 + source_oat_file->GetLocation());
Andreas Gampe833a4852014-05-21 18:46:59 -0700957 }
958 }
959
Richard Uhler66d874d2015-01-15 09:37:19 -0800960 // Fall back to running out of the original dex file if we couldn't load any
961 // dex_files from the oat file.
962 if (dex_files.empty()) {
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700963 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800964 if (!DexFile::Open(dex_location, dex_location, &error_msg, &dex_files)) {
965 LOG(WARNING) << error_msg;
966 error_msgs->push_back("Failed to open dex files from "
967 + std::string(dex_location));
Jean Christophe Beyler24e04aa2014-09-12 12:03:25 -0700968 }
969 } else {
970 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
971 }
Andreas Gampe833a4852014-05-21 18:46:59 -0700972 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800973 return dex_files;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700974}
975
Brian Carlstromae826982011-11-09 01:33:42 -0800976const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700977 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700978 for (size_t i = 0; i < oat_files_.size(); i++) {
979 const OatFile* oat_file = oat_files_[i];
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700980 DCHECK(oat_file != nullptr);
Brian Carlstromae826982011-11-09 01:33:42 -0800981 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700982 return oat_file;
983 }
984 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700985 return nullptr;
Brian Carlstromfad71432011-10-16 20:25:10 -0700986}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700987
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800988void ClassLinker::InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700989 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Andreas Gampe2ed8def2014-08-28 14:41:02 -0700990 DCHECK(obj != nullptr);
991 DCHECK(class_linker != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -0700992 if (obj->IsArtMethod()) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700993 mirror::ArtMethod* method = obj->AsArtMethod();
Ian Rogers848871b2013-08-05 10:56:33 -0700994 if (!method->IsNative()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800995 const size_t pointer_size = class_linker->image_pointer_size_;
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800996 method->SetEntryPointFromInterpreterPtrSize(artInterpreterToInterpreterBridge, pointer_size);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800997 if (!method->IsRuntimeMethod() && method != Runtime::Current()->GetResolutionMethod()) {
Mathieu Chartiera89d7ed2014-12-05 10:57:13 -0800998 method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
999 pointer_size);
Ian Rogers848871b2013-08-05 10:56:33 -07001000 }
1001 }
1002 }
1003}
1004
Mathieu Chartierc7853442015-03-27 14:35:38 -07001005void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
1006 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1007 DCHECK(obj != nullptr);
1008 CHECK(obj->GetClass() != nullptr) << "Null class " << obj;
1009 CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
1010 if (obj->IsClass()) {
1011 auto klass = obj->AsClass();
1012 ArtField* fields[2] = { klass->GetSFields(), klass->GetIFields() };
1013 size_t num_fields[2] = { klass->NumStaticFields(), klass->NumInstanceFields() };
1014 for (size_t i = 0; i < 2; ++i) {
1015 for (size_t j = 0; j < num_fields[i]; ++j) {
1016 CHECK_EQ(fields[i][j].GetDeclaringClass(), klass);
1017 }
1018 }
1019 }
1020}
1021
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001022void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001023 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001024 CHECK(!init_done_);
1025
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001026 Runtime* const runtime = Runtime::Current();
1027 Thread* const self = Thread::Current();
1028 gc::Heap* const heap = runtime->GetHeap();
1029 gc::space::ImageSpace* const space = heap->GetImageSpace();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001030 dex_cache_image_class_lookup_required_ = true;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001031 CHECK(space != nullptr);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001032 OatFile& oat_file = GetImageOatFile(space);
1033 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1034 CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001035 const char* image_file_location = oat_file.GetOatHeader().
1036 GetStoreValueByKey(OatHeader::kImageLocationKey);
1037 CHECK(image_file_location == nullptr || *image_file_location == 0);
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001038 quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
Jeff Hao88474b42013-10-23 16:24:40 -07001039 quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
Andreas Gampe2da88232014-02-27 12:26:20 -08001040 quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
Vladimir Marko8a630572014-04-09 18:45:35 +01001041 quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001042 mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1043 mirror::ObjectArray<mirror::DexCache>* dex_caches =
1044 dex_caches_object->AsObjectArray<mirror::DexCache>();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001045
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001046 StackHandleScope<1> hs(self);
1047 Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1048 space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1049 AsObjectArray<mirror::Class>()));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001050 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Mathieu Chartier02b6a782012-10-26 13:51:26 -07001051
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001052 // Special case of setting up the String class early so that we can test arbitrary objects
1053 // as being Strings or not
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001054 mirror::String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001055
Brian Carlstrom56d947f2013-07-15 13:14:23 -07001056 CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001057 static_cast<uint32_t>(dex_caches->GetLength()));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001058 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001059 StackHandleScope<1> hs2(self);
1060 Handle<mirror::DexCache> dex_cache(hs2.NewHandle(dex_caches->Get(i)));
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001061 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001062 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1063 nullptr);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001064 CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001065 std::string error_msg;
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001066 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
1067 if (dex_file.get() == nullptr) {
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001068 LOG(FATAL) << "Failed to open dex file " << dex_file_location
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001069 << " from within oat file " << oat_file.GetLocation()
1070 << " error '" << error_msg << "'";
Ian Rogerse0a02da2014-12-02 14:10:53 -08001071 UNREACHABLE();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001072 }
Brian Carlstromfddf6f62012-03-15 16:56:45 -07001073
1074 CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1075
Richard Uhlerfbef44d2014-12-23 09:48:51 -08001076 AppendToBootClassPath(*dex_file.get(), dex_cache);
1077 opened_dex_files_.push_back(std::move(dex_file));
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001078 }
1079
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001080 // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1081 // bitmap walk.
Brian Carlstromea46f952013-07-30 01:26:50 -07001082 mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
Mathieu Chartier2d721012014-11-10 11:08:06 -08001083 size_t art_method_object_size = mirror::ArtMethod::GetJavaLangReflectArtMethod()->GetObjectSize();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001084 if (!runtime->IsAotCompiler()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001085 // Aot compiler supports having an image with a different pointer size than the runtime. This
Mathieu Chartier2d721012014-11-10 11:08:06 -08001086 // happens on the host for compile 32 bit tests since we use a 64 bit libart compiler. We may
1087 // also use 32 bit dex2oat on a system with 64 bit apps.
1088 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(sizeof(void*)))
1089 << sizeof(void*);
1090 }
1091 if (art_method_object_size == mirror::ArtMethod::InstanceSize(4)) {
1092 image_pointer_size_ = 4;
1093 } else {
1094 CHECK_EQ(art_method_object_size, mirror::ArtMethod::InstanceSize(8));
1095 image_pointer_size_ = 8;
1096 }
Anwar Ghuloumc4f105d2013-04-10 16:12:11 -07001097
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001098 // Set entry point to interpreter if in InterpretOnly mode.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001099 if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001100 heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -07001101 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001102 if (kSanityCheckObjects) {
1103 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1104 auto* dex_cache = dex_caches->Get(i);
1105 for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1106 auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1107 if (field != nullptr) {
1108 CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1109 }
1110 }
1111 }
1112 heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
1113 }
Brian Carlstroma663ea52011-08-19 23:33:41 -07001114
1115 // reinit class_roots_
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001116 mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001117 class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
Brian Carlstroma663ea52011-08-19 23:33:41 -07001118
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001119 // reinit array_iftable_ from any array class instance, they should be ==
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001120 array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
Mathieu Chartier2d721012014-11-10 11:08:06 -08001121 DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001122 // String class root was set above
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001123 mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
1124 mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001125 mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
1126 mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
1127 mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
1128 mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
Fred Shih4ee7a662014-07-11 09:59:27 -07001129 mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001130 mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1131 mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1132 mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1133 mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1134 mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1135 mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1136 mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1137 mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1138 mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1139 mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -07001140
Ian Rogers98379392014-02-24 16:53:16 -08001141 FinishInit(self);
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -07001142
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001143 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -07001144}
1145
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001146void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001147 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001148 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
1149 visitor, RootInfo(kRootStickyClass));
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001150 if ((flags & kVisitRootFlagAllRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001151 for (GcRoot<mirror::Class>& root : class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001152 buffered_visitor.VisitRoot(root);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001153 root.Read()->VisitFieldRoots(buffered_visitor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001154 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001155 // PreZygote classes can't move so we won't need to update fields' declaring classes.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001156 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001157 buffered_visitor.VisitRoot(root);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001158 root.Read()->VisitFieldRoots(buffered_visitor);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001159 }
1160 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001161 for (auto& root : new_class_roots_) {
1162 mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
Mathieu Chartierc7853442015-03-27 14:35:38 -07001163 old_ref->VisitFieldRoots(buffered_visitor);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001164 root.VisitRoot(visitor, RootInfo(kRootStickyClass));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001165 mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001166 if (UNLIKELY(new_ref != old_ref)) {
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001167 // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1168 // corresponding object. This is slow, but luckily for us, this may only happen with a
1169 // concurrent moving GC.
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001170 auto it = class_table_.Find(GcRoot<mirror::Class>(old_ref));
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -08001171 DCHECK(it != class_table_.end());
1172 *it = GcRoot<mirror::Class>(new_ref);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001173 }
1174 }
1175 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001176 buffered_visitor.Flush(); // Flush before clearing new_class_roots_.
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001177 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1178 new_class_roots_.clear();
1179 }
1180 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1181 log_new_class_table_roots_ = true;
1182 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1183 log_new_class_table_roots_ = false;
1184 }
1185 // We deliberately ignore the class roots in the image since we
1186 // handle image roots by using the MS/CMS rescanning of dirty cards.
1187}
1188
Brian Carlstroma663ea52011-08-19 23:33:41 -07001189// Keep in sync with InitCallback. Anything we visit, we need to
1190// reinit references to when reinitializing a ClassLinker from a
1191// mapped image.
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001192void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
1193 class_roots_.VisitRoot(visitor, RootInfo(kRootVMInternal));
1194 Thread* const self = Thread::Current();
Elliott Hughesf8349362012-06-18 15:00:06 -07001195 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07001196 ReaderMutexLock mu(self, dex_lock_);
Mathieu Chartier893263b2014-03-04 11:07:42 -08001197 if ((flags & kVisitRootFlagAllRoots) != 0) {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07001198 for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001199 dex_cache.VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001200 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001201 } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1202 for (size_t index : new_dex_cache_roots_) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001203 dex_caches_[index].VisitRoot(visitor, RootInfo(kRootVMInternal));
Mathieu Chartierc4621982013-09-16 19:43:47 -07001204 }
Elliott Hughesf8349362012-06-18 15:00:06 -07001205 }
Mathieu Chartier893263b2014-03-04 11:07:42 -08001206 if ((flags & kVisitRootFlagClearRootLog) != 0) {
1207 new_dex_cache_roots_.clear();
1208 }
1209 if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1210 log_new_dex_caches_roots_ = true;
1211 } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1212 log_new_dex_caches_roots_ = false;
1213 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001214 }
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001215 VisitClassRoots(visitor, flags);
1216 array_iftable_.VisitRoot(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001217 for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001218 find_array_class_cache_[i].VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
Ian Rogers98379392014-02-24 16:53:16 -08001219 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001220}
1221
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001222void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1223 if (dex_cache_image_class_lookup_required_) {
1224 MoveImageClassesToClassTable();
Elliott Hughesa2155262011-11-16 16:26:58 -08001225 }
Ian Rogersdbf3be02014-08-29 15:40:08 -07001226 // TODO: why isn't this a ReaderMutexLock?
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001227 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001228 for (GcRoot<mirror::Class>& root : class_table_) {
1229 if (!visitor(root.Read(), arg)) {
1230 return;
1231 }
1232 }
1233 for (GcRoot<mirror::Class>& root : pre_zygote_class_table_) {
1234 if (!visitor(root.Read(), arg)) {
Elliott Hughesa2155262011-11-16 16:26:58 -08001235 return;
1236 }
1237 }
1238}
1239
Ian Rogersdbf3be02014-08-29 15:40:08 -07001240static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001241 std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001242 classes->insert(c);
1243 return true;
1244}
1245
Ian Rogersdbf3be02014-08-29 15:40:08 -07001246struct GetClassesVisitorArrayArg {
1247 Handle<mirror::ObjectArray<mirror::Class>>* classes;
1248 int32_t index;
1249 bool success;
1250};
1251
1252static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1253 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1254 GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1255 if (arg->index < (*arg->classes)->GetLength()) {
1256 (*arg->classes)->Set(arg->index, c);
1257 arg->index++;
1258 return true;
1259 } else {
1260 arg->success = false;
1261 return false;
1262 }
1263}
1264
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001265void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
Ian Rogersdbf3be02014-08-29 15:40:08 -07001266 // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1267 // is avoiding duplicates.
1268 if (!kMovingClasses) {
1269 std::set<mirror::Class*> classes;
1270 VisitClasses(GetClassesVisitorSet, &classes);
1271 for (mirror::Class* klass : classes) {
1272 if (!visitor(klass, arg)) {
1273 return;
1274 }
1275 }
1276 } else {
1277 Thread* self = Thread::Current();
1278 StackHandleScope<1> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001279 MutableHandle<mirror::ObjectArray<mirror::Class>> classes =
Ian Rogersdbf3be02014-08-29 15:40:08 -07001280 hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1281 GetClassesVisitorArrayArg local_arg;
1282 local_arg.classes = &classes;
1283 local_arg.success = false;
1284 // We size the array assuming classes won't be added to the class table during the visit.
1285 // If this assumption fails we iterate again.
1286 while (!local_arg.success) {
1287 size_t class_table_size;
1288 {
Ian Rogers7b078e82014-09-10 14:44:24 -07001289 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08001290 class_table_size = class_table_.Size() + pre_zygote_class_table_.Size();
Ian Rogersdbf3be02014-08-29 15:40:08 -07001291 }
1292 mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1293 mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1294 classes.Assign(
1295 mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1296 CHECK(classes.Get() != nullptr); // OOME.
1297 local_arg.index = 0;
1298 local_arg.success = true;
1299 VisitClasses(GetClassesVisitorArray, &local_arg);
1300 }
1301 for (int32_t i = 0; i < classes->GetLength(); ++i) {
1302 // If the class table shrank during creation of the clases array we expect null elements. If
1303 // the class table grew then the loop repeats. If classes are created after the loop has
1304 // finished then we don't visit.
1305 mirror::Class* klass = classes->Get(i);
1306 if (klass != nullptr && !visitor(klass, arg)) {
1307 return;
1308 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001309 }
1310 }
1311}
1312
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001313ClassLinker::~ClassLinker() {
Brian Carlstromea46f952013-07-30 01:26:50 -07001314 mirror::ArtMethod::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001315 mirror::Class::ResetClass();
1316 mirror::Constructor::ResetClass();
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07001317 mirror::Field::ResetClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001318 mirror::Method::ResetClass();
1319 mirror::Reference::ResetClass();
1320 mirror::StackTraceElement::ResetClass();
1321 mirror::String::ResetClass();
1322 mirror::Throwable::ResetClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001323 mirror::BooleanArray::ResetArrayClass();
1324 mirror::ByteArray::ResetArrayClass();
1325 mirror::CharArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001326 mirror::Constructor::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001327 mirror::DoubleArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001328 mirror::Field::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001329 mirror::FloatArray::ResetArrayClass();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07001330 mirror::Method::ResetArrayClass();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001331 mirror::IntArray::ResetArrayClass();
1332 mirror::LongArray::ResetArrayClass();
1333 mirror::ShortArray::ResetArrayClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -07001334 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001335}
1336
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001337mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001338 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001339 StackHandleScope<16> hs(self);
1340 Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1341 Handle<mirror::DexCache> dex_cache(
1342 hs.NewHandle(down_cast<mirror::DexCache*>(
1343 heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1344 VoidFunctor()))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001345 if (dex_cache.Get() == nullptr) {
1346 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001347 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001348 Handle<mirror::String>
1349 location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001350 if (location.Get() == nullptr) {
1351 return nullptr;
Elliott Hughes30646832011-10-13 16:59:46 -07001352 }
Ian Rogers700a4022014-05-19 16:49:03 -07001353 Handle<mirror::ObjectArray<mirror::String>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001354 strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001355 if (strings.Get() == nullptr) {
1356 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001357 }
Ian Rogers700a4022014-05-19 16:49:03 -07001358 Handle<mirror::ObjectArray<mirror::Class>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001359 types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001360 if (types.Get() == nullptr) {
1361 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001362 }
Ian Rogers700a4022014-05-19 16:49:03 -07001363 Handle<mirror::ObjectArray<mirror::ArtMethod>>
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001364 methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001365 if (methods.Get() == nullptr) {
1366 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001367 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001368 Handle<mirror::Array> fields;
1369 if (image_pointer_size_ == 8) {
1370 fields = hs.NewHandle<mirror::Array>(mirror::LongArray::Alloc(self, dex_file.NumFieldIds()));
1371 } else {
1372 fields = hs.NewHandle<mirror::Array>(mirror::IntArray::Alloc(self, dex_file.NumFieldIds()));
1373 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001374 if (fields.Get() == nullptr) {
1375 return nullptr;
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001376 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001377 dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1378 fields.Get());
1379 return dex_cache.Get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001380}
1381
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001382mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
Ian Rogers6fac4472014-02-25 17:01:10 -08001383 uint32_t class_size) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001384 DCHECK_GE(class_size, sizeof(mirror::Class));
Ian Rogers1d54e732013-05-02 21:10:01 -07001385 gc::Heap* heap = Runtime::Current()->GetHeap();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001386 mirror::Class::InitializeClassVisitor visitor(class_size);
Mathieu Chartier52e4b432014-06-10 11:22:31 -07001387 mirror::Object* k = kMovingClasses ?
Brian Carlstromf3632832014-05-20 15:36:53 -07001388 heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1389 heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
Ian Rogers6fac4472014-02-25 17:01:10 -08001390 if (UNLIKELY(k == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001391 CHECK(self->IsExceptionPending()); // OOME.
Ian Rogers6fac4472014-02-25 17:01:10 -08001392 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001393 }
Ian Rogers6fac4472014-02-25 17:01:10 -08001394 return k->AsClass();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001395}
1396
Ian Rogers6fac4472014-02-25 17:01:10 -08001397mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
Ian Rogers50b35e22012-10-04 10:09:15 -07001398 return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001399}
1400
Brian Carlstromea46f952013-07-30 01:26:50 -07001401mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001402 return down_cast<mirror::ArtMethod*>(
Mathieu Chartiercbb2d202013-11-14 17:45:16 -08001403 GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
Mathieu Chartier66f19252012-09-18 08:57:04 -07001404}
1405
Mathieu Chartier590fee92013-09-13 13:46:47 -07001406mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1407 Thread* self, size_t length) {
1408 return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1409 self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001410}
1411
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001412mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1413 mirror::Class* klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001414 DCHECK(klass != nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001415
1416 // For temporary classes we must wait for them to be retired.
1417 if (init_done_ && klass->IsTemp()) {
1418 CHECK(!klass->IsResolved());
1419 if (klass->IsErroneous()) {
1420 ThrowEarlierClassFailure(klass);
1421 return nullptr;
1422 }
1423 StackHandleScope<1> hs(self);
1424 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1425 ObjectLock<mirror::Class> lock(self, h_class);
1426 // Loop and wait for the resolving thread to retire this class.
1427 while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1428 lock.WaitIgnoringInterrupts();
1429 }
1430 if (h_class->IsErroneous()) {
1431 ThrowEarlierClassFailure(h_class.Get());
1432 return nullptr;
1433 }
1434 CHECK(h_class->IsRetired());
1435 // Get the updated class from class table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001436 klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
1437 h_class.Get()->GetClassLoader());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001438 }
1439
Brian Carlstromaded5f72011-10-07 17:15:04 -07001440 // Wait for the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001441 if (!klass->IsResolved() && !klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001442 StackHandleScope<1> hs(self);
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001443 HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1444 ObjectLock<mirror::Class> lock(self, h_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001445 // Check for circular dependencies between classes.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001446 if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1447 ThrowClassCircularityError(h_class.Get());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001448 mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001449 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001450 }
1451 // Wait for the pending initialization to complete.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001452 while (!h_class->IsResolved() && !h_class->IsErroneous()) {
Ian Rogers05f30572013-02-20 12:13:11 -08001453 lock.WaitIgnoringInterrupts();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001454 }
1455 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001456
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001457 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001458 ThrowEarlierClassFailure(klass);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08001459 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001460 }
1461 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001462 CHECK(klass->IsResolved()) << PrettyClass(klass);
Ian Rogers62d6c772013-02-27 08:32:07 -08001463 self->AssertNoPendingException();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001464 return klass;
1465}
1466
Ian Rogers68b56852014-08-29 20:19:11 -07001467typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1468
1469// Search a collection of DexFiles for a descriptor
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001470ClassPathEntry FindInClassPath(const char* descriptor,
1471 size_t hash, const std::vector<const DexFile*>& class_path) {
1472 for (const DexFile* dex_file : class_path) {
1473 const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001474 if (dex_class_def != nullptr) {
Ian Rogers68b56852014-08-29 20:19:11 -07001475 return ClassPathEntry(dex_file, dex_class_def);
1476 }
1477 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001478 return ClassPathEntry(nullptr, nullptr);
Ian Rogers68b56852014-08-29 20:19:11 -07001479}
1480
Andreas Gampef865ea92015-04-13 22:14:19 -07001481static bool IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1482 mirror::ClassLoader* class_loader)
1483 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1484 return class_loader == nullptr ||
1485 class_loader->GetClass() ==
1486 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader);
1487}
1488
1489bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1490 Thread* self, const char* descriptor,
1491 size_t hash,
1492 Handle<mirror::ClassLoader> class_loader,
1493 mirror::Class** result) {
1494 // Termination case: boot class-loader.
1495 if (IsBootClassLoader(soa, class_loader.Get())) {
1496 // The boot class loader, search the boot class path.
1497 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
1498 if (pair.second != nullptr) {
1499 mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
1500 if (klass != nullptr) {
1501 *result = EnsureResolved(self, descriptor, klass);
1502 } else {
1503 *result = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(),
1504 *pair.first, *pair.second);
1505 }
1506 if (*result == nullptr) {
1507 CHECK(self->IsExceptionPending()) << descriptor;
1508 self->ClearException();
1509 }
Ian Rogers32427292014-11-19 14:05:21 -08001510 } else {
Andreas Gampef865ea92015-04-13 22:14:19 -07001511 *result = nullptr;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001512 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001513 return true;
1514 }
1515
1516 // Unsupported class-loader?
1517 if (class_loader->GetClass() !=
1518 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
1519 *result = nullptr;
1520 return false;
1521 }
1522
1523 // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
1524 StackHandleScope<4> hs(self);
1525 Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
1526 bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
1527
1528 if (!recursive_result) {
1529 // Something wrong up the chain.
1530 return false;
1531 }
1532
1533 if (*result != nullptr) {
1534 // Found the class up the chain.
1535 return true;
1536 }
1537
1538 // Handle this step.
1539 // Handle as if this is the child PathClassLoader.
1540 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
1541 // We need to get the DexPathList and loop through it.
1542 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
1543 ArtField* const dex_file_field =
1544 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1545 mirror::Object* dex_path_list =
1546 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
1547 GetObject(class_loader.Get());
1548 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
1549 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1550 mirror::Object* dex_elements_obj =
1551 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1552 GetObject(dex_path_list);
1553 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1554 // at the mCookie which is a DexFile vector.
1555 if (dex_elements_obj != nullptr) {
1556 Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
1557 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
1558 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
1559 mirror::Object* element = dex_elements->GetWithoutChecks(i);
1560 if (element == nullptr) {
1561 // Should never happen, fall back to java code to throw a NPE.
1562 break;
1563 }
1564 mirror::Object* dex_file = dex_file_field->GetObject(element);
1565 if (dex_file != nullptr) {
1566 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
1567 if (long_array == nullptr) {
1568 // This should never happen so log a warning.
1569 LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001570 break;
1571 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001572 int32_t long_array_size = long_array->GetLength();
1573 for (int32_t j = 0; j < long_array_size; ++j) {
1574 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
1575 long_array->GetWithoutChecks(j)));
1576 const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
1577 if (dex_class_def != nullptr) {
1578 RegisterDexFile(*cp_dex_file);
1579 mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
1580 *cp_dex_file, *dex_class_def);
1581 if (klass == nullptr) {
1582 CHECK(self->IsExceptionPending()) << descriptor;
1583 self->ClearException();
1584 // TODO: Is it really right to break here, and not check the other dex files?
1585 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001586 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001587 *result = klass;
1588 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001589 }
1590 }
1591 }
1592 }
1593 }
Ian Rogers32427292014-11-19 14:05:21 -08001594 self->AssertNoPendingException();
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001595 }
Andreas Gampef865ea92015-04-13 22:14:19 -07001596
1597 // Result is still null from the parent call, no need to set it again...
1598 return true;
Mathieu Chartierab0ed822014-09-11 14:21:41 -07001599}
1600
Ian Rogers98379392014-02-24 16:53:16 -08001601mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001602 Handle<mirror::ClassLoader> class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001603 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Ian Rogers98379392014-02-24 16:53:16 -08001604 DCHECK(self != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001605 self->AssertNoPendingException();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001606 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001607 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1608 // for primitive classes that aren't backed by dex files.
1609 return FindPrimitiveClass(descriptor[0]);
1610 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001611 const size_t hash = ComputeModifiedUtf8Hash(descriptor);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001612 // Find the class in the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001613 mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
Ian Rogers68b56852014-08-29 20:19:11 -07001614 if (klass != nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001615 return EnsureResolved(self, descriptor, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001616 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001617 // Class is not yet loaded.
1618 if (descriptor[0] == '[') {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001619 return CreateArrayClass(self, descriptor, hash, class_loader);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001620 } else if (class_loader.Get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001621 // The boot class loader, search the boot class path.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001622 ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
Ian Rogers68b56852014-08-29 20:19:11 -07001623 if (pair.second != nullptr) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001624 return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
Ian Rogers7b078e82014-09-10 14:44:24 -07001625 *pair.second);
Ian Rogers63557452014-06-04 16:57:15 -07001626 } else {
1627 // The boot class loader is searched ahead of the application class loader, failures are
1628 // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
1629 // trigger the chaining with a proper stack trace.
1630 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001631 self->SetException(pre_allocated);
Ian Rogers63557452014-06-04 16:57:15 -07001632 return nullptr;
Jesse Wilson47daf872011-11-23 11:42:45 -05001633 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001634 } else {
Ian Rogers98379392014-02-24 16:53:16 -08001635 ScopedObjectAccessUnchecked soa(self);
Andreas Gampef865ea92015-04-13 22:14:19 -07001636 mirror::Class* cp_klass;
1637 if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
1638 // The chain was understood. So the value in cp_klass is either the class we were looking
1639 // for, or not found.
1640 if (cp_klass != nullptr) {
1641 return cp_klass;
1642 }
1643 // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
1644 // and the branch above. TODO: throw the right exception here.
1645
1646 // We'll let the Java-side rediscover all this and throw the exception with the right stack
1647 // trace.
Mathieu Chartier6bcae8f2014-09-04 18:33:17 -07001648 }
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07001649
1650 if (Runtime::Current()->IsAotCompiler()) {
1651 // Oops, compile-time, can't run actual class-loader code.
1652 mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
1653 self->SetException(pre_allocated);
1654 return nullptr;
1655 }
1656
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001657 ScopedLocalRef<jobject> class_loader_object(soa.Env(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001658 soa.AddLocalReference<jobject>(class_loader.Get()));
Elliott Hughes95572412011-12-13 18:14:20 -08001659 std::string class_name_string(DescriptorToDot(descriptor));
Ian Rogers68b56852014-08-29 20:19:11 -07001660 ScopedLocalRef<jobject> result(soa.Env(), nullptr);
Ian Rogers365c1022012-06-22 15:05:28 -07001661 {
1662 ScopedThreadStateChange tsc(self, kNative);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001663 ScopedLocalRef<jobject> class_name_object(soa.Env(),
1664 soa.Env()->NewStringUTF(class_name_string.c_str()));
Ian Rogers68b56852014-08-29 20:19:11 -07001665 if (class_name_object.get() == nullptr) {
Ian Rogers63557452014-06-04 16:57:15 -07001666 DCHECK(self->IsExceptionPending()); // OOME.
Ian Rogers68b56852014-08-29 20:19:11 -07001667 return nullptr;
Ian Rogers365c1022012-06-22 15:05:28 -07001668 }
Ian Rogers68b56852014-08-29 20:19:11 -07001669 CHECK(class_loader_object.get() != nullptr);
Ian Rogers00f7d0e2012-07-19 15:28:27 -07001670 result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1671 WellKnownClasses::java_lang_ClassLoader_loadClass,
1672 class_name_object.get()));
Jesse Wilson47daf872011-11-23 11:42:45 -05001673 }
Ian Rogers98379392014-02-24 16:53:16 -08001674 if (self->IsExceptionPending()) {
Elliott Hughes748382f2012-01-26 18:07:38 -08001675 // If the ClassLoader threw, pass that exception up.
Ian Rogers68b56852014-08-29 20:19:11 -07001676 return nullptr;
1677 } else if (result.get() == nullptr) {
Ian Rogerscab01012012-01-10 17:35:46 -08001678 // broken loader - throw NPE to be compatible with Dalvik
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001679 ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
1680 class_name_string.c_str()).c_str());
Ian Rogers68b56852014-08-29 20:19:11 -07001681 return nullptr;
Ian Rogers761bfa82012-01-11 10:14:05 -08001682 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001683 // success, return mirror::Class*
1684 return soa.Decode<mirror::Class*>(result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001685 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001686 }
Ian Rogers07140832014-09-30 15:43:59 -07001687 UNREACHABLE();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001688}
1689
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001690mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07001691 Handle<mirror::ClassLoader> class_loader,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001692 const DexFile& dex_file,
1693 const DexFile::ClassDef& dex_class_def) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001694 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001695 auto klass = hs.NewHandle<mirror::Class>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001696
Brian Carlstromaded5f72011-10-07 17:15:04 -07001697 // Load the class from the dex file.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001698 if (UNLIKELY(!init_done_)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001699 // finish up init of hand crafted class_roots_
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001700 if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001701 klass.Assign(GetClassRoot(kJavaLangObject));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001702 } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001703 klass.Assign(GetClassRoot(kJavaLangClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001704 } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001705 klass.Assign(GetClassRoot(kJavaLangString));
Fred Shih4ee7a662014-07-11 09:59:27 -07001706 } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
1707 klass.Assign(GetClassRoot(kJavaLangRefReference));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001708 } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001709 klass.Assign(GetClassRoot(kJavaLangDexCache));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07001710 } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001711 klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001712 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001713 }
1714
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001715 if (klass.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001716 // Allocate a class with the status of not ready.
1717 // Interface object should get the right size here. Regular class will
1718 // figure out the right size later and be replaced with one of the right
1719 // size when the class becomes resolved.
1720 klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001721 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001722 if (UNLIKELY(klass.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07001723 CHECK(self->IsExceptionPending()); // Expect an OOME.
Ian Rogersc114b5f2014-07-21 08:55:01 -07001724 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07001725 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001726 klass->SetDexCache(FindDexCache(dex_file));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001727
1728 SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
1729
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07001730 ObjectLock<mirror::Class> lock(self, klass);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001731 klass->SetClinitThreadId(self->GetTid());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001732
Mathieu Chartier590fee92013-09-13 13:46:47 -07001733 // Add the newly loaded class to the loaded classes table.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08001734 mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
Ian Rogersc114b5f2014-07-21 08:55:01 -07001735 if (existing != nullptr) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001736 // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1737 // this thread to block.
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001738 return EnsureResolved(self, descriptor, existing);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001739 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001740
Mathieu Chartierc7853442015-03-27 14:35:38 -07001741 // Load the fields and other things after we are inserted in the table. This is so that we don't
1742 // end up allocating unfree-able linear alloc resources and then lose the race condition. The
1743 // other reason is that the field roots are only visited from the class table. So we need to be
1744 // inserted before we allocate / fill in these fields.
1745 LoadClass(self, dex_file, dex_class_def, klass);
1746 if (self->IsExceptionPending()) {
1747 // An exception occured during load, set status to erroneous while holding klass' lock in case
1748 // notification is necessary.
1749 if (!klass->IsErroneous()) {
1750 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
1751 }
1752 return nullptr;
1753 }
1754
Brian Carlstromaded5f72011-10-07 17:15:04 -07001755 // Finish loading (if necessary) by finding parents
1756 CHECK(!klass->IsLoaded());
1757 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1758 // Loading failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001759 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001760 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001761 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001762 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001763 }
1764 CHECK(klass->IsLoaded());
1765 // Link the class (if necessary)
1766 CHECK(!klass->IsResolved());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001767 // TODO: Use fast jobjects?
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001768 auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001769
1770 mirror::Class* new_class = nullptr;
1771 if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001772 // Linking failed.
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001773 if (!klass->IsErroneous()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07001774 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersecd4d9a2014-07-22 00:59:52 -07001775 }
Ian Rogersc114b5f2014-07-21 08:55:01 -07001776 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001777 }
Mathieu Chartier524507a2014-08-27 15:28:28 -07001778 self->AssertNoPendingException();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001779 CHECK(new_class != nullptr) << descriptor;
1780 CHECK(new_class->IsResolved()) << descriptor;
1781
1782 Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001783
Sebastien Hertza8a697f2015-01-15 12:28:47 +01001784 // Instrumentation may have updated entrypoints for all methods of all
1785 // classes. However it could not update methods of this class while we
1786 // were loading it. Now the class is resolved, we can update entrypoints
1787 // as required by instrumentation.
1788 if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
1789 // We must be in the kRunnable state to prevent instrumentation from
1790 // suspending all threads to update entrypoints while we are doing it
1791 // for this class.
1792 DCHECK_EQ(self->GetState(), kRunnable);
1793 Runtime::Current()->GetInstrumentation()->InstallStubsForClass(new_class_h.Get());
1794 }
1795
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001796 /*
1797 * We send CLASS_PREPARE events to the debugger from here. The
1798 * definition of "preparation" is creating the static fields for a
1799 * class and initializing them to the standard default values, but not
1800 * executing any code (that comes later, during "initialization").
1801 *
1802 * We did the static preparation in LinkClass.
1803 *
1804 * The class has been prepared and resolved but possibly not yet verified
1805 * at this point.
1806 */
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001807 Dbg::PostClassPrepare(new_class_h.Get());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001808
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001809 return new_class_h.Get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001810}
1811
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001812uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
1813 const DexFile::ClassDef& dex_class_def) {
Ian Rogers13735952014-10-08 12:43:28 -07001814 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001815 size_t num_ref = 0;
Fred Shih37f05ef2014-07-16 18:38:08 -07001816 size_t num_8 = 0;
1817 size_t num_16 = 0;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001818 size_t num_32 = 0;
1819 size_t num_64 = 0;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001820 if (class_data != nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07001821 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1822 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001823 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001824 char c = descriptor[0];
Fred Shih37f05ef2014-07-16 18:38:08 -07001825 switch (c) {
1826 case 'L':
1827 case '[':
1828 num_ref++;
1829 break;
1830 case 'J':
1831 case 'D':
1832 num_64++;
1833 break;
1834 case 'I':
1835 case 'F':
1836 num_32++;
1837 break;
1838 case 'S':
1839 case 'C':
1840 num_16++;
1841 break;
1842 case 'B':
1843 case 'Z':
1844 num_8++;
1845 break;
1846 default:
1847 LOG(FATAL) << "Unknown descriptor: " << c;
Ian Rogerse0a02da2014-12-02 14:10:53 -08001848 UNREACHABLE();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001849 }
1850 }
1851 }
Fred Shih37f05ef2014-07-16 18:38:08 -07001852 return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001853}
1854
Ian Rogers97b52f82014-08-14 11:34:07 -07001855OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
1856 bool* found) {
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001857 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Richard Uhler07b3c232015-03-31 15:57:54 -07001858 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001859 if (oat_dex_file == nullptr) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001860 *found = false;
1861 return OatFile::OatClass::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001862 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001863 *found = true;
1864 return oat_dex_file->GetOatClass(class_def_idx);
Ian Rogers19846512012-02-24 11:42:47 -08001865}
1866
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001867static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1868 uint32_t method_idx) {
1869 const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
Ian Rogers13735952014-10-08 12:43:28 -07001870 const uint8_t* class_data = dex_file.GetClassData(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07001871 CHECK(class_data != nullptr);
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001872 ClassDataItemIterator it(dex_file, class_data);
1873 // Skip fields
1874 while (it.HasNextStaticField()) {
1875 it.Next();
1876 }
1877 while (it.HasNextInstanceField()) {
1878 it.Next();
1879 }
1880 // Process methods
1881 size_t class_def_method_index = 0;
1882 while (it.HasNextDirectMethod()) {
1883 if (it.GetMemberIndex() == method_idx) {
1884 return class_def_method_index;
1885 }
1886 class_def_method_index++;
1887 it.Next();
1888 }
1889 while (it.HasNextVirtualMethod()) {
1890 if (it.GetMemberIndex() == method_idx) {
1891 return class_def_method_index;
1892 }
1893 class_def_method_index++;
1894 it.Next();
1895 }
1896 DCHECK(!it.HasNext());
1897 LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
Ian Rogerse0a02da2014-12-02 14:10:53 -08001898 UNREACHABLE();
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001899}
1900
Ian Rogers97b52f82014-08-14 11:34:07 -07001901const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
Ian Rogers19846512012-02-24 11:42:47 -08001902 // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
Ian Rogersfb6adba2012-03-04 21:51:51 -08001903 // method for direct methods (or virtual methods made direct).
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001904 mirror::Class* declaring_class = method->GetDeclaringClass();
Ian Rogersfb6adba2012-03-04 21:51:51 -08001905 size_t oat_method_index;
1906 if (method->IsStatic() || method->IsDirect()) {
1907 // Simple case where the oat method index was stashed at load time.
1908 oat_method_index = method->GetMethodIndex();
1909 } else {
1910 // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1911 // by search for its position in the declared virtual methods.
1912 oat_method_index = declaring_class->NumDirectMethods();
1913 size_t end = declaring_class->NumVirtualMethods();
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001914 bool found_virtual = false;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001915 for (size_t i = 0; i < end; i++) {
Jeff Hao68caf9e2014-09-03 13:48:16 -07001916 // Check method index instead of identity in case of duplicate method definitions.
1917 if (method->GetDexMethodIndex() ==
1918 declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001919 found_virtual = true;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001920 break;
1921 }
Ian Rogersf320b632012-03-13 18:47:47 -07001922 oat_method_index++;
Ian Rogersfb6adba2012-03-04 21:51:51 -08001923 }
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001924 CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
1925 << PrettyMethod(method);
Ian Rogersfb6adba2012-03-04 21:51:51 -08001926 }
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001927 DCHECK_EQ(oat_method_index,
1928 GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001929 method->GetDeclaringClass()->GetDexClassDefIndex(),
Mathieu Chartiere35517a2012-10-30 18:49:55 -07001930 method->GetDexMethodIndex()));
Ian Rogers97b52f82014-08-14 11:34:07 -07001931 OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1932 declaring_class->GetDexClassDefIndex(),
1933 found);
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001934 if (!(*found)) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001935 return OatFile::OatMethod::Invalid();
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001936 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001937 return oat_class.GetOatMethod(oat_method_index);
TDYa12785321912012-04-01 15:24:56 -07001938}
1939
1940// Special case to get oat code without overwriting a trampoline.
Ian Rogersef7d42f2014-01-06 12:55:46 -08001941const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
Ian Rogers62d6c772013-02-27 08:32:07 -08001942 CHECK(!method->IsAbstract()) << PrettyMethod(method);
Jeff Hao8df6cea2013-07-29 13:54:48 -07001943 if (method->IsProxyMethod()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08001944 return GetQuickProxyInvokeHandler();
Jeff Hao8df6cea2013-07-29 13:54:48 -07001945 }
Ian Rogers97b52f82014-08-14 11:34:07 -07001946 bool found;
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001947 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1948 if (found) {
1949 auto* code = oat_method.GetQuickCode();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001950 if (code != nullptr) {
1951 return code;
Mathieu Chartier2535abe2015-02-17 10:38:49 -08001952 }
1953 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001954 jit::Jit* const jit = Runtime::Current()->GetJit();
1955 if (jit != nullptr) {
1956 auto* code = jit->GetCodeCache()->GetCodeFor(method);
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001957 if (code != nullptr) {
1958 return code;
1959 }
1960 }
1961 if (method->IsNative()) {
1962 // No code and native? Use generic trampoline.
1963 return GetQuickGenericJniStub();
1964 }
1965 return GetQuickToInterpreterBridge();
TDYa12785321912012-04-01 15:24:56 -07001966}
1967
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001968const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
1969 if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
1970 return nullptr;
1971 }
Mathieu Chartierc0d5f892015-02-25 13:22:57 -08001972 bool found;
1973 OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
1974 if (found) {
1975 return oat_method.GetQuickCode();
1976 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001977 jit::Jit* jit = Runtime::Current()->GetJit();
1978 if (jit != nullptr) {
1979 auto* code = jit->GetCodeCache()->GetCodeFor(method);
1980 if (code != nullptr) {
1981 return code;
1982 }
1983 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001984 return nullptr;
Hiroshi Yamauchi9bdec882014-08-15 17:11:12 -07001985}
1986
Ian Rogersef7d42f2014-01-06 12:55:46 -08001987const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1988 uint32_t method_idx) {
Ian Rogers97b52f82014-08-14 11:34:07 -07001989 bool found;
1990 OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
1991 if (!found) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01001992 return nullptr;
1993 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07001994 uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001995 return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
Ian Rogersef7d42f2014-01-06 12:55:46 -08001996}
1997
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02001998// Returns true if the method must run with interpreter, false otherwise.
Elliott Hughes956af0f2014-12-11 14:34:28 -08001999static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code)
Brian Carlstromf3632832014-05-20 15:36:53 -07002000 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08002001 if (quick_code == nullptr) {
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002002 // No code: need interpreter.
Andreas Gampe2da88232014-02-27 12:26:20 -08002003 // May return true for native code, in the case of generic JNI
2004 // DCHECK(!method->IsNative());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002005 return true;
2006 }
2007 // If interpreter mode is enabled, every method (except native and proxy) must
2008 // be run with interpreter.
2009 return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2010 !method->IsNative() && !method->IsProxyMethod();
2011}
2012
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002013void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
Brian Carlstrom073278c2014-02-19 15:21:21 -08002014 DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
Ian Rogers1c829822013-09-30 18:18:50 -07002015 if (klass->NumDirectMethods() == 0) {
2016 return; // No direct methods => no static methods.
Ian Rogers19846512012-02-24 11:42:47 -08002017 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002018 Runtime* runtime = Runtime::Current();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002019 if (!runtime->IsStarted()) {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002020 if (runtime->IsAotCompiler() || runtime->GetHeap()->HasImageSpace()) {
Alex Light64ad14d2014-08-19 14:23:13 -07002021 return; // OAT file unavailable.
2022 }
Ian Rogers19846512012-02-24 11:42:47 -08002023 }
Alex Light64ad14d2014-08-19 14:23:13 -07002024
Mathieu Chartierf8322842014-05-16 10:59:25 -07002025 const DexFile& dex_file = klass->GetDexFile();
2026 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Ian Rogers1c829822013-09-30 18:18:50 -07002027 CHECK(dex_class_def != nullptr);
Ian Rogers13735952014-10-08 12:43:28 -07002028 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Ian Rogers1c829822013-09-30 18:18:50 -07002029 // There should always be class data if there were direct methods.
2030 CHECK(class_data != nullptr) << PrettyDescriptor(klass);
Ian Rogers19846512012-02-24 11:42:47 -08002031 ClassDataItemIterator it(dex_file, class_data);
2032 // Skip fields
2033 while (it.HasNextStaticField()) {
2034 it.Next();
2035 }
2036 while (it.HasNextInstanceField()) {
2037 it.Next();
2038 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002039 bool has_oat_class;
2040 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2041 &has_oat_class);
Ian Rogers1c829822013-09-30 18:18:50 -07002042 // Link the code of methods skipped by LinkCode.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002043 for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
Brian Carlstromea46f952013-07-30 01:26:50 -07002044 mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002045 if (!method->IsStatic()) {
2046 // Only update static methods.
2047 continue;
Ian Rogers19846512012-02-24 11:42:47 -08002048 }
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002049 const void* quick_code = nullptr;
2050 if (has_oat_class) {
2051 OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002052 quick_code = oat_method.GetQuickCode();
2053 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002054 const bool enter_interpreter = NeedsInterpreter(method, quick_code);
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002055 if (enter_interpreter) {
2056 // Use interpreter entry point.
Ian Rogers1a570662014-03-12 01:02:21 -07002057 // Check whether the method is native, in which case it's generic JNI.
Elliott Hughes956af0f2014-12-11 14:34:28 -08002058 if (quick_code == nullptr && method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002059 quick_code = GetQuickGenericJniStub();
Andreas Gampe2da88232014-02-27 12:26:20 -08002060 } else {
2061 quick_code = GetQuickToInterpreterBridge();
2062 }
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002063 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08002064 runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
Ian Rogers19846512012-02-24 11:42:47 -08002065 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002066 // Ignore virtual methods on the iterator.
Ian Rogers19846512012-02-24 11:42:47 -08002067}
2068
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002069void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
Mathieu Chartierbf99f772014-08-23 16:37:27 -07002070 const OatFile::OatClass* oat_class,
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002071 uint32_t class_def_method_index) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002072 Runtime* runtime = Runtime::Current();
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002073 if (runtime->IsAotCompiler()) {
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002074 // The following code only applies to a non-compiler runtime.
2075 return;
2076 }
Ian Rogers62d6c772013-02-27 08:32:07 -08002077 // Method shouldn't have already been linked.
Ian Rogersef7d42f2014-01-06 12:55:46 -08002078 DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002079 if (oat_class != nullptr) {
2080 // Every kind of method should at least get an invoke stub from the oat_method.
2081 // non-abstract methods also get their code pointers.
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002082 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
Nicolas Geoffray4fcdc942014-07-22 10:48:00 +01002083 oat_method.LinkMethod(method.Get());
2084 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002085
Jeff Hao16743632013-05-08 10:59:04 -07002086 // Install entry point from interpreter.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002087 bool enter_interpreter = NeedsInterpreter(method.Get(),
Elliott Hughes956af0f2014-12-11 14:34:28 -08002088 method->GetEntryPointFromQuickCompiledCode());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002089 if (enter_interpreter && !method->IsNative()) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002090 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002091 } else {
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07002092 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Jeff Hao16743632013-05-08 10:59:04 -07002093 }
2094
Brian Carlstrom92827a52011-10-10 15:50:01 -07002095 if (method->IsAbstract()) {
Ian Rogersef7d42f2014-01-06 12:55:46 -08002096 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002097 return;
2098 }
Ian Rogers19846512012-02-24 11:42:47 -08002099
2100 if (method->IsStatic() && !method->IsConstructor()) {
Ian Rogers62d6c772013-02-27 08:32:07 -08002101 // For static methods excluding the class initializer, install the trampoline.
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002102 // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2103 // after initializing class (see ClassLinker::InitializeClass method).
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002104 method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
Sebastien Hertz7d658cf2013-07-09 10:56:11 +02002105 } else if (enter_interpreter) {
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002106 if (!method->IsNative()) {
2107 // Set entry point from compiled code if there's no code or in interpreter only mode.
2108 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002109 } else {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002110 method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
Andreas Gampebf6b92a2014-03-05 16:11:04 -08002111 }
Ian Rogers0d6de042012-02-29 08:50:26 -08002112 }
jeffhao26c0a1a2012-01-17 16:28:33 -08002113
Ian Rogers62d6c772013-02-27 08:32:07 -08002114 if (method->IsNative()) {
2115 // Unregistering restores the dlsym lookup stub.
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002116 method->UnregisterNative();
Andreas Gampe90546832014-03-12 18:07:19 -07002117
2118 if (enter_interpreter) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002119 // We have a native method here without code. Then it should have either the generic JNI
2120 // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2121 // TODO: this doesn't handle all the cases where trampolines may be installed.
2122 const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2123 DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
Andreas Gampe90546832014-03-12 18:07:19 -07002124 }
Brian Carlstrom92827a52011-10-10 15:50:01 -07002125 }
2126}
2127
Mathieu Chartierc7853442015-03-27 14:35:38 -07002128void ClassLinker::SetupClass(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
2129 Handle<mirror::Class> klass, mirror::ClassLoader* class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002130 CHECK(klass.Get() != nullptr);
2131 CHECK(klass->GetDexCache() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002132 CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07002133 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002134 CHECK(descriptor != nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002135
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002136 klass->SetClass(GetClassRoot(kJavaLangClass));
Andreas Gampe51829322014-08-25 15:05:04 -07002137 uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
Brian Carlstrom8e3fb142013-10-09 21:00:27 -07002138 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002139 klass->SetAccessFlags(access_flags);
2140 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08002141 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002142 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002143
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002144 klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002145 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Mathieu Chartier91a6dc42014-12-01 10:31:15 -08002146 CHECK(klass->GetDexCacheStrings() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002147}
Brian Carlstrom934486c2011-07-12 23:42:50 -07002148
Mathieu Chartierc7853442015-03-27 14:35:38 -07002149void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
2150 const DexFile::ClassDef& dex_class_def,
2151 Handle<mirror::Class> klass) {
Ian Rogers13735952014-10-08 12:43:28 -07002152 const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002153 if (class_data == nullptr) {
Ian Rogers0571d352011-11-03 19:51:38 -07002154 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07002155 }
Ian Rogers97b52f82014-08-14 11:34:07 -07002156 bool has_oat_class = false;
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07002157 if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
Ian Rogers97b52f82014-08-14 11:34:07 -07002158 OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2159 &has_oat_class);
2160 if (has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002161 LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
Ian Rogers97b52f82014-08-14 11:34:07 -07002162 }
2163 }
2164 if (!has_oat_class) {
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002165 LoadClassMembers(self, dex_file, class_data, klass, nullptr);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002166 }
2167}
2168
Mathieu Chartierc7853442015-03-27 14:35:38 -07002169ArtField* ClassLinker::AllocArtFieldArray(Thread* self, size_t length) {
2170 auto* const la = Runtime::Current()->GetLinearAlloc();
2171 auto* ptr = reinterpret_cast<ArtField*>(la->AllocArray<ArtField>(self, length));
2172 CHECK(ptr!= nullptr);
2173 std::uninitialized_fill_n(ptr, length, ArtField());
2174 return ptr;
2175}
2176
Ian Rogers7b078e82014-09-10 14:44:24 -07002177void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
Ian Rogers13735952014-10-08 12:43:28 -07002178 const uint8_t* class_data,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002179 Handle<mirror::Class> klass,
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002180 const OatFile::OatClass* oat_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07002181 // Load static fields.
Ian Rogers0571d352011-11-03 19:51:38 -07002182 ClassDataItemIterator it(dex_file, class_data);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002183 const size_t num_sfields = it.NumStaticFields();
2184 ArtField* sfields = num_sfields != 0 ? AllocArtFieldArray(self, num_sfields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002185 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07002186 CHECK_LT(i, num_sfields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002187 LoadField(it, klass, &sfields[i]);
Ian Rogers0571d352011-11-03 19:51:38 -07002188 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002189 klass->SetSFields(sfields);
2190 klass->SetNumStaticFields(num_sfields);
2191 DCHECK_EQ(klass->NumStaticFields(), num_sfields);
2192 // Load instance fields.
2193 const size_t num_ifields = it.NumInstanceFields();
2194 ArtField* ifields = num_ifields != 0 ? AllocArtFieldArray(self, num_ifields) : nullptr;
Ian Rogers0571d352011-11-03 19:51:38 -07002195 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07002196 CHECK_LT(i, num_ifields);
Mathieu Chartierc7853442015-03-27 14:35:38 -07002197 LoadField(it, klass, &ifields[i]);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002198 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07002199 klass->SetIFields(ifields);
2200 klass->SetNumInstanceFields(num_ifields);
2201 DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
Mathieu Chartierf3f2a7a2015-04-14 15:43:10 -07002202 // Note: We cannot have thread suspension until the field arrays are setup or else
2203 // Class::VisitFieldRoots may miss some fields.
2204 self->AllowThreadSuspension();
Ian Rogers0571d352011-11-03 19:51:38 -07002205 // Load methods.
2206 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07002207 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002208 mirror::ObjectArray<mirror::ArtMethod>* directs =
2209 AllocArtMethodArray(self, it.NumDirectMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002210 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002211 CHECK(self->IsExceptionPending()); // OOME.
2212 return;
2213 }
2214 klass->SetDirectMethods(directs);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002215 }
Ian Rogers0571d352011-11-03 19:51:38 -07002216 if (it.NumVirtualMethods() != 0) {
2217 // TODO: append direct methods to class object
Ian Rogersa436fde2013-08-27 23:34:06 -07002218 mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2219 AllocArtMethodArray(self, it.NumVirtualMethods());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002220 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002221 CHECK(self->IsExceptionPending()); // OOME.
2222 return;
2223 }
2224 klass->SetVirtualMethods(virtuals);
Brian Carlstrom934486c2011-07-12 23:42:50 -07002225 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002226 size_t class_def_method_index = 0;
Jeff Hao68caf9e2014-09-03 13:48:16 -07002227 uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2228 size_t last_class_def_method_index = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07002229 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002230 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002231 StackHandleScope<1> hs(self);
2232 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002233 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002234 CHECK(self->IsExceptionPending()); // OOME.
2235 return;
2236 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002237 klass->SetDirectMethod(i, method.Get());
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002238 LinkCode(method, oat_class, class_def_method_index);
Jeff Hao68caf9e2014-09-03 13:48:16 -07002239 uint32_t it_method_index = it.GetMemberIndex();
2240 if (last_dex_method_index == it_method_index) {
2241 // duplicate case
2242 method->SetMethodIndex(last_class_def_method_index);
2243 } else {
2244 method->SetMethodIndex(class_def_method_index);
2245 last_dex_method_index = it_method_index;
2246 last_class_def_method_index = class_def_method_index;
2247 }
Ian Rogersfb6adba2012-03-04 21:51:51 -08002248 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002249 }
2250 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002251 self->AllowThreadSuspension();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002252 StackHandleScope<1> hs(self);
2253 Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002254 if (UNLIKELY(method.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002255 CHECK(self->IsExceptionPending()); // OOME.
2256 return;
2257 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002258 klass->SetVirtualMethod(i, method.Get());
Ian Rogersfb6adba2012-03-04 21:51:51 -08002259 DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07002260 LinkCode(method, oat_class, class_def_method_index);
Ian Rogersfb6adba2012-03-04 21:51:51 -08002261 class_def_method_index++;
Ian Rogers0571d352011-11-03 19:51:38 -07002262 }
2263 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002264}
2265
Mathieu Chartierc7853442015-03-27 14:35:38 -07002266void ClassLinker::LoadField(const ClassDataItemIterator& it, Handle<mirror::Class> klass,
2267 ArtField* dst) {
2268 const uint32_t field_idx = it.GetMemberIndex();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002269 dst->SetDexFieldIndex(field_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002270 dst->SetDeclaringClass(klass.Get());
Andreas Gampe51829322014-08-25 15:05:04 -07002271 dst->SetAccessFlags(it.GetFieldAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002272}
2273
Brian Carlstromea46f952013-07-30 01:26:50 -07002274mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
Ian Rogersa436fde2013-08-27 23:34:06 -07002275 const ClassDataItemIterator& it,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002276 Handle<mirror::Class> klass) {
Ian Rogers19846512012-02-24 11:42:47 -08002277 uint32_t dex_method_idx = it.GetMemberIndex();
Ian Rogers19846512012-02-24 11:42:47 -08002278 const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002279 const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002280
Brian Carlstromea46f952013-07-30 01:26:50 -07002281 mirror::ArtMethod* dst = AllocArtMethod(self);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002282 if (UNLIKELY(dst == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07002283 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002284 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002285 }
Brian Carlstromea46f952013-07-30 01:26:50 -07002286 DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002287
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002288 ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
Mathieu Chartier66f19252012-09-18 08:57:04 -07002289 dst->SetDexMethodIndex(dex_method_idx);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002290 dst->SetDeclaringClass(klass.Get());
Ian Rogers0571d352011-11-03 19:51:38 -07002291 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Brian Carlstrom934486c2011-07-12 23:42:50 -07002292
Ian Rogers19846512012-02-24 11:42:47 -08002293 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002294 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002295
Andreas Gampe51829322014-08-25 15:05:04 -07002296 uint32_t access_flags = it.GetMethodAccessFlags();
Ian Rogers241b5de2013-10-09 17:58:57 -07002297
Ian Rogersdfb325e2013-10-30 01:00:44 -07002298 if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002299 // Set finalizable flag on declaring class.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002300 if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2301 // Void return type.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002302 if (klass->GetClassLoader() != nullptr) { // All non-boot finalizer methods are flagged.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002303 klass->SetFinalizable();
2304 } else {
Ian Rogers1ff3c982014-08-12 02:30:58 -07002305 std::string temp;
2306 const char* klass_descriptor = klass->GetDescriptor(&temp);
Ian Rogersdfb325e2013-10-30 01:00:44 -07002307 // The Enum class declares a "final" finalize() method to prevent subclasses from
2308 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2309 // subclasses, so we exclude it here.
2310 // We also want to avoid setting the flag on Object, where we know that finalize() is
2311 // empty.
Ian Rogers1ff3c982014-08-12 02:30:58 -07002312 if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2313 strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
Ian Rogers241b5de2013-10-09 17:58:57 -07002314 klass->SetFinalizable();
Ian Rogers241b5de2013-10-09 17:58:57 -07002315 }
2316 }
2317 }
2318 } else if (method_name[0] == '<') {
2319 // Fix broken access flags for initializers. Bug 11157540.
Ian Rogersdfb325e2013-10-30 01:00:44 -07002320 bool is_init = (strcmp("<init>", method_name) == 0);
2321 bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
Ian Rogers241b5de2013-10-09 17:58:57 -07002322 if (UNLIKELY(!is_init && !is_clinit)) {
2323 LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2324 } else {
2325 if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2326 LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002327 << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
Ian Rogers241b5de2013-10-09 17:58:57 -07002328 access_flags |= kAccConstructor;
2329 }
2330 }
2331 }
2332 dst->SetAccessFlags(access_flags);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002333
Mathieu Chartier66f19252012-09-18 08:57:04 -07002334 return dst;
Brian Carlstrom934486c2011-07-12 23:42:50 -07002335}
2336
Ian Rogers7b078e82014-09-10 14:44:24 -07002337void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002338 StackHandleScope<1> hs(self);
2339 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002340 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2341 << dex_file.GetLocation();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002342 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002343}
2344
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002345void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002346 Handle<mirror::DexCache> dex_cache) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002347 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002348 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07002349 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002350}
2351
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002352bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002353 dex_lock_.AssertSharedHeld(Thread::Current());
Mathieu Chartier66f19252012-09-18 08:57:04 -07002354 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002355 mirror::DexCache* dex_cache = GetDexCache(i);
2356 if (dex_cache->GetDexFile() == &dex_file) {
Ian Rogers19846512012-02-24 11:42:47 -08002357 return true;
Brian Carlstromaded5f72011-10-07 17:15:04 -07002358 }
2359 }
2360 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07002361}
2362
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002363bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002364 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07002365 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002366}
2367
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002368void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002369 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002370 dex_lock_.AssertExclusiveHeld(Thread::Current());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002371 CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -07002372 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2373 << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002374 dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
Mathieu Chartier66f19252012-09-18 08:57:04 -07002375 dex_cache->SetDexFile(&dex_file);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002376 if (log_new_dex_caches_roots_) {
2377 // TODO: This is not safe if we can remove dex caches.
2378 new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2379 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002380}
2381
Brian Carlstromaded5f72011-10-07 17:15:04 -07002382void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Ian Rogers1f539342012-10-03 21:09:42 -07002383 Thread* self = Thread::Current();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002384 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002385 ReaderMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002386 if (IsDexFileRegisteredLocked(dex_file)) {
2387 return;
2388 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002389 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002390 // Don't alloc while holding the lock, since allocation may need to
2391 // suspend all threads and another thread may need the dex_lock_ to
2392 // get to a suspend point.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002393 StackHandleScope<1> hs(self);
2394 Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002395 CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2396 << dex_file.GetLocation();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002397 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002398 WriterMutexLock mu(self, dex_lock_);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002399 if (IsDexFileRegisteredLocked(dex_file)) {
2400 return;
2401 }
2402 RegisterDexFileLocked(dex_file, dex_cache);
2403 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07002404}
2405
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002406void ClassLinker::RegisterDexFile(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002407 Handle<mirror::DexCache> dex_cache) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002408 WriterMutexLock mu(Thread::Current(), dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002409 RegisterDexFileLocked(dex_file, dex_cache);
2410}
2411
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002412mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002413 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002414 // Search assuming unique-ness of dex file.
Mathieu Chartier66f19252012-09-18 08:57:04 -07002415 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002416 mirror::DexCache* dex_cache = GetDexCache(i);
Mathieu Chartier66f19252012-09-18 08:57:04 -07002417 if (dex_cache->GetDexFile() == &dex_file) {
2418 return dex_cache;
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002419 }
2420 }
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002421 // Search matching by location name.
2422 std::string location(dex_file.GetLocation());
2423 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002424 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002425 if (dex_cache->GetDexFile()->GetLocation() == location) {
2426 return dex_cache;
2427 }
2428 }
2429 // Failure, dump diagnostic and abort.
2430 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002431 mirror::DexCache* dex_cache = GetDexCache(i);
Ian Rogers2bcb4a42012-11-08 10:39:18 -08002432 LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2433 }
2434 LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
Ian Rogerse0a02da2014-12-02 14:10:53 -08002435 UNREACHABLE();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002436}
2437
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002438void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002439 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Ian Rogers19846512012-02-24 11:42:47 -08002440 for (size_t i = 0; i != dex_caches_.size(); ++i) {
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002441 mirror::DexCache* dex_cache = GetDexCache(i);
2442 dex_cache->Fixup(resolution_method);
Ian Rogers19846512012-02-24 11:42:47 -08002443 }
2444}
2445
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002446mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002447 mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002448 if (UNLIKELY(klass == nullptr)) {
2449 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07002450 }
2451 return InitializePrimitiveClass(klass, type);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002452}
2453
Mathieu Chartierc528dba2013-11-26 12:00:11 -08002454mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2455 Primitive::Type type) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002456 CHECK(primitive_class != nullptr);
Ian Rogers1f539342012-10-03 21:09:42 -07002457 // Must hold lock on object when initializing.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002458 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002459 StackHandleScope<1> hs(self);
2460 Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002461 ObjectLock<mirror::Class> lock(self, h_class);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002462 h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2463 h_class->SetPrimitiveType(type);
2464 mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002465 const char* descriptor = Primitive::Descriptor(type);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002466 mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002467 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002468 CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002469 return h_class.Get();
Carl Shapiro565f5072011-07-10 13:39:43 -07002470}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002471
Brian Carlstrombe977852011-07-19 14:54:54 -07002472// Create an array class (i.e. the class object for the array, not the
2473// array itself). "descriptor" looks like "[C" or "[[[[B" or
2474// "[Ljava/lang/String;".
2475//
2476// If "descriptor" refers to an array of primitives, look up the
2477// primitive type's internally-generated class object.
2478//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002479// "class_loader" is the class loader of the class that's referring to
2480// us. It's used to ensure that we're looking for the element type in
2481// the right context. It does NOT become the class loader for the
2482// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07002483//
Mathieu Chartier2cebb242015-04-21 16:50:40 -07002484// Returns null with an exception raised on failure.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002485mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002486 Handle<mirror::ClassLoader> class_loader) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07002487 // Identify the underlying component type
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002488 CHECK_EQ('[', descriptor[0]);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002489 StackHandleScope<2> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002490 MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
2491 class_loader)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002492 if (component_type.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002493 DCHECK(self->IsExceptionPending());
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002494 // We need to accept erroneous classes as component types.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002495 const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
2496 component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
Andreas Gampedc13d7d2014-07-23 20:18:36 -07002497 if (component_type.Get() == nullptr) {
2498 DCHECK(self->IsExceptionPending());
2499 return nullptr;
2500 } else {
2501 self->ClearException();
2502 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002503 }
Ian Rogers2d10b202014-05-12 19:15:18 -07002504 if (UNLIKELY(component_type->IsPrimitiveVoid())) {
2505 ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
2506 return nullptr;
2507 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002508 // See if the component type is already loaded. Array classes are
2509 // always associated with the class loader of their underlying
2510 // element type -- an array of Strings goes with the loader for
2511 // java/lang/String -- so we need to look for it there. (The
2512 // caller should have checked for the existence of the class
2513 // before calling here, but they did so with *their* class loader,
2514 // not the component type's loader.)
2515 //
2516 // If we find it, the caller adds "loader" to the class' initiating
2517 // loader list, which should prevent us from going through this again.
2518 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002519 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002520 // are the same, because our caller (FindClass) just did the
2521 // lookup. (Even if we get this wrong we still have correct behavior,
2522 // because we effectively do this lookup again when we add the new
2523 // class to the hash table --- necessary because of possible races with
2524 // other threads.)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002525 if (class_loader.Get() != component_type->GetClassLoader()) {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002526 mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002527 if (new_class != nullptr) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002528 return new_class;
2529 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002530 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002531
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002532 // Fill out the fields in the Class.
2533 //
2534 // It is possible to execute some methods against arrays, because
2535 // all arrays are subclasses of java_lang_Object_, so we need to set
2536 // up a vtable. We can just point at the one in java_lang_Object_.
2537 //
2538 // Array classes are simple enough that we don't need to do a full
2539 // link step.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002540 auto new_class = hs.NewHandle<mirror::Class>(nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002541 if (UNLIKELY(!init_done_)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002542 // Classes that were hand created, ie not by FindSystemClass
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002543 if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002544 new_class.Assign(GetClassRoot(kClassArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002545 } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002546 new_class.Assign(GetClassRoot(kObjectArrayClass));
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002547 } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002548 new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002549 } else if (strcmp(descriptor,
Ian Rogers6f3dbba2014-10-14 17:41:57 -07002550 GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002551 new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002552 } else if (strcmp(descriptor, "[C") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002553 new_class.Assign(GetClassRoot(kCharArrayClass));
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002554 } else if (strcmp(descriptor, "[I") == 0) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002555 new_class.Assign(GetClassRoot(kIntArrayClass));
Mathieu Chartierc7853442015-03-27 14:35:38 -07002556 } else if (strcmp(descriptor, "[J") == 0) {
2557 new_class.Assign(GetClassRoot(kLongArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002558 }
2559 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002560 if (new_class.Get() == nullptr) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002561 new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002562 if (new_class.Get() == nullptr) {
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002563 return nullptr;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002564 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002565 new_class->SetComponentType(component_type.Get());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002566 }
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002567 ObjectLock<mirror::Class> lock(self, new_class); // Must hold lock on object when initializing.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002568 DCHECK(new_class->GetComponentType() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002569 mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002570 new_class->SetSuperClass(java_lang_Object);
2571 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002572 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002573 new_class->SetClassLoader(component_type->GetClassLoader());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002574 mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002575 {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002576 StackHandleScope<mirror::Class::kImtSize> hs2(self,
2577 Runtime::Current()->GetImtUnimplementedMethod());
2578 new_class->PopulateEmbeddedImtAndVTable(&hs2);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002579 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002580 mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002581 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002582 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002583
2584
2585 // All arrays have java/lang/Cloneable and java/io/Serializable as
2586 // interfaces. We need to set that up here, so that stuff like
2587 // "instanceof" works right.
2588 //
2589 // Note: The GC could run during the call to FindSystemClass,
2590 // so we need to make sure the class object is GC-valid while we're in
2591 // there. Do this by clearing the interface list so the GC will just
2592 // think that the entries are null.
2593
2594
2595 // Use the single, global copies of "interfaces" and "iftable"
2596 // (remember not to free them for arrays).
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002597 {
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07002598 mirror::IfTable* array_iftable = array_iftable_.Read();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07002599 CHECK(array_iftable != nullptr);
2600 new_class->SetIfTable(array_iftable);
2601 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002602
Elliott Hughes00626c22013-06-14 15:04:14 -07002603 // Inherit access flags from the component type.
2604 int access_flags = new_class->GetComponentType()->GetAccessFlags();
2605 // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2606 access_flags &= kAccJavaFlagsMask;
2607 // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002608 // and remove "interface".
Elliott Hughes00626c22013-06-14 15:04:14 -07002609 access_flags |= kAccAbstract | kAccFinal;
2610 access_flags &= ~kAccInterface;
2611
2612 new_class->SetAccessFlags(access_flags);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002613
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002614 mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
Mathieu Chartierc0a9ea42014-02-03 16:36:49 -08002615 if (existing == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002616 return new_class.Get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002617 }
2618 // Another thread must have loaded the class after we
2619 // started but before we finished. Abandon what we've
2620 // done.
2621 //
2622 // (Yes, this happens.)
2623
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002624 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07002625}
2626
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002627mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
Ian Rogers62f05122014-03-21 11:21:29 -07002628 switch (type) {
2629 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002630 return GetClassRoot(kPrimitiveByte);
Ian Rogers62f05122014-03-21 11:21:29 -07002631 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002632 return GetClassRoot(kPrimitiveChar);
Ian Rogers62f05122014-03-21 11:21:29 -07002633 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002634 return GetClassRoot(kPrimitiveDouble);
Ian Rogers62f05122014-03-21 11:21:29 -07002635 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002636 return GetClassRoot(kPrimitiveFloat);
Ian Rogers62f05122014-03-21 11:21:29 -07002637 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002638 return GetClassRoot(kPrimitiveInt);
Ian Rogers62f05122014-03-21 11:21:29 -07002639 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002640 return GetClassRoot(kPrimitiveLong);
Ian Rogers62f05122014-03-21 11:21:29 -07002641 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002642 return GetClassRoot(kPrimitiveShort);
Ian Rogers62f05122014-03-21 11:21:29 -07002643 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002644 return GetClassRoot(kPrimitiveBoolean);
Ian Rogers62f05122014-03-21 11:21:29 -07002645 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002646 return GetClassRoot(kPrimitiveVoid);
Ian Rogers62f05122014-03-21 11:21:29 -07002647 default:
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002648 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07002649 }
Elliott Hughesbd935992011-08-22 11:59:34 -07002650 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002651 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002652 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002653}
2654
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002655mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2656 size_t hash) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002657 if (VLOG_IS_ON(class_linker)) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002658 mirror::DexCache* dex_cache = klass->GetDexCache();
Brian Carlstromae826982011-11-09 01:33:42 -08002659 std::string source;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002660 if (dex_cache != nullptr) {
Brian Carlstromae826982011-11-09 01:33:42 -08002661 source += " from ";
2662 source += dex_cache->GetLocation()->ToModifiedUtf8();
2663 }
2664 LOG(INFO) << "Loaded class " << descriptor << source;
2665 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002666 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002667 mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002668 if (existing != nullptr) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002669 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07002670 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002671 if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002672 dex_cache_image_class_lookup_required_) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002673 // Check a class loaded with the system class loader matches one in the image if the class
2674 // is in the image.
2675 existing = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002676 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002677 CHECK_EQ(klass, existing);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002678 }
2679 }
Mathieu Chartier4e305412014-02-19 10:54:44 -08002680 VerifyObject(klass);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002681 class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
Mathieu Chartier893263b2014-03-04 11:07:42 -08002682 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002683 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002684 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002685 return nullptr;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002686}
2687
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002688mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
2689 size_t hash) {
2690 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002691 auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
2692 hash);
2693 if (existing_it == class_table_.end()) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002694 CHECK(klass->IsProxyClass());
2695 return nullptr;
2696 }
2697
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002698 mirror::Class* existing = existing_it->Read();
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002699 CHECK_NE(existing, klass) << descriptor;
2700 CHECK(!existing->IsResolved()) << descriptor;
2701 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
2702
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002703 CHECK(!klass->IsTemp()) << descriptor;
2704 if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
2705 dex_cache_image_class_lookup_required_) {
2706 // Check a class loaded with the system class loader matches one in the image if the class
2707 // is in the image.
2708 existing = LookupClassFromImage(descriptor);
2709 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002710 CHECK_EQ(klass, existing) << descriptor;
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002711 }
2712 }
2713 VerifyObject(klass);
2714
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002715 // Update the element in the hash set.
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002716 *existing_it = GcRoot<mirror::Class>(klass);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002717 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002718 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002719 }
2720
2721 return existing;
2722}
2723
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002724bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07002725 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002726 auto pair = std::make_pair(descriptor, class_loader);
2727 auto it = class_table_.Find(pair);
2728 if (it != class_table_.end()) {
2729 class_table_.Erase(it);
2730 return true;
2731 }
2732 it = pre_zygote_class_table_.Find(pair);
2733 if (it != pre_zygote_class_table_.end()) {
2734 pre_zygote_class_table_.Erase(it);
2735 return true;
Brian Carlstromae826982011-11-09 01:33:42 -08002736 }
2737 return false;
2738}
2739
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002740mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002741 mirror::ClassLoader* class_loader) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002742 {
Ian Rogers7b078e82014-09-10 14:44:24 -07002743 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002744 mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002745 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002746 return result;
2747 }
Sameer Abu Asal2c6de222013-05-02 17:38:59 -07002748 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002749 if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
2750 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002751 } else {
2752 // Lookup failed but need to search dex_caches_.
2753 mirror::Class* result = LookupClassFromImage(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002754 if (result != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002755 InsertClass(descriptor, result, hash);
2756 } else {
2757 // Searching the image dex files/caches failed, we don't want to get into this situation
2758 // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2759 // classes into the class table.
Ian Rogers68b56852014-08-29 20:19:11 -07002760 constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002761 if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2762 MoveImageClassesToClassTable();
2763 }
2764 }
2765 return result;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002766 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08002767}
2768
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002769mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002770 mirror::ClassLoader* class_loader,
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002771 size_t hash) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002772 auto descriptor_pair = std::make_pair(descriptor, class_loader);
2773 auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
2774 if (it == pre_zygote_class_table_.end()) {
2775 it = class_table_.FindWithHash(descriptor_pair, hash);
2776 if (it == class_table_.end()) {
2777 return nullptr;
Ian Rogers5d76c432011-10-31 21:42:49 -07002778 }
2779 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002780 return it->Read();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002781}
2782
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002783static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2784 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2785 gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002786 CHECK(image != nullptr);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002787 mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2788 return root->AsObjectArray<mirror::DexCache>();
2789}
2790
2791void ClassLinker::MoveImageClassesToClassTable() {
2792 Thread* self = Thread::Current();
2793 WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2794 if (!dex_cache_image_class_lookup_required_) {
2795 return; // All dex cache classes are already in the class table.
2796 }
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002797 ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002798 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
Ian Rogers1ff3c982014-08-12 02:30:58 -07002799 std::string temp;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002800 for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2801 mirror::DexCache* dex_cache = dex_caches->Get(i);
2802 mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2803 for (int32_t j = 0; j < types->GetLength(); j++) {
2804 mirror::Class* klass = types->Get(j);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002805 if (klass != nullptr) {
2806 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers1ff3c982014-08-12 02:30:58 -07002807 const char* descriptor = klass->GetDescriptor(&temp);
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08002808 size_t hash = ComputeModifiedUtf8Hash(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002809 mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
2810 if (existing != nullptr) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002811 CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002812 << PrettyClassAndClassLoader(klass);
2813 } else {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002814 class_table_.Insert(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002815 if (log_new_class_table_roots_) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002816 new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
Mathieu Chartier893263b2014-03-04 11:07:42 -08002817 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002818 }
2819 }
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002820 }
2821 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002822 dex_cache_image_class_lookup_required_ = false;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002823}
2824
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002825void ClassLinker::MoveClassTableToPreZygote() {
2826 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2827 DCHECK(pre_zygote_class_table_.Empty());
2828 pre_zygote_class_table_ = std::move(class_table_);
2829 class_table_.Clear();
2830}
2831
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002832mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07002833 ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002834 mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2835 for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2836 mirror::DexCache* dex_cache = dex_caches->Get(i);
2837 const DexFile* dex_file = dex_cache->GetDexFile();
Vladimir Marko801a8112014-01-06 14:28:16 +00002838 // Try binary searching the string/type index.
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002839 const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002840 if (string_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002841 const DexFile::TypeId* type_id =
2842 dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002843 if (type_id != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002844 uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2845 mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002846 if (klass != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002847 return klass;
2848 }
2849 }
2850 }
2851 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002852 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07002853}
2854
2855void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2856 result.clear();
2857 if (dex_cache_image_class_lookup_required_) {
2858 MoveImageClassesToClassTable();
2859 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002860 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2861 while (true) {
2862 auto it = class_table_.Find(descriptor);
2863 if (it == class_table_.end()) {
2864 break;
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002865 }
Mathieu Chartierc2e20622014-11-03 11:41:47 -08002866 result.push_back(it->Read());
2867 class_table_.Erase(it);
2868 }
2869 for (mirror::Class* k : result) {
2870 class_table_.Insert(GcRoot<mirror::Class>(k));
2871 }
2872 size_t pre_zygote_start = result.size();
2873 // Now handle the pre zygote table.
2874 // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
2875 // called from the debugger.
2876 while (true) {
2877 auto it = pre_zygote_class_table_.Find(descriptor);
2878 if (it == pre_zygote_class_table_.end()) {
2879 break;
2880 }
2881 result.push_back(it->Read());
2882 pre_zygote_class_table_.Erase(it);
2883 }
2884 for (size_t i = pre_zygote_start; i < result.size(); ++i) {
2885 pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
Elliott Hughes6fa602d2011-12-02 17:54:25 -08002886 }
2887}
2888
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07002889void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002890 // TODO: assert that the monitor on the Class is held
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07002891 ObjectLock<mirror::Class> lock(self, klass);
Elliott Hughesd9c67be2012-02-02 19:54:06 -08002892
Ian Rogers9ffb0392012-09-10 11:56:50 -07002893 // Don't attempt to re-verify if already sufficiently verified.
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002894 if (klass->IsVerified()) {
Andreas Gampe48498592014-09-10 19:48:05 -07002895 EnsurePreverifiedMethods(klass);
jeffhao98eacac2011-09-14 16:11:53 -07002896 return;
2897 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002898 if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
Andreas Gampebb0c7f62014-09-11 10:59:33 -07002899 return;
2900 }
jeffhao98eacac2011-09-14 16:11:53 -07002901
Ian Rogers9ffb0392012-09-10 11:56:50 -07002902 // The class might already be erroneous, for example at compile time if we attempted to verify
2903 // this class as a parent to another.
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002904 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002905 ThrowEarlierClassFailure(klass.Get());
Brian Carlstrom9b5ee882012-02-28 09:48:54 -08002906 return;
2907 }
2908
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002909 if (klass->GetStatus() == mirror::Class::kStatusResolved) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002910 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002911 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002912 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002913 << PrettyClass(klass.Get());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002914 CHECK(!Runtime::Current()->IsAotCompiler());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002915 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
Ian Rogers9ffb0392012-09-10 11:56:50 -07002916 }
jeffhao98eacac2011-09-14 16:11:53 -07002917
Jeff Hao4a200f52014-04-01 14:58:49 -07002918 // Skip verification if disabled.
2919 if (!Runtime::Current()->IsVerificationEnabled()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002920 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampe48498592014-09-10 19:48:05 -07002921 EnsurePreverifiedMethods(klass);
Jeff Hao4a200f52014-04-01 14:58:49 -07002922 return;
2923 }
2924
Ian Rogers9ffb0392012-09-10 11:56:50 -07002925 // Verify super class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002926 StackHandleScope<2> hs(self);
2927 Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002928 if (super.Get() != nullptr) {
Ian Rogers9ffb0392012-09-10 11:56:50 -07002929 // Acquire lock to prevent races on verifying the super class.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08002930 ObjectLock<mirror::Class> super_lock(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002931
2932 if (!super->IsVerified() && !super->IsErroneous()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002933 VerifyClass(self, super);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002934 }
jeffhaof1e6b7c2012-06-05 18:33:30 -07002935 if (!super->IsCompileTimeVerified()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07002936 std::string error_msg(
2937 StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2938 PrettyDescriptor(klass.Get()).c_str(),
2939 PrettyDescriptor(super.Get()).c_str()));
Andreas Gampee4301ff2015-02-17 19:25:29 -08002940 LOG(WARNING) << error_msg << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002941 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002942 if (cause.Get() != nullptr) {
Ian Rogers1c5eb702012-02-01 09:18:34 -08002943 self->ClearException();
2944 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002945 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
2946 if (cause.Get() != nullptr) {
Nicolas Geoffray14691c52015-03-05 10:40:17 +00002947 self->GetException()->SetCause(cause.Get());
Ian Rogers1c5eb702012-02-01 09:18:34 -08002948 }
Jeff Hao22cb09b2013-12-12 14:29:15 -08002949 ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002950 if (Runtime::Current()->IsAotCompiler()) {
Vladimir Marko2b5eaa22013-12-13 13:59:30 +00002951 Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2952 }
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002953 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers1c5eb702012-02-01 09:18:34 -08002954 return;
2955 }
2956 }
2957
Elliott Hughes634eb2e2012-03-22 16:06:28 -07002958 // Try to use verification information from the oat file, otherwise do runtime verification.
Ian Rogers4445a7e2012-10-05 17:19:13 -07002959 const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002960 mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002961 bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08002962 if (oat_file_class_status == mirror::Class::kStatusError) {
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002963 VLOG(class_linker) << "Skipping runtime verification of erroneous class "
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002964 << PrettyDescriptor(klass.Get()) << " in "
Ian Rogerse6bb3b22013-08-19 21:51:45 -07002965 << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002966 ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
2967 PrettyDescriptor(klass.Get()).c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002968 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhaoec014232012-09-05 10:42:25 -07002969 return;
2970 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02002971 verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
Ian Rogers62d6c772013-02-27 08:32:07 -08002972 std::string error_msg;
jeffhaof1e6b7c2012-06-05 18:33:30 -07002973 if (!preverified) {
Ian Rogers7b078e82014-09-10 14:44:24 -07002974 verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002975 Runtime::Current()->IsAotCompiler(),
Ian Rogers8b2c0b92013-09-19 02:56:49 -07002976 &error_msg);
jeffhaof1e6b7c2012-06-05 18:33:30 -07002977 }
2978 if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
Ian Rogers529781d2012-07-23 17:24:29 -07002979 if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07002980 VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
Ian Rogers529781d2012-07-23 17:24:29 -07002981 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2982 << " because: " << error_msg;
2983 }
Ian Rogers1f539342012-10-03 21:09:42 -07002984 self->AssertNoPendingException();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002985 // Make sure all classes referenced by catch blocks are resolved.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002986 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002987 if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002988 // Even though there were no verifier failures we need to respect whether the super-class
2989 // was verified or requiring runtime reverification.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07002990 if (super.Get() == nullptr || super->IsVerified()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002991 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002992 } else {
2993 CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07002994 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07002995 // Pretend a soft failure occured so that we don't consider the class verified below.
2996 verifier_failure = verifier::MethodVerifier::kSoftFailure;
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07002997 }
jeffhaoe4f0b2a2012-08-30 11:18:57 -07002998 } else {
2999 CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3000 // Soft failures at compile time should be retried at runtime. Soft
3001 // failures at runtime will be handled by slow paths in the generated
3002 // code. Set status accordingly.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003003 if (Runtime::Current()->IsAotCompiler()) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003004 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003005 } else {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003006 mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
Andreas Gampebb0c7f62014-09-11 10:59:33 -07003007 // As this is a fake verified status, make sure the methods are _not_ marked preverified
3008 // later.
Ian Rogers7b078e82014-09-10 14:44:24 -07003009 klass->SetPreverified();
jeffhaoe4f0b2a2012-08-30 11:18:57 -07003010 }
3011 }
jeffhao5cfd6fb2011-09-27 13:54:29 -07003012 } else {
Andreas Gampee4301ff2015-02-17 19:25:29 -08003013 LOG(WARNING) << "Verification failed on class " << PrettyDescriptor(klass.Get())
Ian Rogers1c5eb702012-02-01 09:18:34 -08003014 << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3015 << " because: " << error_msg;
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003016 self->AssertNoPendingException();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003017 ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003018 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
jeffhao5cfd6fb2011-09-27 13:54:29 -07003019 }
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003020 if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003021 // Class is verified so we don't need to do any access check on its methods.
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003022 // Let the interpreter know it by setting the kAccPreverified flag onto each
3023 // method.
3024 // Note: we're going here during compilation and at runtime. When we set the
3025 // kAccPreverified flag when compiling image classes, the flag is recorded
3026 // in the image and is set when loading the image.
Andreas Gampe48498592014-09-10 19:48:05 -07003027 EnsurePreverifiedMethods(klass);
3028 }
3029}
3030
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003031void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003032 if (!klass->IsPreverified()) {
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003033 klass->SetPreverifiedFlagOnAllMethods();
Ian Rogers7b078e82014-09-10 14:44:24 -07003034 klass->SetPreverified();
Sebastien Hertz233ea8e2013-06-06 11:57:09 +02003035 }
jeffhao98eacac2011-09-14 16:11:53 -07003036}
3037
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003038bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3039 mirror::Class::Status& oat_file_class_status) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003040 // If we're compiling, we can only verify the class using the oat file if
3041 // we are not compiling the image or if the class we're verifying is not part of
3042 // the app. In other words, we will only check for preverification of bootclasspath
3043 // classes.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003044 if (Runtime::Current()->IsAotCompiler()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003045 // Are we compiling the bootclasspath?
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07003046 if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003047 return false;
3048 }
3049 // We are compiling an app (not the image).
3050
3051 // Is this an app class? (I.e. not a bootclasspath class)
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003052 if (klass->GetClassLoader() != nullptr) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003053 return false;
3054 }
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003055 }
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003056
Richard Uhler07b3c232015-03-31 15:57:54 -07003057 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003058 // In case we run without an image there won't be a backing oat file.
3059 if (oat_dex_file == nullptr) {
Anwar Ghuloumad256bb2013-07-18 14:58:55 -07003060 return false;
3061 }
3062
Andreas Gampe76bd8802014-12-10 16:43:58 -08003063 // We may be running with a preopted oat file but without image. In this case,
3064 // we don't skip verification of preverified classes to ensure we initialize
3065 // dex caches with all types resolved during verification.
3066 // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
3067 // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
3068 // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
3069 // already pre-opted, as then the runtime is started.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003070 if (!Runtime::Current()->IsAotCompiler() &&
Andreas Gampe76bd8802014-12-10 16:43:58 -08003071 !Runtime::Current()->GetHeap()->HasImageSpace() &&
3072 klass->GetClassLoader() != nullptr) {
3073 return false;
3074 }
3075
Ian Rogers8b2c0b92013-09-19 02:56:49 -07003076 uint16_t class_def_index = klass->GetDexClassDefIndex();
Vladimir Markod3c5beb2014-04-11 16:32:51 +01003077 oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003078 if (oat_file_class_status == mirror::Class::kStatusVerified ||
3079 oat_file_class_status == mirror::Class::kStatusInitialized) {
Anwar Ghuloum044d2832013-07-17 15:22:31 -07003080 return true;
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003081 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003082 if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
jeffhao1ac29442012-03-26 11:37:32 -07003083 // Compile time verification failed with a soft error. Compile time verification can fail
3084 // because we have incomplete type information. Consider the following:
Ian Rogersc4762272012-02-01 15:55:55 -08003085 // class ... {
3086 // Foo x;
3087 // .... () {
3088 // if (...) {
3089 // v1 gets assigned a type of resolved class Foo
3090 // } else {
3091 // v1 gets assigned a type of unresolved class Bar
3092 // }
3093 // iput x = v1
3094 // } }
3095 // when we merge v1 following the if-the-else it results in Conflict
3096 // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3097 // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3098 // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3099 // at compile time).
3100 return false;
3101 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003102 if (oat_file_class_status == mirror::Class::kStatusError) {
jeffhao1ac29442012-03-26 11:37:32 -07003103 // Compile time verification failed with a hard error. This is caused by invalid instructions
3104 // in the class. These errors are unrecoverable.
3105 return false;
3106 }
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003107 if (oat_file_class_status == mirror::Class::kStatusNotReady) {
Ian Rogersc4762272012-02-01 15:55:55 -08003108 // Status is uninitialized if we couldn't determine the status at compile time, for example,
3109 // not loading the class.
3110 // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3111 // isn't a problem and this case shouldn't occur
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003112 return false;
3113 }
Ian Rogers1ff3c982014-08-12 02:30:58 -07003114 std::string temp;
Elliott Hughes634eb2e2012-03-22 16:06:28 -07003115 LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
Ian Rogersfc0e94b2013-09-23 23:51:32 -07003116 << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
Ian Rogers1ff3c982014-08-12 02:30:58 -07003117 << klass->GetDescriptor(&temp);
Ian Rogerse0a02da2014-12-02 14:10:53 -08003118 UNREACHABLE();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003119}
3120
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003121void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003122 Handle<mirror::Class> klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003123 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3124 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3125 }
3126 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3127 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3128 }
3129}
3130
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003131void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
Brian Carlstromea46f952013-07-30 01:26:50 -07003132 mirror::ArtMethod* method) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003133 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3134 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003135 if (code_item == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003136 return; // native or abstract method
3137 }
3138 if (code_item->tries_size_ == 0) {
3139 return; // nothing to process
3140 }
Ian Rogers13735952014-10-08 12:43:28 -07003141 const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003142 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3143 ClassLinker* linker = Runtime::Current()->GetClassLinker();
3144 for (uint32_t idx = 0; idx < handlers_size; idx++) {
3145 CatchHandlerIterator iterator(handlers_ptr);
3146 for (; iterator.HasNext(); iterator.Next()) {
3147 // Ensure exception types are resolved so that they don't need resolution to be delivered,
3148 // unresolved exception types will be ignored by exception delivery
3149 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003150 mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003151 if (exception_type == nullptr) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08003152 DCHECK(Thread::Current()->IsExceptionPending());
3153 Thread::Current()->ClearException();
3154 }
3155 }
3156 }
3157 handlers_ptr = iterator.EndDataPointer();
3158 }
3159}
3160
Brian Carlstromea46f952013-07-30 01:26:50 -07003161static void CheckProxyConstructor(mirror::ArtMethod* constructor);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003162static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3163 Handle<mirror::ArtMethod> prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003164
Mathieu Chartier2b7c4d12014-05-19 10:52:16 -07003165mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
Mathieu Chartier590fee92013-09-13 13:46:47 -07003166 jobjectArray interfaces, jobject loader,
3167 jobjectArray methods, jobjectArray throws) {
3168 Thread* self = soa.Self();
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003169 StackHandleScope<9> hs(self);
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003170 MutableHandle<mirror::Class> klass(hs.NewHandle(
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003171 AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003172 if (klass.Get() == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003173 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003174 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003175 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003176 DCHECK(klass->GetClass() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003177 klass->SetObjectSize(sizeof(mirror::Proxy));
Andreas Gampe48498592014-09-10 19:48:05 -07003178 // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3179 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003180 klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
Ian Rogersc2b44472011-12-14 21:17:17 -08003181 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Mathieu Chartier590fee92013-09-13 13:46:47 -07003182 klass->SetName(soa.Decode<mirror::String*>(name));
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003183 mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003184 klass->SetDexCache(proxy_class->GetDexCache());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003185 mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
Ian Rogersc2b44472011-12-14 21:17:17 -08003186
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003187 // Instance fields are inherited, but we add a couple of static fields...
Mathieu Chartierc7853442015-03-27 14:35:38 -07003188 const size_t num_fields = 2;
3189 ArtField* sfields = AllocArtFieldArray(self, num_fields);
3190 klass->SetSFields(sfields);
3191 klass->SetNumStaticFields(num_fields);
3192
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003193 // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3194 // our proxy, so Class.getInterfaces doesn't return the flattened set.
Mathieu Chartierc7853442015-03-27 14:35:38 -07003195 ArtField* interfaces_sfield = &sfields[0];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003196 interfaces_sfield->SetDexFieldIndex(0);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003197 interfaces_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003198 interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Mathieu Chartierc7853442015-03-27 14:35:38 -07003199
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003200 // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
Mathieu Chartierc7853442015-03-27 14:35:38 -07003201 ArtField* throws_sfield = &sfields[1];
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003202 throws_sfield->SetDexFieldIndex(1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003203 throws_sfield->SetDeclaringClass(klass.Get());
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003204 throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003205
Ian Rogers466bb252011-10-14 03:29:56 -07003206 // Proxies have 1 direct method, the constructor
Ian Rogersa436fde2013-08-27 23:34:06 -07003207 {
Mathieu Chartier590fee92013-09-13 13:46:47 -07003208 mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003209 if (UNLIKELY(directs == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003210 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003211 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003212 }
3213 klass->SetDirectMethods(directs);
3214 mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003215 if (UNLIKELY(constructor == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003216 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003217 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003218 }
3219 klass->SetDirectMethod(0, constructor);
3220 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003221
Mathieu Chartier590fee92013-09-13 13:46:47 -07003222 // Create virtual method using specified prototypes.
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003223 auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods));
3224 DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
3225 << PrettyClass(h_methods->GetClass());
3226 const size_t num_virtual_methods = h_methods->GetLength();
Ian Rogersa436fde2013-08-27 23:34:06 -07003227 {
Brian Carlstromf3632832014-05-20 15:36:53 -07003228 mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3229 num_virtual_methods);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003230 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003231 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003232 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003233 }
3234 klass->SetVirtualMethods(virtuals);
3235 }
Jesse Wilson95caa792011-10-12 18:14:17 -04003236 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003237 StackHandleScope<1> hs2(self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003238 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(h_methods->Get(i)->GetArtMethod()));
Ian Rogersa436fde2013-08-27 23:34:06 -07003239 mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003240 if (UNLIKELY(clone == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003241 CHECK(self->IsExceptionPending()); // OOME.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003242 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003243 }
3244 klass->SetVirtualMethod(i, clone);
Jesse Wilson95caa792011-10-12 18:14:17 -04003245 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003246
3247 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003248 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self); // Now effectively in the loaded state.
Ian Rogers62d6c772013-02-27 08:32:07 -08003249 self->AssertNoPendingException();
Ian Rogersc2b44472011-12-14 21:17:17 -08003250
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003251 std::string descriptor(GetDescriptorForProxy(klass.Get()));
3252 mirror::Class* new_class = nullptr;
Ian Rogersc8982582012-09-07 16:53:25 -07003253 {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003254 // Must hold lock on object when resolved.
3255 ObjectLock<mirror::Class> resolution_lock(self, klass);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003256 // Link the fields and virtual methods, creating vtable and iftables
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003257 Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003258 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003259 if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003260 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003261 return nullptr;
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003262 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003263 }
Ian Rogers7dfb28c2013-08-22 08:18:36 -07003264
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003265 CHECK(klass->IsRetired());
3266 CHECK_NE(klass.Get(), new_class);
3267 klass.Assign(new_class);
3268
3269 CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003270 interfaces_sfield->SetObject<false>(klass.Get(),
3271 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003272 CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003273 throws_sfield->SetObject<false>(klass.Get(),
3274 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003275
3276 {
3277 // Lock on klass is released. Lock new class object.
3278 ObjectLock<mirror::Class> initialization_lock(self, klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003279 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogersc8982582012-09-07 16:53:25 -07003280 }
Ian Rogersc2b44472011-12-14 21:17:17 -08003281
3282 // sanity checks
Elliott Hughes67d92002012-03-26 15:08:51 -07003283 if (kIsDebugBuild) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003284 CHECK(klass->GetIFields() == nullptr);
Ian Rogersc2b44472011-12-14 21:17:17 -08003285 CheckProxyConstructor(klass->GetDirectMethod(0));
3286 for (size_t i = 0; i < num_virtual_methods; ++i) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003287 StackHandleScope<2> hs2(self);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003288 Handle<mirror::ArtMethod> prototype(hs2.NewHandle(h_methods->Get(i)->GetArtMethod()));
Andreas Gampe277ccbd2014-11-03 21:36:10 -08003289 Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003290 CheckProxyMethod(virtual_method, prototype);
Ian Rogersc2b44472011-12-14 21:17:17 -08003291 }
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003292
Mathieu Chartier590fee92013-09-13 13:46:47 -07003293 mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003294 std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003295 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003296 CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3297
3298 std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
Mathieu Chartier590fee92013-09-13 13:46:47 -07003299 decoded_name->ToModifiedUtf8().c_str()));
Elliott Hughes2ed52c42012-03-21 16:56:56 -07003300 CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
Ian Rogersc2b44472011-12-14 21:17:17 -08003301
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003302 CHECK_EQ(klass.Get()->GetInterfaces(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003303 soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003304 CHECK_EQ(klass.Get()->GetThrows(),
Brian Carlstromf3632832014-05-20 15:36:53 -07003305 soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
Ian Rogersc2b44472011-12-14 21:17:17 -08003306 }
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003307 mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3308 ComputeModifiedUtf8Hash(descriptor.c_str()));
Mathieu Chartier31b9d662013-10-14 11:53:12 -07003309 CHECK(existing == nullptr);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003310 return klass.Get();
Jesse Wilson95caa792011-10-12 18:14:17 -04003311}
3312
Ian Rogersef7d42f2014-01-06 12:55:46 -08003313std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003314 DCHECK(proxy_class->IsProxyClass());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003315 mirror::String* name = proxy_class->GetName();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003316 DCHECK(name != nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003317 return DotToDescriptor(name->ToModifiedUtf8().c_str());
3318}
3319
Ian Rogersef7d42f2014-01-06 12:55:46 -08003320mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3321 mirror::ArtMethod* proxy_method) {
Ian Rogers16f93672012-02-14 12:29:06 -08003322 DCHECK(proxy_class->IsProxyClass());
3323 DCHECK(proxy_method->IsProxyMethod());
Ian Rogers16f93672012-02-14 12:29:06 -08003324 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07003325 ReaderMutexLock mu(Thread::Current(), dex_lock_);
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003326 // Locate the dex cache of the original interface/Object
3327 for (const GcRoot<mirror::DexCache>& root : dex_caches_) {
3328 auto* dex_cache = root.Read();
3329 if (proxy_method->HasSameDexCacheResolvedTypes(dex_cache->GetResolvedTypes())) {
3330 mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(
3331 proxy_method->GetDexMethodIndex());
3332 CHECK(resolved_method != nullptr);
3333 return resolved_method;
Ian Rogers16f93672012-02-14 12:29:06 -08003334 }
3335 }
3336 }
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003337 LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " "
3338 << PrettyMethod(proxy_method);
3339 UNREACHABLE();
Ian Rogers16f93672012-02-14 12:29:06 -08003340}
3341
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003342
Brian Carlstromea46f952013-07-30 01:26:50 -07003343mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003344 Handle<mirror::Class> klass,
Brian Carlstromea46f952013-07-30 01:26:50 -07003345 mirror::Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07003346 // Create constructor for Proxy that must initialize h
Brian Carlstromea46f952013-07-30 01:26:50 -07003347 mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003348 proxy_class->GetDirectMethods();
Brian Carlstromea46f952013-07-30 01:26:50 -07003349 CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3350 mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
Sebastien Hertzae94e352014-08-27 15:32:56 +02003351 // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3352 // constructor method.
3353 proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3354 proxy_constructor);
Jeff Haodb8a6642014-08-14 17:18:52 -07003355 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3356 // code_ too)
Jeff Haof0a3f092014-07-24 16:26:09 -07003357 mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3358 if (constructor == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003359 CHECK(self->IsExceptionPending()); // OOME.
Jeff Haof0a3f092014-07-24 16:26:09 -07003360 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003361 }
Ian Rogers466bb252011-10-14 03:29:56 -07003362 // Make this constructor public and fix the class to be our Proxy version
3363 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003364 constructor->SetDeclaringClass(klass.Get());
Ian Rogersc2b44472011-12-14 21:17:17 -08003365 return constructor;
3366}
3367
Brian Carlstromea46f952013-07-30 01:26:50 -07003368static void CheckProxyConstructor(mirror::ArtMethod* constructor)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003369 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003370 CHECK(constructor->IsConstructor());
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003371 CHECK_STREQ(constructor->GetName(), "<init>");
3372 CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3373 "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07003374 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04003375}
3376
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003377mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003378 Handle<mirror::Class> klass,
3379 Handle<mirror::ArtMethod> prototype) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003380 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3381 // prototype method
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003382 auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
3383 // Avoid dirtying the dex cache unless we need to.
3384 if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex()) != prototype.Get()) {
3385 dex_cache->SetResolvedMethod(prototype->GetDexMethodIndex(), prototype.Get());
3386 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003387 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07003388 // as necessary
Brian Carlstromea46f952013-07-30 01:26:50 -07003389 mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003390 if (UNLIKELY(method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07003391 CHECK(self->IsExceptionPending()); // OOME.
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003392 return nullptr;
Ian Rogersa436fde2013-08-27 23:34:06 -07003393 }
Ian Rogers466bb252011-10-14 03:29:56 -07003394
3395 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3396 // the intersection of throw exceptions as defined in Proxy
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003397 method->SetDeclaringClass(klass.Get());
Ian Rogers466bb252011-10-14 03:29:56 -07003398 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04003399
Ian Rogers466bb252011-10-14 03:29:56 -07003400 // At runtime the method looks like a reference and argument saving method, clone the code
3401 // related parameters from this method.
Ian Rogersef7d42f2014-01-06 12:55:46 -08003402 method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
Dragos Sbirlea08bf1962013-08-12 08:53:04 -07003403 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers16f93672012-02-14 12:29:06 -08003404
Ian Rogersc2b44472011-12-14 21:17:17 -08003405 return method;
3406}
Jesse Wilson95caa792011-10-12 18:14:17 -04003407
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003408static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3409 Handle<mirror::ArtMethod> prototype)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003410 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Ian Rogers466bb252011-10-14 03:29:56 -07003411 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003412 CHECK(!prototype->IsFinal());
3413 CHECK(method->IsFinal());
3414 CHECK(!method->IsAbstract());
Ian Rogers19846512012-02-24 11:42:47 -08003415
3416 // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3417 // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
Andreas Gampe58a5af82014-07-31 16:23:49 -07003418 CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3419 CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
Mathieu Chartierfc58af42015-04-16 18:00:39 -07003420 CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), method->GetDexCache());
Ian Rogers19846512012-02-24 11:42:47 -08003421 CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3422
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07003423 CHECK_STREQ(method->GetName(), prototype->GetName());
3424 CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
Ian Rogers466bb252011-10-14 03:29:56 -07003425 // More complex sanity - via dex cache
Ian Rogersded66a02014-10-28 18:12:55 -07003426 CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04003427}
3428
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003429static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3430 bool can_init_parents)
3431 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003432 if (can_init_statics && can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003433 return true;
3434 }
3435 if (!can_init_statics) {
3436 // Check if there's a class initializer.
Ian Rogersd91d6d62013-09-25 20:26:14 -07003437 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003438 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003439 return false;
3440 }
3441 // Check if there are encoded static values needing initialization.
3442 if (klass->NumStaticFields() != 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003443 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003444 DCHECK(dex_class_def != nullptr);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003445 if (dex_class_def->static_values_off_ != 0) {
3446 return false;
3447 }
3448 }
3449 }
3450 if (!klass->IsInterface() && klass->HasSuperClass()) {
3451 mirror::Class* super_class = klass->GetSuperClass();
3452 if (!can_init_parents && !super_class->IsInitialized()) {
3453 return false;
3454 } else {
Brian Carlstrom610e49f2013-11-04 17:07:22 -08003455 if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003456 return false;
3457 }
3458 }
3459 }
3460 return true;
3461}
3462
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003463bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
Ian Rogers7b078e82014-09-10 14:44:24 -07003464 bool can_init_statics, bool can_init_parents) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003465 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3466
3467 // Are we already initialized and therefore done?
3468 // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3469 // an initialized class will never change its state.
3470 if (klass->IsInitialized()) {
3471 return true;
3472 }
3473
3474 // Fast fail if initialization requires a full runtime. Not part of the JLS.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003475 if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003476 return false;
3477 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003478
Ian Rogers7b078e82014-09-10 14:44:24 -07003479 self->AllowThreadSuspension();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003480 uint64_t t0;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003481 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003482 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003483
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003484 // Re-check under the lock in case another thread initialized ahead of us.
3485 if (klass->IsInitialized()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003486 return true;
3487 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003488
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003489 // Was the class already found to be erroneous? Done under the lock to match the JLS.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003490 if (klass->IsErroneous()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003491 ThrowEarlierClassFailure(klass.Get());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003492 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003493 return false;
3494 }
3495
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003496 CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003497
3498 if (!klass->IsVerified()) {
Ian Rogers7b078e82014-09-10 14:44:24 -07003499 VerifyClass(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003500 if (!klass->IsVerified()) {
3501 // We failed to verify, expect either the klass to be erroneous or verification failed at
3502 // compile time.
3503 if (klass->IsErroneous()) {
jeffhaoa9b3bf42012-06-06 17:18:39 -07003504 CHECK(self->IsExceptionPending());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003505 VlogClassInitializationFailure(klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003506 } else {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003507 CHECK(Runtime::Current()->IsAotCompiler());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003508 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
jeffhaoa9b3bf42012-06-06 17:18:39 -07003509 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003510 return false;
Mathieu Chartier524507a2014-08-27 15:28:28 -07003511 } else {
3512 self->AssertNoPendingException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003513 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003514 }
3515
Brian Carlstromd1422f82011-09-28 11:37:09 -07003516 // If the class is kStatusInitializing, either this thread is
3517 // initializing higher up the stack or another thread has beat us
3518 // to initializing and we need to wait. Either way, this
3519 // invocation of InitializeClass will not be responsible for
3520 // running <clinit> and will return.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003521 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Mathieu Chartier524507a2014-08-27 15:28:28 -07003522 // Could have got an exception during verification.
3523 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003524 VlogClassInitializationFailure(klass);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003525 return false;
3526 }
Elliott Hughes005ab2e2011-09-11 17:15:31 -07003527 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07003528 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003529 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003530 return true;
3531 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003532 // No. That's fine. Wait for another thread to finish initializing.
3533 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003534 }
3535
3536 if (!ValidateSuperClassDescriptors(klass)) {
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003537 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003538 return false;
3539 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003540 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003541
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003542 CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003543
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003544 // From here out other threads may observe that we're initializing and so changes of state
3545 // require the a notification.
Elliott Hughesdcc24742011-09-07 14:02:44 -07003546 klass->SetClinitThreadId(self->GetTid());
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003547 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003548
3549 t0 = NanoTime();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003550 }
3551
Brian Carlstrom6d3f72c2013-08-21 18:06:34 -07003552 // Initialize super classes, must be done while initializing for the JLS.
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003553 if (!klass->IsInterface() && klass->HasSuperClass()) {
3554 mirror::Class* super_class = klass->GetSuperClass();
3555 if (!super_class->IsInitialized()) {
3556 CHECK(!super_class->IsInterface());
3557 CHECK(can_init_parents);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003558 StackHandleScope<1> hs(self);
3559 Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
Ian Rogers7b078e82014-09-10 14:44:24 -07003560 bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003561 if (!super_initialized) {
3562 // The super class was verified ahead of entering initializing, we should only be here if
3563 // the super class became erroneous due to initialization.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003564 CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
Brian Carlstromf3632832014-05-20 15:36:53 -07003565 << "Super class initialization failed for "
3566 << PrettyDescriptor(handle_scope_super.Get())
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003567 << " that has unexpected status " << handle_scope_super->GetStatus()
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003568 << "\nPending exception:\n"
Nicolas Geoffray14691c52015-03-05 10:40:17 +00003569 << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003570 ObjectLock<mirror::Class> lock(self, klass);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003571 // Initialization failed because the super-class is erroneous.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003572 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003573 return false;
3574 }
Ian Rogers1bddec32012-02-04 12:27:34 -08003575 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003576 }
3577
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003578 const size_t num_static_fields = klass->NumStaticFields();
3579 if (num_static_fields > 0) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07003580 const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003581 CHECK(dex_class_def != nullptr);
Mathieu Chartierf8322842014-05-16 10:59:25 -07003582 const DexFile& dex_file = klass->GetDexFile();
Hiroshi Yamauchi67ef46a2014-08-21 15:59:43 -07003583 StackHandleScope<3> hs(self);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003584 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
Mathieu Chartierf8322842014-05-16 10:59:25 -07003585 Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003586
3587 // Eagerly fill in static fields so that the we don't have to do as many expensive
3588 // Class::FindStaticField in ResolveField.
3589 for (size_t i = 0; i < num_static_fields; ++i) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003590 ArtField* field = klass->GetStaticField(i);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003591 const uint32_t field_idx = field->GetDexFieldIndex();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003592 ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003593 if (resolved_field == nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003594 dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07003595 } else {
3596 DCHECK_EQ(field, resolved_field);
Mathieu Chartier05d89ee2014-10-28 13:57:04 -07003597 }
3598 }
3599
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003600 EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
3601 this, *dex_class_def);
Ian Rogers13735952014-10-08 12:43:28 -07003602 const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003603 ClassDataItemIterator field_it(dex_file, class_data);
3604 if (value_it.HasNext()) {
3605 DCHECK(field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003606 CHECK(can_init_statics);
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003607 for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003608 ArtField* field = ResolveField(
3609 dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003610 if (Runtime::Current()->IsActiveTransaction()) {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003611 value_it.ReadValueToField<true>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003612 } else {
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003613 value_it.ReadValueToField<false>(field);
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01003614 }
Hiroshi Yamauchi88500112014-08-22 12:12:56 -07003615 DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003616 }
3617 }
3618 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003619
Ian Rogersd91d6d62013-09-25 20:26:14 -07003620 mirror::ArtMethod* clinit = klass->FindClassInitializer();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003621 if (clinit != nullptr) {
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003622 CHECK(can_init_statics);
Ian Rogers5d27faf2014-05-02 17:17:18 -07003623 JValue result;
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003624 clinit->Invoke(self, nullptr, 0, &result, "V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003625 }
3626
Ian Rogers7b078e82014-09-10 14:44:24 -07003627 self->AllowThreadSuspension();
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003628 uint64_t t1 = NanoTime();
3629
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003630 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003631 {
Mathieu Chartierdb2633c2014-05-16 09:59:29 -07003632 ObjectLock<mirror::Class> lock(self, klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003633
3634 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003635 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003636 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003637 success = false;
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003638 } else if (Runtime::Current()->IsTransactionAborted()) {
3639 // The exception thrown when the transaction aborted has been caught and cleared
3640 // so we need to throw it again now.
Sebastien Hertzbd9cf9f2015-03-03 12:16:13 +01003641 VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
3642 << " without exception while transaction was aborted: re-throw it now.";
Sebastien Hertz2fd7e692015-04-02 11:11:19 +02003643 Runtime::Current()->ThrowTransactionAbortError(self);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003644 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Sebastien Hertz1c80bec2015-02-03 11:58:06 +01003645 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003646 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07003647 RuntimeStats* global_stats = Runtime::Current()->GetStats();
3648 RuntimeStats* thread_stats = self->GetStats();
3649 ++global_stats->class_init_count;
3650 ++thread_stats->class_init_count;
3651 global_stats->class_init_time_ns += (t1 - t0);
3652 thread_stats->class_init_time_ns += (t1 - t0);
Ian Rogerse6bb3b22013-08-19 21:51:45 -07003653 // Set the class as initialized except if failed to initialize static fields.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003654 mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003655 if (VLOG_IS_ON(class_linker)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -07003656 std::string temp;
3657 LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
Mathieu Chartierf8322842014-05-16 10:59:25 -07003658 klass->GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08003659 }
Brian Carlstrom073278c2014-02-19 15:21:21 -08003660 // Opportunistically set static method trampolines to their destination.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003661 FixupStaticTrampolines(klass.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003662 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003663 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08003664 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003665}
3666
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003667bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003668 ObjectLock<mirror::Class>& lock)
Ian Rogersb726dcb2012-09-05 08:57:23 -07003669 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003670 while (true) {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07003671 self->AssertNoPendingException();
Ian Rogers8f3c9ae2013-08-20 17:26:41 -07003672 CHECK(!klass->IsInitialized());
Ian Rogers05f30572013-02-20 12:13:11 -08003673 lock.WaitIgnoringInterrupts();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003674
3675 // When we wake up, repeat the test for init-in-progress. If
3676 // there's an exception pending (only possible if
Brian Carlstromb23eab12014-10-08 17:55:21 -07003677 // we were not using WaitIgnoringInterrupts), bail out.
Brian Carlstromd1422f82011-09-28 11:37:09 -07003678 if (self->IsExceptionPending()) {
Brian Carlstromb23eab12014-10-08 17:55:21 -07003679 WrapExceptionInInitializer(klass);
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003680 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003681 return false;
3682 }
3683 // Spurious wakeup? Go back to waiting.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003684 if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07003685 continue;
3686 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08003687 if (klass->GetStatus() == mirror::Class::kStatusVerified &&
3688 Runtime::Current()->IsAotCompiler()) {
Ian Rogers3d1548d2012-09-24 14:08:03 -07003689 // Compile time initialization failed.
3690 return false;
3691 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07003692 if (klass->IsErroneous()) {
3693 // The caller wants an exception, but it was thrown in a
3694 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07003695 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003696 PrettyDescriptor(klass.Get()).c_str());
Brian Carlstromb23eab12014-10-08 17:55:21 -07003697 VlogClassInitializationFailure(klass);
Brian Carlstromd1422f82011-09-28 11:37:09 -07003698 return false;
3699 }
3700 if (klass->IsInitialized()) {
3701 return true;
3702 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07003703 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
Mathieu Chartierc528dba2013-11-26 12:00:11 -08003704 << klass->GetStatus();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003705 }
Ian Rogers07140832014-09-30 15:43:59 -07003706 UNREACHABLE();
Brian Carlstromd1422f82011-09-28 11:37:09 -07003707}
3708
Ian Rogersb5fb2072014-12-02 17:22:02 -08003709static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
3710 Handle<mirror::ArtMethod> method1,
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003711 Handle<mirror::ArtMethod> method2,
3712 std::string* error_msg)
Ian Rogersb5fb2072014-12-02 17:22:02 -08003713 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3714 {
3715 StackHandleScope<1> hs(self);
3716 Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType()));
Vladimir Marko862f43c2015-02-10 18:22:57 +00003717 mirror::Class* other_return_type = method2->GetReturnType();
3718 // NOTE: return_type.Get() must be sequenced after method2->GetReturnType().
3719 if (UNLIKELY(other_return_type != return_type.Get())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003720 *error_msg = StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
3721 PrettyClassAndClassLoader(return_type.Get()).c_str(),
3722 return_type.Get(),
3723 PrettyClassAndClassLoader(other_return_type).c_str(),
3724 other_return_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003725 return false;
3726 }
3727 }
3728 const DexFile::TypeList* types1 = method1->GetParameterTypeList();
3729 const DexFile::TypeList* types2 = method2->GetParameterTypeList();
3730 if (types1 == nullptr) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003731 if (types2 != nullptr && types2->Size() != 0) {
3732 *error_msg = StringPrintf("Type list mismatch with %s",
3733 PrettyMethod(method2.Get(), true).c_str());
3734 return false;
3735 }
3736 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003737 } else if (UNLIKELY(types2 == nullptr)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003738 if (types1->Size() != 0) {
3739 *error_msg = StringPrintf("Type list mismatch with %s",
3740 PrettyMethod(method2.Get(), true).c_str());
3741 return false;
3742 }
3743 return true;
Ian Rogersb5fb2072014-12-02 17:22:02 -08003744 }
3745 uint32_t num_types = types1->Size();
3746 if (UNLIKELY(num_types != types2->Size())) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003747 *error_msg = StringPrintf("Type list mismatch with %s",
3748 PrettyMethod(method2.Get(), true).c_str());
Ian Rogersb5fb2072014-12-02 17:22:02 -08003749 return false;
3750 }
3751 for (uint32_t i = 0; i < num_types; ++i) {
Vladimir Marko862f43c2015-02-10 18:22:57 +00003752 StackHandleScope<1> hs(self);
3753 Handle<mirror::Class> param_type(hs.NewHandle(
3754 method1->GetClassFromTypeIndex(types1->GetTypeItem(i).type_idx_, true)));
Ian Rogersb5fb2072014-12-02 17:22:02 -08003755 mirror::Class* other_param_type =
3756 method2->GetClassFromTypeIndex(types2->GetTypeItem(i).type_idx_, true);
Vladimir Marko862f43c2015-02-10 18:22:57 +00003757 // NOTE: param_type.Get() must be sequenced after method2->GetClassFromTypeIndex(...).
3758 if (UNLIKELY(param_type.Get() != other_param_type)) {
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003759 *error_msg = StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
3760 i,
3761 PrettyClassAndClassLoader(param_type.Get()).c_str(),
3762 param_type.Get(),
3763 PrettyClassAndClassLoader(other_param_type).c_str(),
3764 other_param_type);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003765 return false;
3766 }
3767 }
3768 return true;
3769}
3770
3771
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003772bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003773 if (klass->IsInterface()) {
3774 return true;
3775 }
Ian Rogers151f2212014-05-06 11:27:27 -07003776 // Begin with the methods local to the superclass.
Ian Rogersded66a02014-10-28 18:12:55 -07003777 Thread* self = Thread::Current();
3778 StackHandleScope<2> hs(self);
Ian Rogersb5fb2072014-12-02 17:22:02 -08003779 MutableHandle<mirror::ArtMethod> h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
3780 MutableHandle<mirror::ArtMethod> super_h_m(hs.NewHandle<mirror::ArtMethod>(nullptr));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003781 if (klass->HasSuperClass() &&
3782 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
Mingyao Yang2cdbad72014-07-16 10:44:41 -07003783 for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003784 h_m.Assign(klass->GetVTableEntry(i));
3785 super_h_m.Assign(klass->GetSuperClass()->GetVTableEntry(i));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003786 if (h_m.Get() != super_h_m.Get()) {
3787 std::string error_msg;
3788 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3789 ThrowLinkageError(klass.Get(),
3790 "Class %s method %s resolves differently in superclass %s: %s",
3791 PrettyDescriptor(klass.Get()).c_str(),
3792 PrettyMethod(h_m.Get()).c_str(),
3793 PrettyDescriptor(klass->GetSuperClass()).c_str(),
3794 error_msg.c_str());
3795 return false;
3796 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003797 }
3798 }
3799 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07003800 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
Ian Rogers151f2212014-05-06 11:27:27 -07003801 if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
3802 uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
3803 for (uint32_t j = 0; j < num_methods; ++j) {
Ian Rogersb5fb2072014-12-02 17:22:02 -08003804 h_m.Assign(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
3805 super_h_m.Assign(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
Andreas Gamped8ca52e2015-02-13 15:23:18 -08003806 if (h_m.Get() != super_h_m.Get()) {
3807 std::string error_msg;
3808 if (!HasSameSignatureWithDifferentClassLoaders(self, h_m, super_h_m, &error_msg)) {
3809 ThrowLinkageError(klass.Get(),
3810 "Class %s method %s resolves differently in interface %s: %s",
3811 PrettyDescriptor(klass.Get()).c_str(),
3812 PrettyMethod(h_m.Get()).c_str(),
3813 PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str(),
3814 error_msg.c_str());
3815 return false;
3816 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003817 }
3818 }
3819 }
3820 }
3821 return true;
3822}
3823
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003824bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
3825 bool can_init_parents) {
Mathieu Chartier0cd81352014-05-22 16:48:55 -07003826 DCHECK(c.Get() != nullptr);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003827 if (c->IsInitialized()) {
Andreas Gampe48498592014-09-10 19:48:05 -07003828 EnsurePreverifiedMethods(c);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003829 return true;
3830 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003831 const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
Mathieu Chartier524507a2014-08-27 15:28:28 -07003832 if (!success) {
3833 if (can_init_fields && can_init_parents) {
3834 CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
3835 }
3836 } else {
3837 self->AssertNoPendingException();
Ian Rogers595799e2012-01-11 17:32:51 -08003838 }
3839 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07003840}
3841
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003842void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07003843 ArtField* fields = new_class->GetIFields();
3844 for (size_t i = 0, count = new_class->NumInstanceFields(); i < count; i++) {
3845 if (fields[i].GetDeclaringClass() == temp_class) {
3846 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003847 }
3848 }
3849
3850 fields = new_class->GetSFields();
Mathieu Chartierc7853442015-03-27 14:35:38 -07003851 for (size_t i = 0, count = new_class->NumStaticFields(); i < count; i++) {
3852 if (fields[i].GetDeclaringClass() == temp_class) {
3853 fields[i].SetDeclaringClass(new_class);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003854 }
3855 }
3856
3857 mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
3858 if (methods != nullptr) {
3859 for (int index = 0; index < methods->GetLength(); index ++) {
3860 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3861 methods->Get(index)->SetDeclaringClass(new_class);
3862 }
3863 }
3864 }
3865
3866 methods = new_class->GetVirtualMethods();
3867 if (methods != nullptr) {
3868 for (int index = 0; index < methods->GetLength(); index ++) {
3869 if (methods->Get(index)->GetDeclaringClass() == temp_class) {
3870 methods->Get(index)->SetDeclaringClass(new_class);
3871 }
3872 }
3873 }
3874}
3875
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07003876bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
3877 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003878 mirror::Class** new_class) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003879 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003880
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003881 if (!LinkSuperClass(klass)) {
3882 return false;
3883 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003884 StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
3885 self, Runtime::Current()->GetImtUnimplementedMethod());
3886 if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003887 return false;
3888 }
Ian Rogers7b078e82014-09-10 14:44:24 -07003889 if (!LinkInstanceFields(self, klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003890 return false;
3891 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003892 size_t class_size;
Ian Rogers7b078e82014-09-10 14:44:24 -07003893 if (!LinkStaticFields(self, klass, &class_size)) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07003894 return false;
3895 }
3896 CreateReferenceInstanceOffsets(klass);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08003897 CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003898
3899 if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
3900 // We don't need to retire this class as it has no embedded tables or it was created the
3901 // correct size during class linker initialization.
3902 CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
3903
3904 if (klass->ShouldHaveEmbeddedImtAndVTable()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003905 klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003906 }
3907
3908 // This will notify waiters on klass that saw the not yet resolved
3909 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003910 mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003911 *new_class = klass.Get();
3912 } else {
3913 CHECK(!klass->IsResolved());
3914 // Retire the temporary class and create the correctly sized resolved class.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07003915 *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003916 if (UNLIKELY(*new_class == nullptr)) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003917 CHECK(self->IsExceptionPending()); // Expect an OOME.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003918 mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003919 return false;
3920 }
3921
3922 CHECK_EQ((*new_class)->GetClassSize(), class_size);
3923 StackHandleScope<1> hs(self);
3924 auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
3925 ObjectLock<mirror::Class> lock(self, new_class_h);
3926
3927 FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
3928
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08003929 mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
3930 ComputeModifiedUtf8Hash(descriptor));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07003931 CHECK(existing == nullptr || existing == klass.Get());
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003932
3933 // This will notify waiters on temp class that saw the not yet resolved class in the
3934 // class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003935 mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003936
3937 CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
3938 // This will notify waiters on new_class that saw the not yet resolved
3939 // class in the class_table_ during EnsureResolved.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07003940 mirror::Class::SetStatus(new_class_h, mirror::Class::kStatusResolved, self);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07003941 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003942 return true;
3943}
3944
Andreas Gampefd9eb392014-11-06 16:52:58 -08003945static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
3946 size_t* virtual_methods,
3947 size_t* direct_methods,
3948 size_t* static_fields,
3949 size_t* instance_fields) {
3950 *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
3951
3952 while (dex_data.HasNextStaticField()) {
3953 dex_data.Next();
3954 (*static_fields)++;
3955 }
3956 while (dex_data.HasNextInstanceField()) {
3957 dex_data.Next();
3958 (*instance_fields)++;
3959 }
3960 while (dex_data.HasNextDirectMethod()) {
3961 (*direct_methods)++;
3962 dex_data.Next();
3963 }
3964 while (dex_data.HasNextVirtualMethod()) {
3965 (*virtual_methods)++;
3966 dex_data.Next();
3967 }
3968 DCHECK(!dex_data.HasNext());
3969}
3970
3971static void DumpClass(std::ostream& os,
3972 const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3973 const char* suffix) {
3974 ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
3975 os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
3976 os << " Static fields:\n";
3977 while (dex_data.HasNextStaticField()) {
3978 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3979 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3980 dex_data.Next();
3981 }
3982 os << " Instance fields:\n";
3983 while (dex_data.HasNextInstanceField()) {
3984 const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
3985 os << " " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
3986 dex_data.Next();
3987 }
3988 os << " Direct methods:\n";
3989 while (dex_data.HasNextDirectMethod()) {
3990 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3991 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3992 dex_data.Next();
3993 }
3994 os << " Virtual methods:\n";
3995 while (dex_data.HasNextVirtualMethod()) {
3996 const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
3997 os << " " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
3998 dex_data.Next();
3999 }
4000}
4001
4002static std::string DumpClasses(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4003 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2) {
4004 std::ostringstream os;
4005 DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
4006 DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
4007 return os.str();
4008}
4009
4010
4011// Very simple structural check on whether the classes match. Only compares the number of
4012// methods and fields.
4013static bool SimpleStructuralCheck(const DexFile& dex_file1, const DexFile::ClassDef& dex_class_def1,
4014 const DexFile& dex_file2, const DexFile::ClassDef& dex_class_def2,
4015 std::string* error_msg) {
4016 ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
4017 ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
4018
4019 // Counters for current dex file.
4020 size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
4021 CountMethodsAndFields(dex_data1, &dex_virtual_methods1, &dex_direct_methods1, &dex_static_fields1,
4022 &dex_instance_fields1);
4023 // Counters for compile-time dex file.
4024 size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
4025 CountMethodsAndFields(dex_data2, &dex_virtual_methods2, &dex_direct_methods2, &dex_static_fields2,
4026 &dex_instance_fields2);
4027
4028 if (dex_virtual_methods1 != dex_virtual_methods2) {
4029 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4030 *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s", dex_virtual_methods1,
4031 dex_virtual_methods2, class_dump.c_str());
4032 return false;
4033 }
4034 if (dex_direct_methods1 != dex_direct_methods2) {
4035 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4036 *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s", dex_direct_methods1,
4037 dex_direct_methods2, class_dump.c_str());
4038 return false;
4039 }
4040 if (dex_static_fields1 != dex_static_fields2) {
4041 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4042 *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s", dex_static_fields1,
4043 dex_static_fields2, class_dump.c_str());
4044 return false;
4045 }
4046 if (dex_instance_fields1 != dex_instance_fields2) {
4047 std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
4048 *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s", dex_instance_fields1,
4049 dex_instance_fields2, class_dump.c_str());
4050 return false;
4051 }
4052
4053 return true;
4054}
4055
4056// Checks whether a the super-class changed from what we had at compile-time. This would
4057// invalidate quickening.
4058static bool CheckSuperClassChange(Handle<mirror::Class> klass,
4059 const DexFile& dex_file,
4060 const DexFile::ClassDef& class_def,
4061 mirror::Class* super_class)
4062 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4063 // Check for unexpected changes in the superclass.
4064 // Quick check 1) is the super_class class-loader the boot class loader? This always has
4065 // precedence.
4066 if (super_class->GetClassLoader() != nullptr &&
4067 // Quick check 2) different dex cache? Breaks can only occur for different dex files,
4068 // which is implied by different dex cache.
4069 klass->GetDexCache() != super_class->GetDexCache()) {
4070 // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
4071 // definition for the super-class, and (b) the files are in separate oat files. The oat files
4072 // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
Richard Uhler07b3c232015-03-31 15:57:54 -07004073 const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
4074 const OatFile* class_oat_file = nullptr;
4075 if (class_oat_dex_file != nullptr) {
4076 class_oat_file = class_oat_dex_file->GetOatFile();
4077 }
4078
Andreas Gampefd9eb392014-11-06 16:52:58 -08004079 if (class_oat_file != nullptr) {
Richard Uhler07b3c232015-03-31 15:57:54 -07004080 const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
4081 const OatFile* loaded_super_oat_file = nullptr;
4082 if (loaded_super_oat_dex_file != nullptr) {
4083 loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
4084 }
4085
Andreas Gampefd9eb392014-11-06 16:52:58 -08004086 if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
4087 // Now check (a).
4088 const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
4089 if (super_class_def != nullptr) {
4090 // Uh-oh, we found something. Do our check.
4091 std::string error_msg;
4092 if (!SimpleStructuralCheck(dex_file, *super_class_def,
4093 super_class->GetDexFile(), *super_class->GetClassDef(),
4094 &error_msg)) {
4095 // Print a warning to the log. This exception might be caught, e.g., as common in test
4096 // drivers. When the class is later tried to be used, we re-throw a new instance, as we
4097 // only save the type of the exception.
4098 LOG(WARNING) << "Incompatible structural change detected: " <<
4099 StringPrintf(
4100 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4101 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4102 class_oat_file->GetLocation().c_str(),
4103 loaded_super_oat_file->GetLocation().c_str(),
4104 error_msg.c_str());
4105 ThrowIncompatibleClassChangeError(klass.Get(),
4106 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
4107 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
4108 class_oat_file->GetLocation().c_str(),
4109 loaded_super_oat_file->GetLocation().c_str(),
4110 error_msg.c_str());
4111 return false;
4112 }
4113 }
4114 }
4115 }
4116 }
4117 return true;
4118}
4119
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004120bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004121 CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004122 const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4123 uint16_t super_class_idx = class_def.superclass_idx_;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004124 if (super_class_idx != DexFile::kDexNoIndex16) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004125 mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004126 if (super_class == nullptr) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07004127 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004128 return false;
4129 }
Ian Rogersbe125a92012-01-11 15:19:49 -08004130 // Verify
4131 if (!klass->CanAccess(super_class)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004132 ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004133 PrettyDescriptor(super_class).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004134 PrettyDescriptor(klass.Get()).c_str());
Ian Rogersbe125a92012-01-11 15:19:49 -08004135 return false;
4136 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004137 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004138 klass->SetSuperClass(super_class);
Andreas Gampefd9eb392014-11-06 16:52:58 -08004139
4140 if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
4141 DCHECK(Thread::Current()->IsExceptionPending());
4142 return false;
4143 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004144 }
Ian Rogers8b2c0b92013-09-19 02:56:49 -07004145 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004146 if (interfaces != nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004147 for (size_t i = 0; i < interfaces->Size(); i++) {
4148 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004149 mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004150 if (interface == nullptr) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004151 DCHECK(Thread::Current()->IsExceptionPending());
4152 return false;
4153 }
4154 // Verify
4155 if (!klass->CanAccess(interface)) {
4156 // TODO: the RI seemed to ignore this in my testing.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004157 ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
Ian Rogers62d6c772013-02-27 08:32:07 -08004158 PrettyDescriptor(interface).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004159 PrettyDescriptor(klass.Get()).c_str());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004160 return false;
4161 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004162 }
4163 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07004164 // Mark the class as loaded.
Hiroshi Yamauchi5b783e62015-03-18 17:20:11 -07004165 mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004166 return true;
4167}
4168
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004169bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004170 CHECK(!klass->IsPrimitive());
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004171 mirror::Class* super = klass->GetSuperClass();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004172 if (klass.Get() == GetClassRoot(kJavaLangObject)) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004173 if (super != nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004174 ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004175 return false;
4176 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004177 return true;
4178 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004179 if (super == nullptr) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004180 ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4181 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004182 return false;
4183 }
4184 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07004185 if (super->IsFinal() || super->IsInterface()) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004186 ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004187 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004188 PrettyDescriptor(klass.Get()).c_str(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004189 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004190 return false;
4191 }
4192 if (!klass->CanAccess(super)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004193 ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
Ian Rogers62d6c772013-02-27 08:32:07 -08004194 PrettyDescriptor(super).c_str(),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004195 PrettyDescriptor(klass.Get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004196 return false;
4197 }
Elliott Hughes20cde902011-10-04 17:37:27 -07004198
Brian Carlstromf3632832014-05-20 15:36:53 -07004199 // Inherit kAccClassIsFinalizable from the superclass in case this
4200 // class doesn't override finalize.
Elliott Hughes20cde902011-10-04 17:37:27 -07004201 if (super->IsFinalizable()) {
4202 klass->SetFinalizable();
4203 }
4204
Elliott Hughes2da50362011-10-10 16:57:08 -07004205 // Inherit reference flags (if any) from the superclass.
4206 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4207 if (reference_flags != 0) {
4208 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4209 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004210 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07004211 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004212 ThrowLinkageError(klass.Get(),
Ian Rogers62d6c772013-02-27 08:32:07 -08004213 "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004214 PrettyDescriptor(klass.Get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07004215 return false;
4216 }
Elliott Hughes2da50362011-10-10 16:57:08 -07004217
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004218 if (kIsDebugBuild) {
4219 // Ensure super classes are fully resolved prior to resolving fields..
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004220 while (super != nullptr) {
Ian Rogers7dfb28c2013-08-22 08:18:36 -07004221 CHECK(super->IsResolved());
4222 super = super->GetSuperClass();
4223 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004224 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004225 return true;
4226}
4227
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004228// Populate the class vtable and itable. Compute return type indices.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004229bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004230 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4231 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004232 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004233 if (klass->IsInterface()) {
4234 // No vtable.
4235 size_t count = klass->NumVirtualMethods();
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004236 if (!IsUint<16>(count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004237 ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004238 return false;
4239 }
Carl Shapiro565f5072011-07-10 13:39:43 -07004240 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004241 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004242 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004243 } else if (!LinkVirtualMethods(self, klass)) { // Link virtual methods first.
4244 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004245 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004246 return LinkInterfaceMethods(self, klass, interfaces, out_imt); // Link interface method last.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004247}
4248
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004249// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4250// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4251// caches in the implementation below.
4252class MethodNameAndSignatureComparator FINAL : public ValueObject {
4253 public:
4254 explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4255 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4256 dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4257 name_(nullptr), name_len_(0) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004258 DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4259 }
4260
4261 const char* GetName() {
4262 if (name_ == nullptr) {
4263 name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4264 }
4265 return name_;
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004266 }
4267
4268 bool HasSameNameAndSignature(mirror::ArtMethod* other)
4269 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4270 DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4271 const DexFile* other_dex_file = other->GetDexFile();
4272 const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4273 if (dex_file_ == other_dex_file) {
4274 return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4275 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004276 GetName(); // Only used to make sure its calculated.
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004277 uint32_t other_name_len;
4278 const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4279 &other_name_len);
4280 if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4281 return false;
4282 }
4283 return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4284 }
4285
4286 private:
4287 // Dex file for the method to compare against.
4288 const DexFile* const dex_file_;
4289 // MethodId for the method to compare against.
4290 const DexFile::MethodId* const mid_;
4291 // Lazily computed name from the dex file's strings.
4292 const char* name_;
4293 // Lazily computed name length.
4294 uint32_t name_len_;
4295};
4296
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004297class LinkVirtualHashTable {
4298 public:
4299 LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4300 : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4301 std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4302 }
4303 void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4304 mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4305 const char* name = local_method->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004306 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004307 uint32_t index = hash % hash_size_;
4308 // Linear probe until we have an empty slot.
4309 while (hash_table_[index] != invalid_index_) {
4310 if (++index == hash_size_) {
4311 index = 0;
4312 }
4313 }
4314 hash_table_[index] = virtual_method_index;
4315 }
4316 uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4317 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4318 const char* name = comparator->GetName();
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08004319 uint32_t hash = ComputeModifiedUtf8Hash(name);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004320 size_t index = hash % hash_size_;
4321 while (true) {
4322 const uint32_t value = hash_table_[index];
4323 // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4324 // the block and can safely assume not found.
4325 if (value == invalid_index_) {
4326 break;
4327 }
4328 if (value != removed_index_) { // This signifies not already overriden.
4329 mirror::ArtMethod* virtual_method =
4330 klass_->GetVirtualMethodDuringLinking(value);
4331 if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4332 hash_table_[index] = removed_index_;
4333 return value;
4334 }
4335 }
4336 if (++index == hash_size_) {
4337 index = 0;
4338 }
4339 }
4340 return GetNotFoundIndex();
4341 }
4342 static uint32_t GetNotFoundIndex() {
4343 return invalid_index_;
4344 }
4345
4346 private:
4347 static const uint32_t invalid_index_;
4348 static const uint32_t removed_index_;
4349
4350 Handle<mirror::Class> klass_;
4351 const size_t hash_size_;
4352 uint32_t* const hash_table_;
4353};
4354
4355const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4356const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4357
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004358bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004359 const size_t num_virtual_methods = klass->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004360 if (klass->HasSuperClass()) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004361 const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4362 const size_t max_count = num_virtual_methods + super_vtable_length;
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004363 StackHandleScope<2> hs(self);
Mingyao Yang38eecb02014-08-13 14:51:03 -07004364 Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004365 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004366 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4367 vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4368 if (UNLIKELY(vtable.Get() == nullptr)) {
4369 CHECK(self->IsExceptionPending()); // OOME.
4370 return false;
4371 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004372 for (size_t i = 0; i < super_vtable_length; i++) {
4373 vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004374 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004375 if (num_virtual_methods == 0) {
4376 klass->SetVTable(vtable.Get());
4377 return true;
4378 }
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004379 } else {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004380 mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4381 CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4382 if (num_virtual_methods == 0) {
4383 klass->SetVTable(super_vtable);
4384 return true;
4385 }
4386 vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
Mingyao Yang2cdbad72014-07-16 10:44:41 -07004387 if (UNLIKELY(vtable.Get() == nullptr)) {
4388 CHECK(self->IsExceptionPending()); // OOME.
4389 return false;
4390 }
Ian Rogersa436fde2013-08-27 23:34:06 -07004391 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004392 // How the algorithm works:
4393 // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4394 // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4395 // method which has not been matched to a vtable method, and j if the virtual method at the
4396 // index overrode the super virtual method at index j.
4397 // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4398 // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4399 // the need for the initial vtable which we later shrink back down).
4400 // 3. Add non overridden methods to the end of the vtable.
4401 static constexpr size_t kMaxStackHash = 250;
4402 const size_t hash_table_size = num_virtual_methods * 3;
4403 uint32_t* hash_table_ptr;
4404 std::unique_ptr<uint32_t[]> hash_heap_storage;
4405 if (hash_table_size <= kMaxStackHash) {
4406 hash_table_ptr = reinterpret_cast<uint32_t*>(
4407 alloca(hash_table_size * sizeof(*hash_table_ptr)));
4408 } else {
4409 hash_heap_storage.reset(new uint32_t[hash_table_size]);
4410 hash_table_ptr = hash_heap_storage.get();
4411 }
4412 LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4413 // Add virtual methods to the hash table.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004414 for (size_t i = 0; i < num_virtual_methods; ++i) {
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004415 hash_table.Add(i);
4416 }
4417 // Loop through each super vtable method and see if they are overriden by a method we added to
4418 // the hash table.
4419 for (size_t j = 0; j < super_vtable_length; ++j) {
4420 // Search the hash table to see if we are overidden by any method.
4421 mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4422 MethodNameAndSignatureComparator super_method_name_comparator(
4423 super_method->GetInterfaceMethodIfProxy());
4424 uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4425 if (hash_index != hash_table.GetNotFoundIndex()) {
4426 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4427 if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4428 super_method->GetAccessFlags())) {
4429 if (super_method->IsFinal()) {
4430 ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4431 PrettyMethod(virtual_method).c_str(),
4432 super_method->GetDeclaringClassDescriptor());
4433 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004434 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004435 vtable->SetWithoutChecks<false>(j, virtual_method);
4436 virtual_method->SetMethodIndex(j);
4437 } else {
4438 LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004439 << " would have incorrectly overridden the package-private method in "
4440 << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004441 }
4442 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004443 }
4444 // Add the non overridden methods at the end.
4445 size_t actual_count = super_vtable_length;
4446 for (size_t i = 0; i < num_virtual_methods; ++i) {
4447 mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4448 size_t method_idx = local_method->GetMethodIndexDuringLinking();
4449 if (method_idx < super_vtable_length &&
4450 local_method == vtable->GetWithoutChecks(method_idx)) {
4451 continue;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004452 }
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004453 vtable->SetWithoutChecks<false>(actual_count, local_method);
4454 local_method->SetMethodIndex(actual_count);
4455 ++actual_count;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004456 }
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004457 if (!IsUint<16>(actual_count)) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004458 ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004459 return false;
4460 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004461 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004462 CHECK_LE(actual_count, max_count);
4463 if (actual_count < max_count) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004464 vtable.Assign(vtable->CopyOf(self, actual_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004465 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004466 CHECK(self->IsExceptionPending()); // OOME.
4467 return false;
4468 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004469 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004470 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004471 } else {
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004472 CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
Andreas Gampeab1eb0d2015-02-13 19:23:55 -08004473 if (!IsUint<16>(num_virtual_methods)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004474 ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4475 static_cast<int>(num_virtual_methods));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004476 return false;
4477 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004478 mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4479 if (UNLIKELY(vtable == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004480 CHECK(self->IsExceptionPending()); // OOME.
4481 return false;
4482 }
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07004483 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromea46f952013-07-30 01:26:50 -07004484 mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004485 vtable->SetWithoutChecks<false>(i, virtual_method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004486 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004487 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004488 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004489 }
4490 return true;
4491}
4492
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004493bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4494 Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4495 StackHandleScope<mirror::Class::kImtSize>* out_imt) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004496 StackHandleScope<3> hs(self);
Mathieu Chartierbfd9a432014-05-21 17:43:44 -07004497 Runtime* const runtime = Runtime::Current();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004498 const bool has_superclass = klass->HasSuperClass();
4499 const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4500 const bool have_interfaces = interfaces.Get() != nullptr;
4501 const size_t num_interfaces =
4502 have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4503 if (num_interfaces == 0) {
4504 if (super_ifcount == 0) {
4505 // Class implements no interfaces.
4506 DCHECK_EQ(klass->GetIfTableCount(), 0);
4507 DCHECK(klass->GetIfTable() == nullptr);
4508 return true;
4509 }
Ian Rogers9bc81912012-10-11 21:43:36 -07004510 // Class implements same interfaces as parent, are any of these not marker interfaces?
4511 bool has_non_marker_interface = false;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004512 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004513 for (size_t i = 0; i < super_ifcount; ++i) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004514 if (super_iftable->GetMethodArrayCount(i) > 0) {
4515 has_non_marker_interface = true;
4516 break;
4517 }
4518 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004519 // Class just inherits marker interfaces from parent so recycle parent's iftable.
Ian Rogers9bc81912012-10-11 21:43:36 -07004520 if (!has_non_marker_interface) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004521 klass->SetIfTable(super_iftable);
4522 return true;
4523 }
4524 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004525 size_t ifcount = super_ifcount + num_interfaces;
4526 for (size_t i = 0; i < num_interfaces; i++) {
4527 mirror::Class* interface = have_interfaces ?
4528 interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4529 DCHECK(interface != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004530 if (UNLIKELY(!interface->IsInterface())) {
4531 std::string temp;
4532 ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4533 PrettyDescriptor(klass.Get()).c_str(),
4534 PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4535 return false;
4536 }
4537 ifcount += interface->GetIfTableCount();
4538 }
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004539 MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004540 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004541 CHECK(self->IsExceptionPending()); // OOME.
4542 return false;
4543 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004544 if (super_ifcount != 0) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004545 mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004546 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004547 mirror::Class* super_interface = super_iftable->GetInterface(i);
Ian Rogers9bc81912012-10-11 21:43:36 -07004548 iftable->SetInterface(i, super_interface);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004549 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004550 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004551 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004552 // Flatten the interface inheritance hierarchy.
4553 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08004554 for (size_t i = 0; i < num_interfaces; i++) {
Mathieu Chartierd035c2d2014-10-27 17:30:20 -07004555 mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4556 mirror::Class::GetDirectInterface(self, klass, i);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004557 // Check if interface is already in iftable
4558 bool duplicate = false;
4559 for (size_t j = 0; j < idx; j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004560 mirror::Class* existing_interface = iftable->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004561 if (existing_interface == interface) {
4562 duplicate = true;
4563 break;
4564 }
4565 }
4566 if (!duplicate) {
4567 // Add this non-duplicate interface.
Ian Rogers9bc81912012-10-11 21:43:36 -07004568 iftable->SetInterface(idx++, interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004569 // Add this interface's non-duplicate super-interfaces.
4570 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004571 mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004572 bool super_duplicate = false;
4573 for (size_t k = 0; k < idx; k++) {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004574 mirror::Class* existing_interface = iftable->GetInterface(k);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004575 if (existing_interface == super_interface) {
4576 super_duplicate = true;
4577 break;
4578 }
4579 }
4580 if (!super_duplicate) {
Ian Rogers9bc81912012-10-11 21:43:36 -07004581 iftable->SetInterface(idx++, super_interface);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004582 }
4583 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004584 }
4585 }
Ian Rogers7b078e82014-09-10 14:44:24 -07004586 self->AllowThreadSuspension();
Ian Rogersb52b01a2012-01-12 17:01:38 -08004587 // Shrink iftable in case duplicates were found
4588 if (idx < ifcount) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004589 DCHECK_NE(num_interfaces, 0U);
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004590 iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004591 if (UNLIKELY(iftable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004592 CHECK(self->IsExceptionPending()); // OOME.
4593 return false;
4594 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08004595 ifcount = idx;
4596 } else {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004597 DCHECK_EQ(idx, ifcount);
Ian Rogersb52b01a2012-01-12 17:01:38 -08004598 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004599 klass->SetIfTable(iftable.Get());
Elliott Hughes4681c802011-09-25 18:04:37 -07004600 // If we're an interface, we don't need the vtable pointers, so we're done.
Ian Rogers9bc81912012-10-11 21:43:36 -07004601 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004602 return true;
4603 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004604 size_t miranda_list_size = 0;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004605 size_t max_miranda_methods = 0; // The max size of miranda_list.
4606 for (size_t i = 0; i < ifcount; ++i) {
4607 max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4608 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004609 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004610 miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004611 MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4612 hs.NewHandle(klass->GetVTableDuringLinking()));
4613 // Copy the IMT from the super class if possible.
4614 bool extend_super_iftable = false;
4615 if (has_superclass) {
4616 mirror::Class* super_class = klass->GetSuperClass();
4617 extend_super_iftable = true;
4618 if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4619 for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
4620 out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
4621 }
4622 } else {
4623 // No imt in the super class, need to reconstruct from the iftable.
4624 mirror::IfTable* if_table = super_class->GetIfTable();
4625 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4626 const size_t length = super_class->GetIfTableCount();
4627 for (size_t i = 0; i < length; ++i) {
4628 mirror::Class* interface = iftable->GetInterface(i);
4629 const size_t num_virtuals = interface->NumVirtualMethods();
4630 const size_t method_array_count = if_table->GetMethodArrayCount(i);
4631 DCHECK_EQ(num_virtuals, method_array_count);
4632 if (method_array_count == 0) {
4633 continue;
4634 }
4635 mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
4636 for (size_t j = 0; j < num_virtuals; ++j) {
4637 mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
4638 if (method->IsMiranda()) {
4639 continue;
4640 }
4641 mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
4642 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4643 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4644 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4645 out_imt->SetReference(imt_index, method);
4646 } else if (imt_ref != conflict_method) {
4647 out_imt->SetReference(imt_index, conflict_method);
4648 }
4649 }
4650 }
4651 }
4652 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07004653 for (size_t i = 0; i < ifcount; ++i) {
Ian Rogers7b078e82014-09-10 14:44:24 -07004654 self->AllowThreadSuspension();
Mathieu Chartierc528dba2013-11-26 12:00:11 -08004655 size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
Ian Rogers9bc81912012-10-11 21:43:36 -07004656 if (num_methods > 0) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004657 StackHandleScope<2> hs2(self);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004658 const bool is_super = i < super_ifcount;
4659 const bool super_interface = is_super && extend_super_iftable;
4660 Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
4661 Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
4662 if (super_interface) {
4663 mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
4664 DCHECK(if_table != nullptr);
4665 DCHECK(if_table->GetMethodArray(i) != nullptr);
4666 // If we are working on a super interface, try extending the existing method array.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004667 method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004668 AsObjectArray<mirror::ArtMethod>());
4669 // We are overwriting a super class interface, try to only virtual methods instead of the
4670 // whole vtable.
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004671 input_array = hs2.NewHandle(klass->GetVirtualMethods());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004672 } else {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004673 method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004674 // A new interface, we need the whole vtable incase a new interface method is implemented
4675 // in the whole superclass.
4676 input_array = vtable;
4677 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004678 if (UNLIKELY(method_array.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004679 CHECK(self->IsExceptionPending()); // OOME.
4680 return false;
4681 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004682 iftable->SetMethodArray(i, method_array.Get());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004683 if (input_array.Get() == nullptr) {
4684 // If the added virtual methods is empty, do nothing.
4685 DCHECK(super_interface);
4686 continue;
4687 }
Ian Rogers62d6c772013-02-27 08:32:07 -08004688 for (size_t j = 0; j < num_methods; ++j) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004689 mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004690 MethodNameAndSignatureComparator interface_name_comparator(
4691 interface_method->GetInterfaceMethodIfProxy());
Ian Rogers9bc81912012-10-11 21:43:36 -07004692 int32_t k;
4693 // For each method listed in the interface's method list, find the
4694 // matching method in our class's method list. We want to favor the
4695 // subclass over the superclass, which just requires walking
4696 // back from the end of the vtable. (This only matters if the
4697 // superclass defines a private method and this class redefines
4698 // it -- otherwise it would use the same vtable slot. In .dex files
4699 // those don't end up in the virtual method table, so it shouldn't
4700 // matter which direction we go. We walk it backward anyway.)
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004701 for (k = input_array->GetLength() - 1; k >= 0; --k) {
4702 mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004703 mirror::ArtMethod* vtable_method_for_name_comparison =
4704 vtable_method->GetInterfaceMethodIfProxy();
4705 if (interface_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004706 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004707 if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004708 ThrowIllegalAccessError(
4709 klass.Get(),
4710 "Method '%s' implementing interface method '%s' is not public",
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004711 PrettyMethod(vtable_method).c_str(),
4712 PrettyMethod(interface_method).c_str());
Ian Rogers9bc81912012-10-11 21:43:36 -07004713 return false;
4714 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004715 method_array->SetWithoutChecks<false>(j, vtable_method);
Jeff Hao88474b42013-10-23 16:24:40 -07004716 // Place method in imt if entry is empty, place conflict otherwise.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004717 uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4718 mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
4719 mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
4720 if (imt_ref == runtime->GetImtUnimplementedMethod()) {
4721 out_imt->SetReference(imt_index, vtable_method);
4722 } else if (imt_ref != conflict_method) {
4723 // If we are not a conflict and we have the same signature and name as the imt entry,
4724 // it must be that we overwrote a superclass vtable entry.
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004725 MethodNameAndSignatureComparator imt_ref_name_comparator(
4726 imt_ref->GetInterfaceMethodIfProxy());
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004727 if (imt_ref_name_comparator.HasSameNameAndSignature(
Mathieu Chartier9f3629d2014-10-28 18:23:02 -07004728 vtable_method_for_name_comparison)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004729 out_imt->SetReference(imt_index, vtable_method);
4730 } else {
4731 out_imt->SetReference(imt_index, conflict_method);
4732 }
Jeff Hao88474b42013-10-23 16:24:40 -07004733 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004734 break;
4735 }
4736 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004737 if (k < 0 && !super_interface) {
4738 mirror::ArtMethod* miranda_method = nullptr;
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004739 for (size_t l = 0; l < miranda_list_size; ++l) {
4740 mirror::ArtMethod* mir_method = miranda_list->Get(l);
Ian Rogers03b6eaf2014-10-28 09:34:57 -07004741 if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004742 miranda_method = mir_method;
Ian Rogers9bc81912012-10-11 21:43:36 -07004743 break;
4744 }
4745 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004746 if (miranda_method == nullptr) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004747 // Point the interface table at a phantom slot.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004748 miranda_method = interface_method->Clone(self)->AsArtMethod();
4749 if (UNLIKELY(miranda_method == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004750 CHECK(self->IsExceptionPending()); // OOME.
4751 return false;
4752 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004753 DCHECK_LT(miranda_list_size, max_miranda_methods);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004754 miranda_list->Set<false>(miranda_list_size++, miranda_method);
Ian Rogers9bc81912012-10-11 21:43:36 -07004755 }
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004756 method_array->SetWithoutChecks<false>(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004757 }
4758 }
4759 }
4760 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004761 if (miranda_list_size > 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07004762 int old_method_count = klass->NumVirtualMethods();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004763 int new_method_count = old_method_count + miranda_list_size;
Ian Rogersa436fde2013-08-27 23:34:06 -07004764 mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4765 if (old_method_count == 0) {
4766 virtuals = AllocArtMethodArray(self, new_method_count);
4767 } else {
4768 virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4769 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004770 if (UNLIKELY(virtuals == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004771 CHECK(self->IsExceptionPending()); // OOME.
4772 return false;
4773 }
4774 klass->SetVirtualMethods(virtuals);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004775
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004776 int old_vtable_count = vtable->GetLength();
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004777 int new_vtable_count = old_vtable_count + miranda_list_size;
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004778 vtable.Assign(vtable->CopyOf(self, new_vtable_count));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004779 if (UNLIKELY(vtable.Get() == nullptr)) {
Ian Rogersa436fde2013-08-27 23:34:06 -07004780 CHECK(self->IsExceptionPending()); // OOME.
4781 return false;
4782 }
Hiroshi Yamauchi41369d22014-08-19 13:10:36 -07004783 for (size_t i = 0; i < miranda_list_size; ++i) {
4784 mirror::ArtMethod* method = miranda_list->Get(i);
Ian Rogers9074b992011-10-26 17:41:55 -07004785 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07004786 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4787 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4788 klass->SetVirtualMethod(old_method_count + i, method);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004789 vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004790 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004791 // TODO: do not assign to the vtable field until it is fully constructed.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07004792 klass->SetVTable(vtable.Get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004793 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004794
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004795 if (kIsDebugBuild) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08004796 mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
4797 for (int i = 0; i < check_vtable->GetLength(); ++i) {
4798 CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07004799 }
Elliott Hughes4681c802011-09-25 18:04:37 -07004800 }
4801
Ian Rogers7b078e82014-09-10 14:44:24 -07004802 self->AllowThreadSuspension();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004803 return true;
4804}
4805
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004806bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004807 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004808 return LinkFields(self, klass, false, nullptr);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004809}
4810
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004811bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004812 CHECK(klass.Get() != nullptr);
Ian Rogers7b078e82014-09-10 14:44:24 -07004813 return LinkFields(self, klass, true, class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -07004814}
4815
Brian Carlstromdbc05252011-09-09 01:59:59 -07004816struct LinkFieldsComparator {
Mathieu Chartier590fee92013-09-13 13:46:47 -07004817 explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4818 }
Ian Rogers00f7d0e2012-07-19 15:28:27 -07004819 // No thread safety analysis as will be called from STL. Checked lock held in constructor.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004820 bool operator()(ArtField* field1, ArtField* field2)
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004821 NO_THREAD_SAFETY_ANALYSIS {
Fred Shih37f05ef2014-07-16 18:38:08 -07004822 // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit.
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004823 Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4824 Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
Ian Rogersef7d42f2014-01-06 12:55:46 -08004825 if (type1 != type2) {
Vladimir Markod5777482014-11-12 17:02:02 +00004826 if (type1 == Primitive::kPrimNot) {
4827 // Reference always goes first.
4828 return true;
Ian Rogersef7d42f2014-01-06 12:55:46 -08004829 }
Vladimir Markod5777482014-11-12 17:02:02 +00004830 if (type2 == Primitive::kPrimNot) {
4831 // Reference always goes first.
4832 return false;
4833 }
4834 size_t size1 = Primitive::ComponentSize(type1);
4835 size_t size2 = Primitive::ComponentSize(type2);
4836 if (size1 != size2) {
4837 // Larger primitive types go first.
4838 return size1 > size2;
4839 }
4840 // Primitive types differ but sizes match. Arbitrarily order by primitive type.
4841 return type1 < type2;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004842 }
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004843 // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
4844 // by name and for equal names by type id index.
4845 // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
4846 return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
Brian Carlstromdbc05252011-09-09 01:59:59 -07004847 }
4848};
4849
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004850bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
Ian Rogers7b078e82014-09-10 14:44:24 -07004851 size_t* class_size) {
4852 self->AllowThreadSuspension();
Mathieu Chartierc7853442015-03-27 14:35:38 -07004853 const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
4854 ArtField* const fields = is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004855
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004856 // Initialize field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07004857 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004858 if (is_static) {
Vladimir Marko76649e82014-11-10 18:32:59 +00004859 field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004860 } else {
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08004861 mirror::Class* super_class = klass->GetSuperClass();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004862 if (super_class != nullptr) {
Brian Carlstromf3632832014-05-20 15:36:53 -07004863 CHECK(super_class->IsResolved())
4864 << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004865 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004866 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004867 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004868
Andreas Gampe2ed8def2014-08-28 14:41:02 -07004869 CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004870
Brian Carlstromdbc05252011-09-09 01:59:59 -07004871 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07004872 // minimizes disruption of C++ version such as Class and Method.
Mathieu Chartierc7853442015-03-27 14:35:38 -07004873 std::deque<ArtField*> grouped_and_sorted_fields;
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -07004874 const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
Fred Shih37f05ef2014-07-16 18:38:08 -07004875 "Naked ArtField references in deque");
Brian Carlstromdbc05252011-09-09 01:59:59 -07004876 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004877 grouped_and_sorted_fields.push_back(&fields[i]);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004878 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07004879 std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4880 LinkFieldsComparator());
Brian Carlstromdbc05252011-09-09 01:59:59 -07004881
Fred Shih381e4ca2014-08-25 17:24:27 -07004882 // References should be at the front.
Brian Carlstromdbc05252011-09-09 01:59:59 -07004883 size_t current_field = 0;
4884 size_t num_reference_fields = 0;
Fred Shih381e4ca2014-08-25 17:24:27 -07004885 FieldGaps gaps;
4886
Brian Carlstromdbc05252011-09-09 01:59:59 -07004887 for (; current_field < num_fields; current_field++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004888 ArtField* field = grouped_and_sorted_fields.front();
Mathieu Chartier61c5ebc2014-06-05 17:42:53 -07004889 Primitive::Type type = field->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07004890 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07004891 if (isPrimitive) {
Brian Carlstrom7934ac22013-07-26 10:54:15 -07004892 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004893 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004894 if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
4895 field_offset.Uint32Value()))) {
Fred Shih381e4ca2014-08-25 17:24:27 -07004896 MemberOffset old_offset = field_offset;
4897 field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
4898 AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
4899 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004900 DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07004901 grouped_and_sorted_fields.pop_front();
4902 num_reference_fields++;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004903 field->SetOffset(field_offset);
Vladimir Marko76649e82014-11-10 18:32:59 +00004904 field_offset = MemberOffset(field_offset.Uint32Value() +
4905 sizeof(mirror::HeapReference<mirror::Object>));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004906 }
Fred Shih381e4ca2014-08-25 17:24:27 -07004907 // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
4908 // otherwise we could end up with suboptimal gap fills.
Vladimir Marko76649e82014-11-10 18:32:59 +00004909 ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4910 ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4911 ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
4912 ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
Fred Shih37f05ef2014-07-16 18:38:08 -07004913 CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
4914 " fields.";
Ian Rogers7b078e82014-09-10 14:44:24 -07004915 self->EndAssertNoThreadSuspension(old_no_suspend_cause);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004916
Elliott Hughesadb460d2011-10-05 17:02:34 -07004917 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Mathieu Chartier0cd81352014-05-22 16:48:55 -07004918 if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07004919 // We know there are no non-reference fields in the Reference classes, and we know
4920 // that 'referent' is alphabetically last, so this is easy...
Brian Carlstromf3632832014-05-20 15:36:53 -07004921 CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
Mathieu Chartierc7853442015-03-27 14:35:38 -07004922 CHECK_STREQ(fields[num_fields - 1].GetName(), "referent") << PrettyClass(klass.Get());
Elliott Hughesadb460d2011-10-05 17:02:34 -07004923 --num_reference_fields;
4924 }
4925
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004926 size_t size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004927 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004928 if (is_static) {
4929 klass->SetNumReferenceStaticFields(num_reference_fields);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07004930 *class_size = size;
Brian Carlstrom3320cf42011-10-04 14:58:28 -07004931 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004932 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07004933 if (!klass->IsVariableSize()) {
Mathieu Chartier2d721012014-11-10 11:08:06 -08004934 if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
Jeff Haoc7d11882015-02-03 15:08:39 -08004935 size_t pointer_size = GetInstructionSetPointerSize(Runtime::Current()->GetInstructionSet());
4936 klass->SetObjectSize(mirror::ArtMethod::InstanceSize(pointer_size));
Mathieu Chartier2d721012014-11-10 11:08:06 -08004937 } else {
4938 std::string temp;
4939 DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
4940 size_t previous_size = klass->GetObjectSize();
4941 if (previous_size != 0) {
4942 // Make sure that we didn't originally have an incorrect size.
4943 CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
4944 }
4945 klass->SetObjectSize(size);
Mathieu Chartier79b4f382013-10-23 15:21:37 -07004946 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004947 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07004948 }
Vladimir Marko76649e82014-11-10 18:32:59 +00004949
4950 if (kIsDebugBuild) {
4951 // Make sure that the fields array is ordered by name but all reference
4952 // offsets are at the beginning as far as alignment allows.
4953 MemberOffset start_ref_offset = is_static
4954 ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
4955 : klass->GetFirstReferenceInstanceFieldOffset();
4956 MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
4957 num_reference_fields *
4958 sizeof(mirror::HeapReference<mirror::Object>));
4959 MemberOffset current_ref_offset = start_ref_offset;
4960 for (size_t i = 0; i < num_fields; i++) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004961 ArtField* field = &fields[i];
4962 VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
4963 << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
4964 << field->GetOffset();
Vladimir Marko76649e82014-11-10 18:32:59 +00004965 if (i != 0) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07004966 ArtField* const prev_field = &fields[i - 1];
Vladimir Marko7a7c1db2014-11-17 15:13:34 +00004967 // NOTE: The field names can be the same. This is not possible in the Java language
4968 // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
4969 CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
Vladimir Marko76649e82014-11-10 18:32:59 +00004970 }
4971 Primitive::Type type = field->GetTypeAsPrimitiveType();
4972 bool is_primitive = type != Primitive::kPrimNot;
4973 if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
4974 strcmp("referent", field->GetName()) == 0) {
4975 is_primitive = true; // We lied above, so we have to expect a lie here.
4976 }
4977 MemberOffset offset = field->GetOffsetDuringLinking();
4978 if (is_primitive) {
4979 if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
4980 // Shuffled before references.
4981 size_t type_size = Primitive::ComponentSize(type);
4982 CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
4983 CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
4984 CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
4985 CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
4986 }
4987 } else {
4988 CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
4989 current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
4990 sizeof(mirror::HeapReference<mirror::Object>));
4991 }
4992 }
4993 CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
4994 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004995 return true;
4996}
4997
Vladimir Marko76649e82014-11-10 18:32:59 +00004998// Set the bitmap of reference instance field offsets.
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07004999void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005000 uint32_t reference_offsets = 0;
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005001 mirror::Class* super_class = klass->GetSuperClass();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005002 // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005003 if (super_class != nullptr) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005004 reference_offsets = super_class->GetReferenceInstanceOffsets();
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005005 // Compute reference offsets unless our superclass overflowed.
5006 if (reference_offsets != mirror::Class::kClassWalkSuper) {
5007 size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
Vladimir Marko76649e82014-11-10 18:32:59 +00005008 if (num_reference_fields != 0u) {
5009 // All of the fields that contain object references are guaranteed be grouped in memory
5010 // starting at an appropriately aligned address after super class object data.
5011 uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5012 sizeof(mirror::HeapReference<mirror::Object>));
5013 uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005014 sizeof(mirror::HeapReference<mirror::Object>);
Vladimir Marko76649e82014-11-10 18:32:59 +00005015 if (start_bit + num_reference_fields > 32) {
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005016 reference_offsets = mirror::Class::kClassWalkSuper;
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005017 } else {
Vladimir Marko76649e82014-11-10 18:32:59 +00005018 reference_offsets |= (0xffffffffu << start_bit) &
5019 (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
Ian Rogerscdc1aaf2014-10-09 13:21:38 -07005020 }
5021 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07005022 }
5023 }
Mingyao Yangfaff0f02014-09-10 12:03:22 -07005024 klass->SetReferenceInstanceOffsets(reference_offsets);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005025}
5026
Mathieu Chartier590fee92013-09-13 13:46:47 -07005027mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005028 Handle<mirror::DexCache> dex_cache) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005029 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005030 mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005031 if (resolved != nullptr) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005032 return resolved;
5033 }
Ian Rogersdfb325e2013-10-30 01:00:44 -07005034 uint32_t utf16_length;
5035 const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005036 mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005037 dex_cache->SetResolvedString(string_idx, string);
5038 return string;
5039}
5040
Mathieu Chartier590fee92013-09-13 13:46:47 -07005041mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Ian Rogersef7d42f2014-01-06 12:55:46 -08005042 mirror::Class* referrer) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005043 StackHandleScope<2> hs(Thread::Current());
5044 Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5045 Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07005046 return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5047}
5048
5049mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005050 Handle<mirror::DexCache> dex_cache,
5051 Handle<mirror::ClassLoader> class_loader) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005052 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005053 mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005054 if (resolved == nullptr) {
Ian Rogers98379392014-02-24 16:53:16 -08005055 Thread* self = Thread::Current();
Ian Rogers0571d352011-11-03 19:51:38 -07005056 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Ian Rogers98379392014-02-24 16:53:16 -08005057 resolved = FindClass(self, descriptor, class_loader);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005058 if (resolved != nullptr) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05005059 // TODO: we used to throw here if resolved's class loader was not the
5060 // boot class loader. This was to permit different classes with the
5061 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005062 dex_cache->SetResolvedType(type_idx, resolved);
5063 } else {
Ian Rogers62d6c772013-02-27 08:32:07 -08005064 CHECK(self->IsExceptionPending())
Ian Rogerscab01012012-01-10 17:35:46 -08005065 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers62d6c772013-02-27 08:32:07 -08005066 // Convert a ClassNotFoundException to a NoClassDefFoundError.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005067 StackHandleScope<1> hs(self);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005068 Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
Ian Rogers62d6c772013-02-27 08:32:07 -08005069 if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005070 DCHECK(resolved == nullptr); // No Handle needed to preserve resolved.
Ian Rogers98379392014-02-24 16:53:16 -08005071 self->ClearException();
jeffhao8cd6dda2012-02-22 10:15:34 -08005072 ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
Nicolas Geoffray14691c52015-03-05 10:40:17 +00005073 self->GetException()->SetCause(cause.Get());
jeffhao8cd6dda2012-02-22 10:15:34 -08005074 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005075 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005076 }
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005077 DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
Brian Carlstromabcf7ae2013-09-23 22:19:52 -07005078 << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005079 return resolved;
5080}
5081
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005082mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
Andreas Gampe5a4b8a22014-09-11 08:30:08 -07005083 Handle<mirror::DexCache> dex_cache,
5084 Handle<mirror::ClassLoader> class_loader,
5085 Handle<mirror::ArtMethod> referrer,
Ian Rogersd91d6d62013-09-25 20:26:14 -07005086 InvokeType type) {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005087 DCHECK(dex_cache.Get() != nullptr);
Ian Rogers08f753d2012-08-24 14:35:25 -07005088 // Check for hit in the dex cache.
Brian Carlstromea46f952013-07-30 01:26:50 -07005089 mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
Mathieu Chartier0cd81352014-05-22 16:48:55 -07005090 if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005091 return resolved;
5092 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005093 // Fail, get the declaring class.
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005094 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005095 mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005096 if (klass == nullptr) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07005097 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005098 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005099 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005100 // Scan using method_idx, this saves string compares but will only hit for matching dex
5101 // caches/files.
5102 switch (type) {
5103 case kDirect: // Fall-through.
5104 case kStatic:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005105 resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005106 break;
5107 case kInterface:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005108 resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005109 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005110 break;
5111 case kSuper: // Fall-through.
5112 case kVirtual:
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005113 resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
Ian Rogers08f753d2012-08-24 14:35:25 -07005114 break;
5115 default:
5116 LOG(FATAL) << "Unreachable - invocation type: " << type;
Ian Rogers2c4257b2014-10-24 14:20:06 -07005117 UNREACHABLE();
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005118 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005119 if (resolved == nullptr) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005120 // Search by name, which works across dex files.
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005121 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
Ian Rogersd91d6d62013-09-25 20:26:14 -07005122 const Signature signature = dex_file.GetMethodSignature(method_id);
Ian Rogers08f753d2012-08-24 14:35:25 -07005123 switch (type) {
5124 case kDirect: // Fall-through.
5125 case kStatic:
jeffhao8cd6dda2012-02-22 10:15:34 -08005126 resolved = klass->FindDirectMethod(name, signature);
Ian Rogers08f753d2012-08-24 14:35:25 -07005127 break;
5128 case kInterface:
5129 resolved = klass->FindInterfaceMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005130 DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
Ian Rogers08f753d2012-08-24 14:35:25 -07005131 break;
5132 case kSuper: // Fall-through.
5133 case kVirtual:
5134 resolved = klass->FindVirtualMethod(name, signature);
5135 break;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005136 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005137 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005138 // If we found a method, check for incompatible class changes.
5139 if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
Ian Rogers08f753d2012-08-24 14:35:25 -07005140 // Be a good citizen and update the dex cache to speed subsequent calls.
5141 dex_cache->SetResolvedMethod(method_idx, resolved);
5142 return resolved;
5143 } else {
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005144 // If we had a method, it's an incompatible-class-change error.
5145 if (resolved != nullptr) {
5146 ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5147 } else {
5148 // We failed to find the method which means either an access error, an incompatible class
5149 // change, or no such method. First try to find the method among direct and virtual methods.
5150 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5151 const Signature signature = dex_file.GetMethodSignature(method_id);
5152 switch (type) {
5153 case kDirect:
5154 case kStatic:
Ian Rogers08f753d2012-08-24 14:35:25 -07005155 resolved = klass->FindVirtualMethod(name, signature);
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005156 // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5157 // have had a resolved method before, which triggers the "true" branch above.
5158 break;
5159 case kInterface:
5160 case kVirtual:
5161 case kSuper:
5162 resolved = klass->FindDirectMethod(name, signature);
5163 break;
5164 }
5165
5166 // If we found something, check that it can be accessed by the referrer.
Ian Rogerse0a02da2014-12-02 14:10:53 -08005167 bool exception_generated = false;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005168 if (resolved != nullptr && referrer.Get() != nullptr) {
5169 mirror::Class* methods_class = resolved->GetDeclaringClass();
5170 mirror::Class* referring_class = referrer->GetDeclaringClass();
5171 if (!referring_class->CanAccess(methods_class)) {
5172 ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5173 resolved, type);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005174 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005175 } else if (!referring_class->CanAccessMember(methods_class,
5176 resolved->GetAccessFlags())) {
5177 ThrowIllegalAccessErrorMethod(referring_class, resolved);
Ian Rogerse0a02da2014-12-02 14:10:53 -08005178 exception_generated = true;
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005179 }
5180 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005181 if (!exception_generated) {
5182 // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
5183 // interface methods and throw if we find the method there. If we find nothing, throw a
5184 // NoSuchMethodError.
5185 switch (type) {
5186 case kDirect:
5187 case kStatic:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005188 if (resolved != nullptr) {
5189 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5190 } else {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005191 resolved = klass->FindInterfaceMethod(name, signature);
5192 if (resolved != nullptr) {
5193 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5194 } else {
5195 ThrowNoSuchMethodError(type, klass, name, signature);
5196 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005197 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005198 break;
5199 case kInterface:
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005200 if (resolved != nullptr) {
Ian Rogerse0a02da2014-12-02 14:10:53 -08005201 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5202 } else {
5203 resolved = klass->FindVirtualMethod(name, signature);
5204 if (resolved != nullptr) {
5205 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5206 } else {
5207 ThrowNoSuchMethodError(type, klass, name, signature);
5208 }
5209 }
5210 break;
5211 case kSuper:
5212 if (resolved != nullptr) {
5213 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005214 } else {
5215 ThrowNoSuchMethodError(type, klass, name, signature);
5216 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005217 break;
5218 case kVirtual:
5219 if (resolved != nullptr) {
5220 ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5221 } else {
5222 resolved = klass->FindInterfaceMethod(name, signature);
5223 if (resolved != nullptr) {
5224 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5225 } else {
5226 ThrowNoSuchMethodError(type, klass, name, signature);
5227 }
5228 }
5229 break;
5230 }
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005231 }
Ian Rogers08f753d2012-08-24 14:35:25 -07005232 }
Ian Rogerse0a02da2014-12-02 14:10:53 -08005233 Thread::Current()->AssertPendingException();
Andreas Gampeeff0f5d2014-08-13 21:49:37 -07005234 return nullptr;
Ian Rogers08f753d2012-08-24 14:35:25 -07005235 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005236}
5237
Mathieu Chartierc7853442015-03-27 14:35:38 -07005238ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
5239 Handle<mirror::DexCache> dex_cache,
5240 Handle<mirror::ClassLoader> class_loader, bool is_static) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005241 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005242 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005243 if (resolved != nullptr) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005244 return resolved;
5245 }
5246 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005247 Thread* const self = Thread::Current();
5248 StackHandleScope<1> hs(self);
5249 Handle<mirror::Class> klass(
5250 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe58a5af82014-07-31 16:23:49 -07005251 if (klass.Get() == nullptr) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08005252 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe58a5af82014-07-31 16:23:49 -07005253 return nullptr;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005254 }
5255
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005256 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005257 resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005258 } else {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005259 resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07005260 }
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005261
Andreas Gampe58a5af82014-07-31 16:23:49 -07005262 if (resolved == nullptr) {
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005263 const char* name = dex_file.GetFieldName(field_id);
5264 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5265 if (is_static) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005266 resolved = mirror::Class::FindStaticField(self, klass, name, type);
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005267 } else {
5268 resolved = klass->FindInstanceField(name, type);
5269 }
Andreas Gampe58a5af82014-07-31 16:23:49 -07005270 if (resolved == nullptr) {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005271 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005272 return nullptr;
Ian Rogers7b0c5b42012-02-16 15:29:07 -08005273 }
Ian Rogersb067ac22011-12-13 18:05:09 -08005274 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07005275 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005276 return resolved;
5277}
5278
Mathieu Chartierc7853442015-03-27 14:35:38 -07005279ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file, uint32_t field_idx,
5280 Handle<mirror::DexCache> dex_cache,
5281 Handle<mirror::ClassLoader> class_loader) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07005282 DCHECK(dex_cache.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005283 ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
Andreas Gampe58a5af82014-07-31 16:23:49 -07005284 if (resolved != nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005285 return resolved;
5286 }
5287 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
Mathieu Chartierf8322842014-05-16 10:59:25 -07005288 Thread* self = Thread::Current();
5289 StackHandleScope<1> hs(self);
5290 Handle<mirror::Class> klass(
5291 hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005292 if (klass.Get() == nullptr) {
Ian Rogersb067ac22011-12-13 18:05:09 -08005293 DCHECK(Thread::Current()->IsExceptionPending());
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005294 return nullptr;
Ian Rogersb067ac22011-12-13 18:05:09 -08005295 }
5296
Ian Rogersdfb325e2013-10-30 01:00:44 -07005297 StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5298 StringPiece type(dex_file.StringDataByIdx(
Ian Rogersfc0e94b2013-09-23 23:51:32 -07005299 dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
Mathieu Chartierf8322842014-05-16 10:59:25 -07005300 resolved = mirror::Class::FindField(self, klass, name, type);
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005301 if (resolved != nullptr) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07005302 dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
Ian Rogersb067ac22011-12-13 18:05:09 -08005303 } else {
Mathieu Chartierf8322842014-05-16 10:59:25 -07005304 ThrowNoSuchFieldError("", klass.Get(), type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07005305 }
5306 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07005307}
5308
Brian Carlstromea46f952013-07-30 01:26:50 -07005309const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005310 uint32_t* length) {
5311 mirror::Class* declaring_class = referrer->GetDeclaringClass();
5312 mirror::DexCache* dex_cache = declaring_class->GetDexCache();
Ian Rogers4445a7e2012-10-05 17:19:13 -07005313 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogersad25ac52011-10-04 19:13:33 -07005314 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Ian Rogers19846512012-02-24 11:42:47 -08005315 return dex_file.GetMethodShorty(method_id, length);
Ian Rogersad25ac52011-10-04 19:13:33 -07005316}
5317
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005318void ClassLinker::DumpAllClasses(int flags) {
5319 if (dex_cache_image_class_lookup_required_) {
5320 MoveImageClassesToClassTable();
5321 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005322 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5323 // lock held, because it might need to resolve a field's type, which would try to take the lock.
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005324 std::vector<mirror::Class*> all_classes;
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005325 {
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005326 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005327 for (GcRoot<mirror::Class>& it : class_table_) {
5328 all_classes.push_back(it.Read());
Ian Rogers5d76c432011-10-31 21:42:49 -07005329 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07005330 }
5331
5332 for (size_t i = 0; i < all_classes.size(); ++i) {
5333 all_classes[i]->DumpClass(std::cerr, flags);
5334 }
5335}
5336
Elliott Hughes956af0f2014-12-11 14:34:28 -08005337static OatFile::OatMethod CreateOatMethod(const void* code) {
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005338 CHECK(code != nullptr);
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08005339 const uint8_t* base = reinterpret_cast<const uint8_t*>(code); // Base of data points at code.
5340 base -= sizeof(void*); // Move backward so that code_offset != 0.
5341 const uint32_t code_offset = sizeof(void*);
5342 return OatFile::OatMethod(base, code_offset);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005343}
5344
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005345bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5346 return (entry_point == GetQuickResolutionStub()) ||
5347 (quick_resolution_trampoline_ == entry_point);
5348}
5349
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005350bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5351 return (entry_point == GetQuickToInterpreterBridge()) ||
5352 (quick_to_interpreter_bridge_trampoline_ == entry_point);
5353}
5354
5355bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5356 return (entry_point == GetQuickGenericJniStub()) ||
5357 (quick_generic_jni_trampoline_ == entry_point);
5358}
5359
5360const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5361 return GetQuickGenericJniStub();
5362}
5363
Elliott Hughes956af0f2014-12-11 14:34:28 -08005364void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method,
5365 const void* method_code) const {
5366 OatFile::OatMethod oat_method = CreateOatMethod(method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005367 oat_method.LinkMethod(method);
5368 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005369}
5370
5371void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5372 if (!method->IsNative()) {
5373 method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005374 method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5375 } else {
5376 const void* quick_method_code = GetQuickGenericJniStub();
Elliott Hughes956af0f2014-12-11 14:34:28 -08005377 OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005378 oat_method.LinkMethod(method);
5379 method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005380 }
5381}
5382
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005383void ClassLinker::DumpForSigQuit(std::ostream& os) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005384 Thread* self = Thread::Current();
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005385 if (dex_cache_image_class_lookup_required_) {
Ian Rogers7b078e82014-09-10 14:44:24 -07005386 ScopedObjectAccess soa(self);
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005387 MoveImageClassesToClassTable();
5388 }
Ian Rogers7b078e82014-09-10 14:44:24 -07005389 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005390 os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5391 << class_table_.Size() << "\n";
Elliott Hughescac6cc72011-11-03 20:31:21 -07005392}
5393
Ian Rogers7dfb28c2013-08-22 08:18:36 -07005394size_t ClassLinker::NumLoadedClasses() {
5395 if (dex_cache_image_class_lookup_required_) {
5396 MoveImageClassesToClassTable();
5397 }
Ian Rogers1bf8d4d2013-05-30 00:18:49 -07005398 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005399 // Only return non zygote classes since these are the ones which apps which care about.
5400 return class_table_.Size();
Elliott Hughese27955c2011-08-26 15:21:24 -07005401}
5402
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005403pid_t ClassLinker::GetClassesLockOwner() {
Ian Rogersb726dcb2012-09-05 08:57:23 -07005404 return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
Brian Carlstrom47d237a2011-10-18 15:08:33 -07005405}
5406
5407pid_t ClassLinker::GetDexLockOwner() {
Ian Rogers00f7d0e2012-07-19 15:28:27 -07005408 return dex_lock_.GetExclusiveOwnerTid();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07005409}
5410
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08005411void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005412 DCHECK(!init_done_);
5413
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005414 DCHECK(klass != nullptr);
5415 DCHECK(klass->GetClassLoader() == nullptr);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005416
Hiroshi Yamauchi94f7b492014-07-22 18:08:23 -07005417 mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
Andreas Gampe2ed8def2014-08-28 14:41:02 -07005418 DCHECK(class_roots != nullptr);
5419 DCHECK(class_roots->Get(class_root) == nullptr);
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07005420 class_roots->Set<false>(class_root, klass);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08005421}
5422
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005423const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5424 static const char* class_roots_descriptors[] = {
5425 "Ljava/lang/Class;",
5426 "Ljava/lang/Object;",
5427 "[Ljava/lang/Class;",
5428 "[Ljava/lang/Object;",
5429 "Ljava/lang/String;",
5430 "Ljava/lang/DexCache;",
5431 "Ljava/lang/ref/Reference;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005432 "Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005433 "Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005434 "Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005435 "Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005436 "Ljava/lang/reflect/Proxy;",
5437 "[Ljava/lang/String;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005438 "[Ljava/lang/reflect/ArtMethod;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005439 "[Ljava/lang/reflect/Constructor;",
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005440 "[Ljava/lang/reflect/Field;",
Mathieu Chartierfc58af42015-04-16 18:00:39 -07005441 "[Ljava/lang/reflect/Method;",
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005442 "Ljava/lang/ClassLoader;",
5443 "Ljava/lang/Throwable;",
5444 "Ljava/lang/ClassNotFoundException;",
5445 "Ljava/lang/StackTraceElement;",
5446 "Z",
5447 "B",
5448 "C",
5449 "D",
5450 "F",
5451 "I",
5452 "J",
5453 "S",
5454 "V",
5455 "[Z",
5456 "[B",
5457 "[C",
5458 "[D",
5459 "[F",
5460 "[I",
5461 "[J",
5462 "[S",
5463 "[Ljava/lang/StackTraceElement;",
5464 };
Andreas Gampe575e78c2014-11-03 23:41:03 -08005465 static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5466 "Mismatch between class descriptors and class-root enum");
Ian Rogers6f3dbba2014-10-14 17:41:57 -07005467
5468 const char* descriptor = class_roots_descriptors[class_root];
5469 CHECK(descriptor != nullptr);
5470 return descriptor;
5471}
5472
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005473std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5474 const {
5475 std::string temp;
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005476 return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005477}
5478
5479bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005480 const GcRoot<mirror::Class>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005481 if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5482 return false;
5483 }
5484 std::string temp;
5485 return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5486}
5487
5488std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5489 const std::pair<const char*, mirror::ClassLoader*>& element) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005490 return ComputeModifiedUtf8Hash(element.first);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005491}
5492
5493bool ClassLinker::ClassDescriptorHashEquals::operator()(
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005494 const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005495 if (a.Read()->GetClassLoader() != b.second) {
5496 return false;
5497 }
5498 return a.Read()->DescriptorEquals(b.first);
5499}
5500
5501bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
Mathieu Chartier47f867a2015-03-18 10:39:00 -07005502 const char* descriptor) const {
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005503 return a.Read()->DescriptorEquals(descriptor);
5504}
5505
5506std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
Mathieu Chartiere7c9a8c2014-11-06 16:35:45 -08005507 return ComputeModifiedUtf8Hash(descriptor);
Mathieu Chartierc2e20622014-11-03 11:41:47 -08005508}
5509
Sebastien Hertz6963e442014-11-26 22:11:27 +01005510bool ClassLinker::MayBeCalledWithDirectCodePointer(mirror::ArtMethod* m) {
Mathieu Chartierd8565452015-03-26 09:41:50 -07005511 if (Runtime::Current()->UseJit()) {
5512 // JIT can have direct code pointers from any method to any other method.
5513 return true;
5514 }
Sebastien Hertz6963e442014-11-26 22:11:27 +01005515 // Non-image methods don't use direct code pointer.
5516 if (!m->GetDeclaringClass()->IsBootStrapClassLoaded()) {
5517 return false;
5518 }
5519 if (m->IsPrivate()) {
5520 // The method can only be called inside its own oat file. Therefore it won't be called using
5521 // its direct code if the oat file has been compiled in PIC mode.
Sebastien Hertz6963e442014-11-26 22:11:27 +01005522 const DexFile& dex_file = m->GetDeclaringClass()->GetDexFile();
Richard Uhler07b3c232015-03-31 15:57:54 -07005523 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Sebastien Hertz6963e442014-11-26 22:11:27 +01005524 if (oat_dex_file == nullptr) {
5525 // No oat file: the method has not been compiled.
5526 return false;
5527 }
5528 const OatFile* oat_file = oat_dex_file->GetOatFile();
5529 return oat_file != nullptr && !oat_file->IsPic();
5530 } else {
5531 // The method can be called outside its own oat file. Therefore it won't be called using its
5532 // direct code pointer only if all loaded oat files have been compiled in PIC mode.
5533 ReaderMutexLock mu(Thread::Current(), dex_lock_);
5534 for (const OatFile* oat_file : oat_files_) {
5535 if (!oat_file->IsPic()) {
5536 return true;
5537 }
5538 }
5539 return false;
5540 }
5541}
5542
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005543jobject ClassLinker::CreatePathClassLoader(Thread* self, std::vector<const DexFile*>& dex_files) {
5544 // SOAAlreadyRunnable is protected, and we need something to add a global reference.
5545 // We could move the jobject to the callers, but all call-sites do this...
5546 ScopedObjectAccessUnchecked soa(self);
5547
5548 // Register the dex files.
5549 for (const DexFile* dex_file : dex_files) {
5550 RegisterDexFile(*dex_file);
5551 }
5552
5553 // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005554 StackHandleScope<10> hs(self);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005555
Mathieu Chartierc7853442015-03-27 14:35:38 -07005556 ArtField* dex_elements_field =
5557 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005558
Mathieu Chartierc7853442015-03-27 14:35:38 -07005559 mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005560 DCHECK(dex_elements_class != nullptr);
5561 DCHECK(dex_elements_class->IsArrayClass());
Mathieu Chartierdaaf3262015-03-24 13:30:28 -07005562 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
5563 mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005564 Handle<mirror::Class> h_dex_element_class =
5565 hs.NewHandle(dex_elements_class->GetComponentType());
5566
Mathieu Chartierc7853442015-03-27 14:35:38 -07005567 ArtField* element_file_field =
5568 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
5569 DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005570
Mathieu Chartierc7853442015-03-27 14:35:38 -07005571 ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
5572 DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005573
5574 // Fill the elements array.
5575 int32_t index = 0;
5576 for (const DexFile* dex_file : dex_files) {
5577 StackHandleScope<3> hs2(self);
5578
5579 Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(self, 1));
5580 DCHECK(h_long_array.Get() != nullptr);
5581 h_long_array->Set(0, reinterpret_cast<intptr_t>(dex_file));
5582
5583 Handle<mirror::Object> h_dex_file = hs2.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005584 cookie_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005585 DCHECK(h_dex_file.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005586 cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005587
5588 Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
5589 DCHECK(h_element.Get() != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005590 element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005591
5592 h_dex_elements->Set(index, h_element.Get());
5593 index++;
5594 }
5595 DCHECK_EQ(index, h_dex_elements->GetLength());
5596
5597 // Create DexPathList.
5598 Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
Mathieu Chartierc7853442015-03-27 14:35:38 -07005599 dex_elements_field->GetDeclaringClass()->AllocObject(self));
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005600 DCHECK(h_dex_path_list.Get() != nullptr);
5601 // Set elements.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005602 dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005603
5604 // Create PathClassLoader.
5605 Handle<mirror::Class> h_path_class_class = hs.NewHandle(
5606 soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
5607 Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
5608 h_path_class_class->AllocObject(self));
5609 DCHECK(h_path_class_loader.Get() != nullptr);
5610 // Set DexPathList.
Mathieu Chartierc7853442015-03-27 14:35:38 -07005611 ArtField* path_list_field =
5612 soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
5613 DCHECK(path_list_field != nullptr);
5614 path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005615
5616 // Make a pretend boot-classpath.
5617 // TODO: Should we scan the image?
Mathieu Chartierc7853442015-03-27 14:35:38 -07005618 ArtField* const parent_field =
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005619 mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
Mathieu Chartierc7853442015-03-27 14:35:38 -07005620 "Ljava/lang/ClassLoader;");
5621 DCHECK(parent_field!= nullptr);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005622 mirror::Object* boot_cl =
5623 soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
Mathieu Chartierc7853442015-03-27 14:35:38 -07005624 parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
Andreas Gampe81c6f8d2015-03-25 17:19:53 -07005625
5626 // Make it a global ref and return.
5627 ScopedLocalRef<jobject> local_ref(
5628 soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
5629 return soa.Env()->NewGlobalRef(local_ref.get());
5630}
5631
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07005632} // namespace art