1 /*
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  */
16 
17 #include "class_linker.h"
18 
19 #include <algorithm>
20 #include <deque>
21 #include <iostream>
22 #include <memory>
23 #include <queue>
24 #include <string>
25 #include <tuple>
26 #include <unistd.h>
27 #include <unordered_map>
28 #include <utility>
29 #include <vector>
30 
31 #include "art_field-inl.h"
32 #include "art_method-inl.h"
33 #include "base/arena_allocator.h"
34 #include "base/casts.h"
35 #include "base/logging.h"
36 #include "base/scoped_arena_containers.h"
37 #include "base/scoped_flock.h"
38 #include "base/stl_util.h"
39 #include "base/systrace.h"
40 #include "base/time_utils.h"
41 #include "base/unix_file/fd_file.h"
42 #include "base/value_object.h"
43 #include "class_linker-inl.h"
44 #include "class_table-inl.h"
45 #include "compiler_callbacks.h"
46 #include "debugger.h"
47 #include "dex_file-inl.h"
48 #include "entrypoints/entrypoint_utils.h"
49 #include "entrypoints/runtime_asm_entrypoints.h"
50 #include "experimental_flags.h"
51 #include "gc_root-inl.h"
52 #include "gc/accounting/card_table-inl.h"
53 #include "gc/accounting/heap_bitmap-inl.h"
54 #include "gc/heap.h"
55 #include "gc/scoped_gc_critical_section.h"
56 #include "gc/space/image_space.h"
57 #include "handle_scope-inl.h"
58 #include "image-inl.h"
59 #include "intern_table.h"
60 #include "interpreter/interpreter.h"
61 #include "jit/jit.h"
62 #include "jit/jit_code_cache.h"
63 #include "jit/offline_profiling_info.h"
64 #include "leb128.h"
65 #include "linear_alloc.h"
66 #include "mirror/class.h"
67 #include "mirror/class-inl.h"
68 #include "mirror/class_loader.h"
69 #include "mirror/dex_cache-inl.h"
70 #include "mirror/field.h"
71 #include "mirror/iftable-inl.h"
72 #include "mirror/method.h"
73 #include "mirror/object-inl.h"
74 #include "mirror/object_array-inl.h"
75 #include "mirror/proxy.h"
76 #include "mirror/reference-inl.h"
77 #include "mirror/stack_trace_element.h"
78 #include "mirror/string-inl.h"
79 #include "native/dalvik_system_DexFile.h"
80 #include "oat.h"
81 #include "oat_file.h"
82 #include "oat_file-inl.h"
83 #include "oat_file_assistant.h"
84 #include "oat_file_manager.h"
85 #include "object_lock.h"
86 #include "os.h"
87 #include "runtime.h"
88 #include "ScopedLocalRef.h"
89 #include "scoped_thread_state_change.h"
90 #include "thread-inl.h"
91 #include "trace.h"
92 #include "utils.h"
93 #include "utils/dex_cache_arrays_layout-inl.h"
94 #include "verifier/method_verifier.h"
95 #include "well_known_classes.h"
96 
97 namespace art {
98 
99 static constexpr bool kSanityCheckObjects = kIsDebugBuild;
100 static constexpr bool kVerifyArtMethodDeclaringClasses = kIsDebugBuild;
101 
102 static void ThrowNoClassDefFoundError(const char* fmt, ...)
103     __attribute__((__format__(__printf__, 1, 2)))
104     SHARED_REQUIRES(Locks::mutator_lock_);
ThrowNoClassDefFoundError(const char * fmt,...)105 static void ThrowNoClassDefFoundError(const char* fmt, ...) {
106   va_list args;
107   va_start(args, fmt);
108   Thread* self = Thread::Current();
109   self->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
110   va_end(args);
111 }
112 
HasInitWithString(Thread * self,ClassLinker * class_linker,const char * descriptor)113 static bool HasInitWithString(Thread* self, ClassLinker* class_linker, const char* descriptor)
114     SHARED_REQUIRES(Locks::mutator_lock_) {
115   ArtMethod* method = self->GetCurrentMethod(nullptr);
116   StackHandleScope<1> hs(self);
117   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(method != nullptr ?
118       method->GetDeclaringClass()->GetClassLoader() : nullptr));
119   mirror::Class* exception_class = class_linker->FindClass(self, descriptor, class_loader);
120 
121   if (exception_class == nullptr) {
122     // No exc class ~ no <init>-with-string.
123     CHECK(self->IsExceptionPending());
124     self->ClearException();
125     return false;
126   }
127 
128   ArtMethod* exception_init_method = exception_class->FindDeclaredDirectMethod(
129       "<init>", "(Ljava/lang/String;)V", class_linker->GetImagePointerSize());
130   return exception_init_method != nullptr;
131 }
132 
133 // Helper for ThrowEarlierClassFailure. Throws the stored error.
HandleEarlierVerifyError(Thread * self,ClassLinker * class_linker,mirror::Class * c)134 static void HandleEarlierVerifyError(Thread* self, ClassLinker* class_linker, mirror::Class* c)
135     SHARED_REQUIRES(Locks::mutator_lock_) {
136   mirror::Object* obj = c->GetVerifyError();
137   DCHECK(obj != nullptr);
138   self->AssertNoPendingException();
139   if (obj->IsClass()) {
140     // Previous error has been stored as class. Create a new exception of that type.
141 
142     // It's possible the exception doesn't have a <init>(String).
143     std::string temp;
144     const char* descriptor = obj->AsClass()->GetDescriptor(&temp);
145 
146     if (HasInitWithString(self, class_linker, descriptor)) {
147       self->ThrowNewException(descriptor, PrettyDescriptor(c).c_str());
148     } else {
149       self->ThrowNewException(descriptor, nullptr);
150     }
151   } else {
152     // Previous error has been stored as an instance. Just rethrow.
153     mirror::Class* throwable_class =
154         self->DecodeJObject(WellKnownClasses::java_lang_Throwable)->AsClass();
155     mirror::Class* error_class = obj->GetClass();
156     CHECK(throwable_class->IsAssignableFrom(error_class));
157     self->SetException(obj->AsThrowable());
158   }
159   self->AssertPendingException();
160 }
161 
ThrowEarlierClassFailure(mirror::Class * c,bool wrap_in_no_class_def)162 void ClassLinker::ThrowEarlierClassFailure(mirror::Class* c, bool wrap_in_no_class_def) {
163   // The class failed to initialize on a previous attempt, so we want to throw
164   // a NoClassDefFoundError (v2 2.17.5).  The exception to this rule is if we
165   // failed in verification, in which case v2 5.4.1 says we need to re-throw
166   // the previous error.
167   Runtime* const runtime = Runtime::Current();
168   if (!runtime->IsAotCompiler()) {  // Give info if this occurs at runtime.
169     std::string extra;
170     if (c->GetVerifyError() != nullptr) {
171       mirror::Object* verify_error = c->GetVerifyError();
172       if (verify_error->IsClass()) {
173         extra = PrettyDescriptor(verify_error->AsClass());
174       } else {
175         extra = verify_error->AsThrowable()->Dump();
176       }
177     }
178     LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c) << ": " << extra;
179   }
180 
181   CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
182   Thread* self = Thread::Current();
183   if (runtime->IsAotCompiler()) {
184     // At compile time, accurate errors and NCDFE are disabled to speed compilation.
185     mirror::Throwable* pre_allocated = runtime->GetPreAllocatedNoClassDefFoundError();
186     self->SetException(pre_allocated);
187   } else {
188     if (c->GetVerifyError() != nullptr) {
189       // Rethrow stored error.
190       HandleEarlierVerifyError(self, this, c);
191     }
192     if (c->GetVerifyError() == nullptr || wrap_in_no_class_def) {
193       // If there isn't a recorded earlier error, or this is a repeat throw from initialization,
194       // the top-level exception must be a NoClassDefFoundError. The potentially already pending
195       // exception will be a cause.
196       self->ThrowNewWrappedException("Ljava/lang/NoClassDefFoundError;",
197                                      PrettyDescriptor(c).c_str());
198     }
199   }
200 }
201 
VlogClassInitializationFailure(Handle<mirror::Class> klass)202 static void VlogClassInitializationFailure(Handle<mirror::Class> klass)
203     SHARED_REQUIRES(Locks::mutator_lock_) {
204   if (VLOG_IS_ON(class_linker)) {
205     std::string temp;
206     LOG(INFO) << "Failed to initialize class " << klass->GetDescriptor(&temp) << " from "
207               << klass->GetLocation() << "\n" << Thread::Current()->GetException()->Dump();
208   }
209 }
210 
WrapExceptionInInitializer(Handle<mirror::Class> klass)211 static void WrapExceptionInInitializer(Handle<mirror::Class> klass)
212     SHARED_REQUIRES(Locks::mutator_lock_) {
213   Thread* self = Thread::Current();
214   JNIEnv* env = self->GetJniEnv();
215 
216   ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
217   CHECK(cause.get() != nullptr);
218 
219   env->ExceptionClear();
220   bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
221   env->Throw(cause.get());
222 
223   // We only wrap non-Error exceptions; an Error can just be used as-is.
224   if (!is_error) {
225     self->ThrowNewWrappedException("Ljava/lang/ExceptionInInitializerError;", nullptr);
226   }
227   VlogClassInitializationFailure(klass);
228 }
229 
230 // Gap between two fields in object layout.
231 struct FieldGap {
232   uint32_t start_offset;  // The offset from the start of the object.
233   uint32_t size;  // The gap size of 1, 2, or 4 bytes.
234 };
235 struct FieldGapsComparator {
FieldGapsComparatorart::FieldGapsComparator236   explicit FieldGapsComparator() {
237   }
operator ()art::FieldGapsComparator238   bool operator() (const FieldGap& lhs, const FieldGap& rhs)
239       NO_THREAD_SAFETY_ANALYSIS {
240     // Sort by gap size, largest first. Secondary sort by starting offset.
241     // Note that the priority queue returns the largest element, so operator()
242     // should return true if lhs is less than rhs.
243     return lhs.size < rhs.size || (lhs.size == rhs.size && lhs.start_offset > rhs.start_offset);
244   }
245 };
246 typedef std::priority_queue<FieldGap, std::vector<FieldGap>, FieldGapsComparator> FieldGaps;
247 
248 // Adds largest aligned gaps to queue of gaps.
AddFieldGap(uint32_t gap_start,uint32_t gap_end,FieldGaps * gaps)249 static void AddFieldGap(uint32_t gap_start, uint32_t gap_end, FieldGaps* gaps) {
250   DCHECK(gaps != nullptr);
251 
252   uint32_t current_offset = gap_start;
253   while (current_offset != gap_end) {
254     size_t remaining = gap_end - current_offset;
255     if (remaining >= sizeof(uint32_t) && IsAligned<4>(current_offset)) {
256       gaps->push(FieldGap {current_offset, sizeof(uint32_t)});
257       current_offset += sizeof(uint32_t);
258     } else if (remaining >= sizeof(uint16_t) && IsAligned<2>(current_offset)) {
259       gaps->push(FieldGap {current_offset, sizeof(uint16_t)});
260       current_offset += sizeof(uint16_t);
261     } else {
262       gaps->push(FieldGap {current_offset, sizeof(uint8_t)});
263       current_offset += sizeof(uint8_t);
264     }
265     DCHECK_LE(current_offset, gap_end) << "Overran gap";
266   }
267 }
268 // Shuffle fields forward, making use of gaps whenever possible.
269 template<int n>
ShuffleForward(size_t * current_field_idx,MemberOffset * field_offset,std::deque<ArtField * > * grouped_and_sorted_fields,FieldGaps * gaps)270 static void ShuffleForward(size_t* current_field_idx,
271                            MemberOffset* field_offset,
272                            std::deque<ArtField*>* grouped_and_sorted_fields,
273                            FieldGaps* gaps)
274     SHARED_REQUIRES(Locks::mutator_lock_) {
275   DCHECK(current_field_idx != nullptr);
276   DCHECK(grouped_and_sorted_fields != nullptr);
277   DCHECK(gaps != nullptr);
278   DCHECK(field_offset != nullptr);
279 
280   DCHECK(IsPowerOfTwo(n));
281   while (!grouped_and_sorted_fields->empty()) {
282     ArtField* field = grouped_and_sorted_fields->front();
283     Primitive::Type type = field->GetTypeAsPrimitiveType();
284     if (Primitive::ComponentSize(type) < n) {
285       break;
286     }
287     if (!IsAligned<n>(field_offset->Uint32Value())) {
288       MemberOffset old_offset = *field_offset;
289       *field_offset = MemberOffset(RoundUp(field_offset->Uint32Value(), n));
290       AddFieldGap(old_offset.Uint32Value(), field_offset->Uint32Value(), gaps);
291     }
292     CHECK(type != Primitive::kPrimNot) << PrettyField(field);  // should be primitive types
293     grouped_and_sorted_fields->pop_front();
294     if (!gaps->empty() && gaps->top().size >= n) {
295       FieldGap gap = gaps->top();
296       gaps->pop();
297       DCHECK_ALIGNED(gap.start_offset, n);
298       field->SetOffset(MemberOffset(gap.start_offset));
299       if (gap.size > n) {
300         AddFieldGap(gap.start_offset + n, gap.start_offset + gap.size, gaps);
301       }
302     } else {
303       DCHECK_ALIGNED(field_offset->Uint32Value(), n);
304       field->SetOffset(*field_offset);
305       *field_offset = MemberOffset(field_offset->Uint32Value() + n);
306     }
307     ++(*current_field_idx);
308   }
309 }
310 
ClassLinker(InternTable * intern_table)311 ClassLinker::ClassLinker(InternTable* intern_table)
312     // dex_lock_ is recursive as it may be used in stack dumping.
313     : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
314       dex_cache_boot_image_class_lookup_required_(false),
315       failed_dex_cache_class_lookups_(0),
316       class_roots_(nullptr),
317       array_iftable_(nullptr),
318       find_array_class_cache_next_victim_(0),
319       init_done_(false),
320       log_new_class_table_roots_(false),
321       intern_table_(intern_table),
322       quick_resolution_trampoline_(nullptr),
323       quick_imt_conflict_trampoline_(nullptr),
324       quick_generic_jni_trampoline_(nullptr),
325       quick_to_interpreter_bridge_trampoline_(nullptr),
326       image_pointer_size_(sizeof(void*)) {
327   CHECK(intern_table_ != nullptr);
328   static_assert(kFindArrayCacheSize == arraysize(find_array_class_cache_),
329                 "Array cache size wrong.");
330   std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
331 }
332 
CheckSystemClass(Thread * self,Handle<mirror::Class> c1,const char * descriptor)333 void ClassLinker::CheckSystemClass(Thread* self, Handle<mirror::Class> c1, const char* descriptor) {
334   mirror::Class* c2 = FindSystemClass(self, descriptor);
335   if (c2 == nullptr) {
336     LOG(FATAL) << "Could not find class " << descriptor;
337     UNREACHABLE();
338   }
339   if (c1.Get() != c2) {
340     std::ostringstream os1, os2;
341     c1->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
342     c2->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
343     LOG(FATAL) << "InitWithoutImage: Class mismatch for " << descriptor
344                << ". This is most likely the result of a broken build. Make sure that "
345                << "libcore and art projects match.\n\n"
346                << os1.str() << "\n\n" << os2.str();
347     UNREACHABLE();
348   }
349 }
350 
InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,std::string * error_msg)351 bool ClassLinker::InitWithoutImage(std::vector<std::unique_ptr<const DexFile>> boot_class_path,
352                                    std::string* error_msg) {
353   VLOG(startup) << "ClassLinker::Init";
354 
355   Thread* const self = Thread::Current();
356   Runtime* const runtime = Runtime::Current();
357   gc::Heap* const heap = runtime->GetHeap();
358 
359   CHECK(!heap->HasBootImageSpace()) << "Runtime has image. We should use it.";
360   CHECK(!init_done_);
361 
362   // Use the pointer size from the runtime since we are probably creating the image.
363   image_pointer_size_ = InstructionSetPointerSize(runtime->GetInstructionSet());
364   if (!ValidPointerSize(image_pointer_size_)) {
365     *error_msg = StringPrintf("Invalid image pointer size: %zu", image_pointer_size_);
366     return false;
367   }
368 
369   // java_lang_Class comes first, it's needed for AllocClass
370   // The GC can't handle an object with a null class since we can't get the size of this object.
371   heap->IncrementDisableMovingGC(self);
372   StackHandleScope<64> hs(self);  // 64 is picked arbitrarily.
373   auto class_class_size = mirror::Class::ClassClassSize(image_pointer_size_);
374   Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
375       heap->AllocNonMovableObject<true>(self, nullptr, class_class_size, VoidFunctor()))));
376   CHECK(java_lang_Class.Get() != nullptr);
377   mirror::Class::SetClassClass(java_lang_Class.Get());
378   java_lang_Class->SetClass(java_lang_Class.Get());
379   if (kUseBakerOrBrooksReadBarrier) {
380     java_lang_Class->AssertReadBarrierPointer();
381   }
382   java_lang_Class->SetClassSize(class_class_size);
383   java_lang_Class->SetPrimitiveType(Primitive::kPrimNot);
384   heap->DecrementDisableMovingGC(self);
385   // AllocClass(mirror::Class*) can now be used
386 
387   // Class[] is used for reflection support.
388   auto class_array_class_size = mirror::ObjectArray<mirror::Class>::ClassSize(image_pointer_size_);
389   Handle<mirror::Class> class_array_class(hs.NewHandle(
390       AllocClass(self, java_lang_Class.Get(), class_array_class_size)));
391   class_array_class->SetComponentType(java_lang_Class.Get());
392 
393   // java_lang_Object comes next so that object_array_class can be created.
394   Handle<mirror::Class> java_lang_Object(hs.NewHandle(
395       AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize(image_pointer_size_))));
396   CHECK(java_lang_Object.Get() != nullptr);
397   // backfill Object as the super class of Class.
398   java_lang_Class->SetSuperClass(java_lang_Object.Get());
399   mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusLoaded, self);
400 
401   java_lang_Object->SetObjectSize(sizeof(mirror::Object));
402   // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
403   // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
404   runtime->SetSentinel(heap->AllocNonMovableObject<true>(self,
405                                                          java_lang_Object.Get(),
406                                                          java_lang_Object->GetObjectSize(),
407                                                          VoidFunctor()));
408 
409   // Object[] next to hold class roots.
410   Handle<mirror::Class> object_array_class(hs.NewHandle(
411       AllocClass(self, java_lang_Class.Get(),
412                  mirror::ObjectArray<mirror::Object>::ClassSize(image_pointer_size_))));
413   object_array_class->SetComponentType(java_lang_Object.Get());
414 
415   // Setup the char (primitive) class to be used for char[].
416   Handle<mirror::Class> char_class(hs.NewHandle(
417       AllocClass(self, java_lang_Class.Get(),
418                  mirror::Class::PrimitiveClassSize(image_pointer_size_))));
419   // The primitive char class won't be initialized by
420   // InitializePrimitiveClass until line 459, but strings (and
421   // internal char arrays) will be allocated before that and the
422   // component size, which is computed from the primitive type, needs
423   // to be set here.
424   char_class->SetPrimitiveType(Primitive::kPrimChar);
425 
426   // Setup the char[] class to be used for String.
427   Handle<mirror::Class> char_array_class(hs.NewHandle(
428       AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
429   char_array_class->SetComponentType(char_class.Get());
430   mirror::CharArray::SetArrayClass(char_array_class.Get());
431 
432   // Setup String.
433   Handle<mirror::Class> java_lang_String(hs.NewHandle(
434       AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize(image_pointer_size_))));
435   java_lang_String->SetStringClass();
436   mirror::String::SetClass(java_lang_String.Get());
437   mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusResolved, self);
438 
439   // Setup java.lang.ref.Reference.
440   Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
441       AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize(image_pointer_size_))));
442   mirror::Reference::SetClass(java_lang_ref_Reference.Get());
443   java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
444   mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusResolved, self);
445 
446   // Create storage for root classes, save away our work so far (requires descriptors).
447   class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
448       mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
449                                                 kClassRootsMax));
450   CHECK(!class_roots_.IsNull());
451   SetClassRoot(kJavaLangClass, java_lang_Class.Get());
452   SetClassRoot(kJavaLangObject, java_lang_Object.Get());
453   SetClassRoot(kClassArrayClass, class_array_class.Get());
454   SetClassRoot(kObjectArrayClass, object_array_class.Get());
455   SetClassRoot(kCharArrayClass, char_array_class.Get());
456   SetClassRoot(kJavaLangString, java_lang_String.Get());
457   SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
458 
459   // Setup the primitive type classes.
460   SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
461   SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
462   SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
463   SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
464   SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
465   SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
466   SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
467   SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
468 
469   // Create array interface entries to populate once we can load system classes.
470   array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
471 
472   // Create int array type for AllocDexCache (done in AppendToBootClassPath).
473   Handle<mirror::Class> int_array_class(hs.NewHandle(
474       AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
475   int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
476   mirror::IntArray::SetArrayClass(int_array_class.Get());
477   SetClassRoot(kIntArrayClass, int_array_class.Get());
478 
479   // Create long array type for AllocDexCache (done in AppendToBootClassPath).
480   Handle<mirror::Class> long_array_class(hs.NewHandle(
481       AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize(image_pointer_size_))));
482   long_array_class->SetComponentType(GetClassRoot(kPrimitiveLong));
483   mirror::LongArray::SetArrayClass(long_array_class.Get());
484   SetClassRoot(kLongArrayClass, long_array_class.Get());
485 
486   // now that these are registered, we can use AllocClass() and AllocObjectArray
487 
488   // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
489   Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
490       AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize(image_pointer_size_))));
491   SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
492   java_lang_DexCache->SetDexCacheClass();
493   java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
494   mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusResolved, self);
495 
496   // Set up array classes for string, field, method
497   Handle<mirror::Class> object_array_string(hs.NewHandle(
498       AllocClass(self, java_lang_Class.Get(),
499                  mirror::ObjectArray<mirror::String>::ClassSize(image_pointer_size_))));
500   object_array_string->SetComponentType(java_lang_String.Get());
501   SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
502 
503   LinearAlloc* linear_alloc = runtime->GetLinearAlloc();
504   // Create runtime resolution and imt conflict methods.
505   runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
506   runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod(linear_alloc));
507   runtime->SetImtUnimplementedMethod(runtime->CreateImtConflictMethod(linear_alloc));
508 
509   // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
510   // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
511   // these roots.
512   if (boot_class_path.empty()) {
513     *error_msg = "Boot classpath is empty.";
514     return false;
515   }
516   for (auto& dex_file : boot_class_path) {
517     if (dex_file.get() == nullptr) {
518       *error_msg = "Null dex file.";
519       return false;
520     }
521     AppendToBootClassPath(self, *dex_file);
522     boot_dex_files_.push_back(std::move(dex_file));
523   }
524 
525   // now we can use FindSystemClass
526 
527   // run char class through InitializePrimitiveClass to finish init
528   InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
529   SetClassRoot(kPrimitiveChar, char_class.Get());  // needs descriptor
530 
531   // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
532   // we do not need friend classes or a publicly exposed setter.
533   quick_generic_jni_trampoline_ = GetQuickGenericJniStub();
534   if (!runtime->IsAotCompiler()) {
535     // We need to set up the generic trampolines since we don't have an image.
536     quick_resolution_trampoline_ = GetQuickResolutionStub();
537     quick_imt_conflict_trampoline_ = GetQuickImtConflictStub();
538     quick_to_interpreter_bridge_trampoline_ = GetQuickToInterpreterBridge();
539   }
540 
541   // Object, String and DexCache need to be rerun through FindSystemClass to finish init
542   mirror::Class::SetStatus(java_lang_Object, mirror::Class::kStatusNotReady, self);
543   CheckSystemClass(self, java_lang_Object, "Ljava/lang/Object;");
544   CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
545   mirror::Class::SetStatus(java_lang_String, mirror::Class::kStatusNotReady, self);
546   CheckSystemClass(self, java_lang_String, "Ljava/lang/String;");
547   mirror::Class::SetStatus(java_lang_DexCache, mirror::Class::kStatusNotReady, self);
548   CheckSystemClass(self, java_lang_DexCache, "Ljava/lang/DexCache;");
549   CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
550 
551   // Setup the primitive array type classes - can't be done until Object has a vtable.
552   SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
553   mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
554 
555   SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
556   mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
557 
558   CheckSystemClass(self, char_array_class, "[C");
559 
560   SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
561   mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
562 
563   CheckSystemClass(self, int_array_class, "[I");
564   CheckSystemClass(self, long_array_class, "[J");
565 
566   SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
567   mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
568 
569   SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
570   mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
571 
572   // Run Class through FindSystemClass. This initializes the dex_cache_ fields and register it
573   // in class_table_.
574   CheckSystemClass(self, java_lang_Class, "Ljava/lang/Class;");
575 
576   CheckSystemClass(self, class_array_class, "[Ljava/lang/Class;");
577   CheckSystemClass(self, object_array_class, "[Ljava/lang/Object;");
578 
579   // Setup the single, global copy of "iftable".
580   auto java_lang_Cloneable = hs.NewHandle(FindSystemClass(self, "Ljava/lang/Cloneable;"));
581   CHECK(java_lang_Cloneable.Get() != nullptr);
582   auto java_io_Serializable = hs.NewHandle(FindSystemClass(self, "Ljava/io/Serializable;"));
583   CHECK(java_io_Serializable.Get() != nullptr);
584   // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
585   // crawl up and explicitly list all of the supers as well.
586   array_iftable_.Read()->SetInterface(0, java_lang_Cloneable.Get());
587   array_iftable_.Read()->SetInterface(1, java_io_Serializable.Get());
588 
589   // Sanity check Class[] and Object[]'s interfaces. GetDirectInterface may cause thread
590   // suspension.
591   CHECK_EQ(java_lang_Cloneable.Get(),
592            mirror::Class::GetDirectInterface(self, class_array_class, 0));
593   CHECK_EQ(java_io_Serializable.Get(),
594            mirror::Class::GetDirectInterface(self, class_array_class, 1));
595   CHECK_EQ(java_lang_Cloneable.Get(),
596            mirror::Class::GetDirectInterface(self, object_array_class, 0));
597   CHECK_EQ(java_io_Serializable.Get(),
598            mirror::Class::GetDirectInterface(self, object_array_class, 1));
599 
600   CHECK_EQ(object_array_string.Get(),
601            FindSystemClass(self, GetClassRootDescriptor(kJavaLangStringArrayClass)));
602 
603   // End of special init trickery, all subsequent classes may be loaded via FindSystemClass.
604 
605   // Create java.lang.reflect.Proxy root.
606   SetClassRoot(kJavaLangReflectProxy, FindSystemClass(self, "Ljava/lang/reflect/Proxy;"));
607 
608   // Create java.lang.reflect.Field.class root.
609   auto* class_root = FindSystemClass(self, "Ljava/lang/reflect/Field;");
610   CHECK(class_root != nullptr);
611   SetClassRoot(kJavaLangReflectField, class_root);
612   mirror::Field::SetClass(class_root);
613 
614   // Create java.lang.reflect.Field array root.
615   class_root = FindSystemClass(self, "[Ljava/lang/reflect/Field;");
616   CHECK(class_root != nullptr);
617   SetClassRoot(kJavaLangReflectFieldArrayClass, class_root);
618   mirror::Field::SetArrayClass(class_root);
619 
620   // Create java.lang.reflect.Constructor.class root and array root.
621   class_root = FindSystemClass(self, "Ljava/lang/reflect/Constructor;");
622   CHECK(class_root != nullptr);
623   SetClassRoot(kJavaLangReflectConstructor, class_root);
624   mirror::Constructor::SetClass(class_root);
625   class_root = FindSystemClass(self, "[Ljava/lang/reflect/Constructor;");
626   CHECK(class_root != nullptr);
627   SetClassRoot(kJavaLangReflectConstructorArrayClass, class_root);
628   mirror::Constructor::SetArrayClass(class_root);
629 
630   // Create java.lang.reflect.Method.class root and array root.
631   class_root = FindSystemClass(self, "Ljava/lang/reflect/Method;");
632   CHECK(class_root != nullptr);
633   SetClassRoot(kJavaLangReflectMethod, class_root);
634   mirror::Method::SetClass(class_root);
635   class_root = FindSystemClass(self, "[Ljava/lang/reflect/Method;");
636   CHECK(class_root != nullptr);
637   SetClassRoot(kJavaLangReflectMethodArrayClass, class_root);
638   mirror::Method::SetArrayClass(class_root);
639 
640   // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
641   // finish initializing Reference class
642   mirror::Class::SetStatus(java_lang_ref_Reference, mirror::Class::kStatusNotReady, self);
643   CheckSystemClass(self, java_lang_ref_Reference, "Ljava/lang/ref/Reference;");
644   CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
645   CHECK_EQ(java_lang_ref_Reference->GetClassSize(),
646            mirror::Reference::ClassSize(image_pointer_size_));
647   class_root = FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
648   CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
649   class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagFinalizerReference);
650   class_root = FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
651   CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
652   class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagPhantomReference);
653   class_root = FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
654   CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
655   class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagSoftReference);
656   class_root = FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
657   CHECK_EQ(class_root->GetClassFlags(), mirror::kClassFlagNormal);
658   class_root->SetClassFlags(class_root->GetClassFlags() | mirror::kClassFlagWeakReference);
659 
660   // Setup the ClassLoader, verifying the object_size_.
661   class_root = FindSystemClass(self, "Ljava/lang/ClassLoader;");
662   class_root->SetClassLoaderClass();
663   CHECK_EQ(class_root->GetObjectSize(), mirror::ClassLoader::InstanceSize());
664   SetClassRoot(kJavaLangClassLoader, class_root);
665 
666   // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
667   // java.lang.StackTraceElement as a convenience.
668   SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
669   mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
670   SetClassRoot(kJavaLangClassNotFoundException,
671                FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
672   SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
673   SetClassRoot(kJavaLangStackTraceElementArrayClass,
674                FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
675   mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
676 
677   // Ensure void type is resolved in the core's dex cache so java.lang.Void is correctly
678   // initialized.
679   {
680     const DexFile& dex_file = java_lang_Object->GetDexFile();
681     const DexFile::TypeId* void_type_id = dex_file.FindTypeId("V");
682     CHECK(void_type_id != nullptr);
683     uint16_t void_type_idx = dex_file.GetIndexForTypeId(*void_type_id);
684     // Now we resolve void type so the dex cache contains it. We use java.lang.Object class
685     // as referrer so the used dex cache is core's one.
686     mirror::Class* resolved_type = ResolveType(dex_file, void_type_idx, java_lang_Object.Get());
687     CHECK_EQ(resolved_type, GetClassRoot(kPrimitiveVoid));
688     self->AssertNoPendingException();
689   }
690 
691   // Create conflict tables that depend on the class linker.
692   runtime->FixupConflictTables();
693 
694   FinishInit(self);
695 
696   VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
697 
698   return true;
699 }
700 
FinishInit(Thread * self)701 void ClassLinker::FinishInit(Thread* self) {
702   VLOG(startup) << "ClassLinker::FinishInit entering";
703 
704   // Let the heap know some key offsets into java.lang.ref instances
705   // Note: we hard code the field indexes here rather than using FindInstanceField
706   // as the types of the field can't be resolved prior to the runtime being
707   // fully initialized
708   mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
709   mirror::Class* java_lang_ref_FinalizerReference =
710       FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
711 
712   ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
713   CHECK_STREQ(pendingNext->GetName(), "pendingNext");
714   CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
715 
716   ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
717   CHECK_STREQ(queue->GetName(), "queue");
718   CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
719 
720   ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
721   CHECK_STREQ(queueNext->GetName(), "queueNext");
722   CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
723 
724   ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
725   CHECK_STREQ(referent->GetName(), "referent");
726   CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
727 
728   ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
729   CHECK_STREQ(zombie->GetName(), "zombie");
730   CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
731 
732   // ensure all class_roots_ are initialized
733   for (size_t i = 0; i < kClassRootsMax; i++) {
734     ClassRoot class_root = static_cast<ClassRoot>(i);
735     mirror::Class* klass = GetClassRoot(class_root);
736     CHECK(klass != nullptr);
737     DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
738     // note SetClassRoot does additional validation.
739     // if possible add new checks there to catch errors early
740   }
741 
742   CHECK(!array_iftable_.IsNull());
743 
744   // disable the slow paths in FindClass and CreatePrimitiveClass now
745   // that Object, Class, and Object[] are setup
746   init_done_ = true;
747 
748   VLOG(startup) << "ClassLinker::FinishInit exiting";
749 }
750 
RunRootClinits()751 void ClassLinker::RunRootClinits() {
752   Thread* self = Thread::Current();
753   for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
754     mirror::Class* c = GetClassRoot(ClassRoot(i));
755     if (!c->IsArrayClass() && !c->IsPrimitive()) {
756       StackHandleScope<1> hs(self);
757       Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
758       EnsureInitialized(self, h_class, true, true);
759       self->AssertNoPendingException();
760     }
761   }
762 }
763 
SanityCheckArtMethod(ArtMethod * m,mirror::Class * expected_class,const std::vector<gc::space::ImageSpace * > & spaces)764 static void SanityCheckArtMethod(ArtMethod* m,
765                                  mirror::Class* expected_class,
766                                  const std::vector<gc::space::ImageSpace*>& spaces)
767     SHARED_REQUIRES(Locks::mutator_lock_) {
768   if (m->IsRuntimeMethod()) {
769     mirror::Class* declaring_class = m->GetDeclaringClassUnchecked();
770     CHECK(declaring_class == nullptr) << declaring_class << " " << PrettyMethod(m);
771   } else if (m->IsCopied()) {
772     CHECK(m->GetDeclaringClass() != nullptr) << PrettyMethod(m);
773   } else if (expected_class != nullptr) {
774     CHECK_EQ(m->GetDeclaringClassUnchecked(), expected_class) << PrettyMethod(m);
775   }
776   if (!spaces.empty()) {
777     bool contains = false;
778     for (gc::space::ImageSpace* space : spaces) {
779       auto& header = space->GetImageHeader();
780       size_t offset = reinterpret_cast<uint8_t*>(m) - space->Begin();
781 
782       const ImageSection& methods = header.GetMethodsSection();
783       contains = contains || methods.Contains(offset);
784 
785       const ImageSection& runtime_methods = header.GetRuntimeMethodsSection();
786       contains = contains || runtime_methods.Contains(offset);
787     }
788     CHECK(contains) << m << " not found";
789   }
790 }
791 
SanityCheckArtMethodPointerArray(mirror::PointerArray * arr,mirror::Class * expected_class,size_t pointer_size,const std::vector<gc::space::ImageSpace * > & spaces)792 static void SanityCheckArtMethodPointerArray(mirror::PointerArray* arr,
793                                              mirror::Class* expected_class,
794                                              size_t pointer_size,
795                                              const std::vector<gc::space::ImageSpace*>& spaces)
796     SHARED_REQUIRES(Locks::mutator_lock_) {
797   CHECK(arr != nullptr);
798   for (int32_t j = 0; j < arr->GetLength(); ++j) {
799     auto* method = arr->GetElementPtrSize<ArtMethod*>(j, pointer_size);
800     // expected_class == null means we are a dex cache.
801     if (expected_class != nullptr) {
802       CHECK(method != nullptr);
803     }
804     if (method != nullptr) {
805       SanityCheckArtMethod(method, expected_class, spaces);
806     }
807   }
808 }
809 
SanityCheckArtMethodPointerArray(ArtMethod ** arr,size_t size,size_t pointer_size,const std::vector<gc::space::ImageSpace * > & spaces)810 static void SanityCheckArtMethodPointerArray(ArtMethod** arr,
811                                              size_t size,
812                                              size_t pointer_size,
813                                              const std::vector<gc::space::ImageSpace*>& spaces)
814     SHARED_REQUIRES(Locks::mutator_lock_) {
815   CHECK_EQ(arr != nullptr, size != 0u);
816   if (arr != nullptr) {
817     bool contains = false;
818     for (auto space : spaces) {
819       auto offset = reinterpret_cast<uint8_t*>(arr) - space->Begin();
820       if (space->GetImageHeader().GetImageSection(
821           ImageHeader::kSectionDexCacheArrays).Contains(offset)) {
822         contains = true;
823         break;
824       }
825     }
826     CHECK(contains);
827   }
828   for (size_t j = 0; j < size; ++j) {
829     ArtMethod* method = mirror::DexCache::GetElementPtrSize(arr, j, pointer_size);
830     // expected_class == null means we are a dex cache.
831     if (method != nullptr) {
832       SanityCheckArtMethod(method, nullptr, spaces);
833     }
834   }
835 }
836 
SanityCheckObjectsCallback(mirror::Object * obj,void * arg ATTRIBUTE_UNUSED)837 static void SanityCheckObjectsCallback(mirror::Object* obj, void* arg ATTRIBUTE_UNUSED)
838     SHARED_REQUIRES(Locks::mutator_lock_) {
839   DCHECK(obj != nullptr);
840   CHECK(obj->GetClass() != nullptr) << "Null class in object " << obj;
841   CHECK(obj->GetClass()->GetClass() != nullptr) << "Null class class " << obj;
842   if (obj->IsClass()) {
843     auto klass = obj->AsClass();
844     for (ArtField& field : klass->GetIFields()) {
845       CHECK_EQ(field.GetDeclaringClass(), klass);
846     }
847     for (ArtField& field : klass->GetSFields()) {
848       CHECK_EQ(field.GetDeclaringClass(), klass);
849     }
850     auto* runtime = Runtime::Current();
851     auto image_spaces = runtime->GetHeap()->GetBootImageSpaces();
852     auto pointer_size = runtime->GetClassLinker()->GetImagePointerSize();
853     for (auto& m : klass->GetMethods(pointer_size)) {
854       SanityCheckArtMethod(&m, klass, image_spaces);
855     }
856     auto* vtable = klass->GetVTable();
857     if (vtable != nullptr) {
858       SanityCheckArtMethodPointerArray(vtable, nullptr, pointer_size, image_spaces);
859     }
860     if (klass->ShouldHaveEmbeddedImtAndVTable()) {
861       for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
862         SanityCheckArtMethod(
863             klass->GetEmbeddedImTableEntry(i, pointer_size), nullptr, image_spaces);
864       }
865       for (int32_t i = 0; i < klass->GetEmbeddedVTableLength(); ++i) {
866         SanityCheckArtMethod(klass->GetEmbeddedVTableEntry(i, pointer_size), nullptr, image_spaces);
867       }
868     }
869     auto* iftable = klass->GetIfTable();
870     if (iftable != nullptr) {
871       for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
872         if (iftable->GetMethodArrayCount(i) > 0) {
873           SanityCheckArtMethodPointerArray(
874               iftable->GetMethodArray(i), nullptr, pointer_size, image_spaces);
875         }
876       }
877     }
878   }
879 }
880 
881 // Set image methods' entry point to interpreter.
882 class SetInterpreterEntrypointArtMethodVisitor : public ArtMethodVisitor {
883  public:
SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size)884   explicit SetInterpreterEntrypointArtMethodVisitor(size_t image_pointer_size)
885     : image_pointer_size_(image_pointer_size) {}
886 
Visit(ArtMethod * method)887   void Visit(ArtMethod* method) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
888     if (kIsDebugBuild && !method->IsRuntimeMethod()) {
889       CHECK(method->GetDeclaringClass() != nullptr);
890     }
891     if (!method->IsNative() && !method->IsRuntimeMethod() && !method->IsResolutionMethod()) {
892       method->SetEntryPointFromQuickCompiledCodePtrSize(GetQuickToInterpreterBridge(),
893                                                         image_pointer_size_);
894     }
895   }
896 
897  private:
898   const size_t image_pointer_size_;
899 
900   DISALLOW_COPY_AND_ASSIGN(SetInterpreterEntrypointArtMethodVisitor);
901 };
902 
903 struct TrampolineCheckData {
904   const void* quick_resolution_trampoline;
905   const void* quick_imt_conflict_trampoline;
906   const void* quick_generic_jni_trampoline;
907   const void* quick_to_interpreter_bridge_trampoline;
908   size_t pointer_size;
909   ArtMethod* m;
910   bool error;
911 };
912 
CheckTrampolines(mirror::Object * obj,void * arg)913 static void CheckTrampolines(mirror::Object* obj, void* arg) NO_THREAD_SAFETY_ANALYSIS {
914   if (obj->IsClass()) {
915     mirror::Class* klass = obj->AsClass();
916     TrampolineCheckData* d = reinterpret_cast<TrampolineCheckData*>(arg);
917     for (ArtMethod& m : klass->GetMethods(d->pointer_size)) {
918       const void* entrypoint = m.GetEntryPointFromQuickCompiledCodePtrSize(d->pointer_size);
919       if (entrypoint == d->quick_resolution_trampoline ||
920           entrypoint == d->quick_imt_conflict_trampoline ||
921           entrypoint == d->quick_generic_jni_trampoline ||
922           entrypoint == d->quick_to_interpreter_bridge_trampoline) {
923         d->m = &m;
924         d->error = true;
925         return;
926       }
927     }
928   }
929 }
930 
InitFromBootImage(std::string * error_msg)931 bool ClassLinker::InitFromBootImage(std::string* error_msg) {
932   VLOG(startup) << __FUNCTION__ << " entering";
933   CHECK(!init_done_);
934 
935   Runtime* const runtime = Runtime::Current();
936   Thread* const self = Thread::Current();
937   gc::Heap* const heap = runtime->GetHeap();
938   std::vector<gc::space::ImageSpace*> spaces = heap->GetBootImageSpaces();
939   CHECK(!spaces.empty());
940   image_pointer_size_ = spaces[0]->GetImageHeader().GetPointerSize();
941   if (!ValidPointerSize(image_pointer_size_)) {
942     *error_msg = StringPrintf("Invalid image pointer size: %zu", image_pointer_size_);
943     return false;
944   }
945   if (!runtime->IsAotCompiler()) {
946     // Only the Aot compiler supports having an image with a different pointer size than the
947     // runtime. This happens on the host for compiling 32 bit tests since we use a 64 bit libart
948     // compiler. We may also use 32 bit dex2oat on a system with 64 bit apps.
949     if (image_pointer_size_ != sizeof(void*)) {
950       *error_msg = StringPrintf("Runtime must use current image pointer size: %zu vs %zu",
951                                 image_pointer_size_,
952                                 sizeof(void*));
953       return false;
954     }
955   }
956   dex_cache_boot_image_class_lookup_required_ = true;
957   std::vector<const OatFile*> oat_files =
958       runtime->GetOatFileManager().RegisterImageOatFiles(spaces);
959   DCHECK(!oat_files.empty());
960   const OatHeader& default_oat_header = oat_files[0]->GetOatHeader();
961   CHECK_EQ(default_oat_header.GetImageFileLocationOatChecksum(), 0U);
962   CHECK_EQ(default_oat_header.GetImageFileLocationOatDataBegin(), 0U);
963   const char* image_file_location = oat_files[0]->GetOatHeader().
964       GetStoreValueByKey(OatHeader::kImageLocationKey);
965   CHECK(image_file_location == nullptr || *image_file_location == 0);
966   quick_resolution_trampoline_ = default_oat_header.GetQuickResolutionTrampoline();
967   quick_imt_conflict_trampoline_ = default_oat_header.GetQuickImtConflictTrampoline();
968   quick_generic_jni_trampoline_ = default_oat_header.GetQuickGenericJniTrampoline();
969   quick_to_interpreter_bridge_trampoline_ = default_oat_header.GetQuickToInterpreterBridge();
970   if (kIsDebugBuild) {
971     // Check that the other images use the same trampoline.
972     for (size_t i = 1; i < oat_files.size(); ++i) {
973       const OatHeader& ith_oat_header = oat_files[i]->GetOatHeader();
974       const void* ith_quick_resolution_trampoline =
975           ith_oat_header.GetQuickResolutionTrampoline();
976       const void* ith_quick_imt_conflict_trampoline =
977           ith_oat_header.GetQuickImtConflictTrampoline();
978       const void* ith_quick_generic_jni_trampoline =
979           ith_oat_header.GetQuickGenericJniTrampoline();
980       const void* ith_quick_to_interpreter_bridge_trampoline =
981           ith_oat_header.GetQuickToInterpreterBridge();
982       if (ith_quick_resolution_trampoline != quick_resolution_trampoline_ ||
983           ith_quick_imt_conflict_trampoline != quick_imt_conflict_trampoline_ ||
984           ith_quick_generic_jni_trampoline != quick_generic_jni_trampoline_ ||
985           ith_quick_to_interpreter_bridge_trampoline != quick_to_interpreter_bridge_trampoline_) {
986         // Make sure that all methods in this image do not contain those trampolines as
987         // entrypoints. Otherwise the class-linker won't be able to work with a single set.
988         TrampolineCheckData data;
989         data.error = false;
990         data.pointer_size = GetImagePointerSize();
991         data.quick_resolution_trampoline = ith_quick_resolution_trampoline;
992         data.quick_imt_conflict_trampoline = ith_quick_imt_conflict_trampoline;
993         data.quick_generic_jni_trampoline = ith_quick_generic_jni_trampoline;
994         data.quick_to_interpreter_bridge_trampoline = ith_quick_to_interpreter_bridge_trampoline;
995         ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
996         spaces[i]->GetLiveBitmap()->Walk(CheckTrampolines, &data);
997         if (data.error) {
998           ArtMethod* m = data.m;
999           LOG(ERROR) << "Found a broken ArtMethod: " << PrettyMethod(m);
1000           *error_msg = "Found an ArtMethod with a bad entrypoint";
1001           return false;
1002         }
1003       }
1004     }
1005   }
1006 
1007   class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(
1008       down_cast<mirror::ObjectArray<mirror::Class>*>(
1009           spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)));
1010   mirror::Class::SetClassClass(class_roots_.Read()->Get(kJavaLangClass));
1011 
1012   // Special case of setting up the String class early so that we can test arbitrary objects
1013   // as being Strings or not
1014   mirror::String::SetClass(GetClassRoot(kJavaLangString));
1015 
1016   mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
1017   java_lang_Object->SetObjectSize(sizeof(mirror::Object));
1018   // Allocate in non-movable so that it's possible to check if a JNI weak global ref has been
1019   // cleared without triggering the read barrier and unintentionally mark the sentinel alive.
1020   runtime->SetSentinel(heap->AllocNonMovableObject<true>(
1021       self, java_lang_Object, java_lang_Object->GetObjectSize(), VoidFunctor()));
1022 
1023   // reinit array_iftable_ from any array class instance, they should be ==
1024   array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1025   DCHECK_EQ(array_iftable_.Read(), GetClassRoot(kBooleanArrayClass)->GetIfTable());
1026   // String class root was set above
1027   mirror::Field::SetClass(GetClassRoot(kJavaLangReflectField));
1028   mirror::Field::SetArrayClass(GetClassRoot(kJavaLangReflectFieldArrayClass));
1029   mirror::Constructor::SetClass(GetClassRoot(kJavaLangReflectConstructor));
1030   mirror::Constructor::SetArrayClass(GetClassRoot(kJavaLangReflectConstructorArrayClass));
1031   mirror::Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
1032   mirror::Method::SetArrayClass(GetClassRoot(kJavaLangReflectMethodArrayClass));
1033   mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
1034   mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1035   mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1036   mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1037   mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1038   mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1039   mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1040   mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1041   mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1042   mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1043   mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
1044 
1045   for (gc::space::ImageSpace* image_space : spaces) {
1046     // Boot class loader, use a null handle.
1047     std::vector<std::unique_ptr<const DexFile>> dex_files;
1048     if (!AddImageSpace(image_space,
1049                        ScopedNullHandle<mirror::ClassLoader>(),
1050                        /*dex_elements*/nullptr,
1051                        /*dex_location*/nullptr,
1052                        /*out*/&dex_files,
1053                        error_msg)) {
1054       return false;
1055     }
1056     // Append opened dex files at the end.
1057     boot_dex_files_.insert(boot_dex_files_.end(),
1058                            std::make_move_iterator(dex_files.begin()),
1059                            std::make_move_iterator(dex_files.end()));
1060   }
1061   FinishInit(self);
1062 
1063   VLOG(startup) << __FUNCTION__ << " exiting";
1064   return true;
1065 }
1066 
IsBootClassLoader(ScopedObjectAccessAlreadyRunnable & soa,mirror::ClassLoader * class_loader)1067 bool ClassLinker::IsBootClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1068                                     mirror::ClassLoader* class_loader) {
1069   return class_loader == nullptr ||
1070       class_loader->GetClass() ==
1071           soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader);
1072 }
1073 
GetDexPathListElementName(ScopedObjectAccessUnchecked & soa,mirror::Object * element)1074 static mirror::String* GetDexPathListElementName(ScopedObjectAccessUnchecked& soa,
1075                                                  mirror::Object* element)
1076     SHARED_REQUIRES(Locks::mutator_lock_) {
1077   ArtField* const dex_file_field =
1078       soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1079   ArtField* const dex_file_name_field =
1080       soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_fileName);
1081   DCHECK(dex_file_field != nullptr);
1082   DCHECK(dex_file_name_field != nullptr);
1083   DCHECK(element != nullptr);
1084   CHECK_EQ(dex_file_field->GetDeclaringClass(), element->GetClass()) << PrettyTypeOf(element);
1085   mirror::Object* dex_file = dex_file_field->GetObject(element);
1086   if (dex_file == nullptr) {
1087     return nullptr;
1088   }
1089   mirror::Object* const name_object = dex_file_name_field->GetObject(dex_file);
1090   if (name_object != nullptr) {
1091     return name_object->AsString();
1092   }
1093   return nullptr;
1094 }
1095 
FlattenPathClassLoader(mirror::ClassLoader * class_loader,std::list<mirror::String * > * out_dex_file_names,std::string * error_msg)1096 static bool FlattenPathClassLoader(mirror::ClassLoader* class_loader,
1097                                    std::list<mirror::String*>* out_dex_file_names,
1098                                    std::string* error_msg)
1099     SHARED_REQUIRES(Locks::mutator_lock_) {
1100   DCHECK(out_dex_file_names != nullptr);
1101   DCHECK(error_msg != nullptr);
1102   ScopedObjectAccessUnchecked soa(Thread::Current());
1103   ArtField* const dex_path_list_field =
1104       soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
1105   ArtField* const dex_elements_field =
1106       soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
1107   CHECK(dex_path_list_field != nullptr);
1108   CHECK(dex_elements_field != nullptr);
1109   while (!ClassLinker::IsBootClassLoader(soa, class_loader)) {
1110     if (class_loader->GetClass() !=
1111         soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
1112       *error_msg = StringPrintf("Unknown class loader type %s", PrettyTypeOf(class_loader).c_str());
1113       // Unsupported class loader.
1114       return false;
1115     }
1116     mirror::Object* dex_path_list = dex_path_list_field->GetObject(class_loader);
1117     if (dex_path_list != nullptr) {
1118       // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1119       mirror::Object* dex_elements_obj = dex_elements_field->GetObject(dex_path_list);
1120       // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1121       // at the mCookie which is a DexFile vector.
1122       if (dex_elements_obj != nullptr) {
1123         mirror::ObjectArray<mirror::Object>* dex_elements =
1124             dex_elements_obj->AsObjectArray<mirror::Object>();
1125         // Reverse order since we insert the parent at the front.
1126         for (int32_t i = dex_elements->GetLength() - 1; i >= 0; --i) {
1127           mirror::Object* const element = dex_elements->GetWithoutChecks(i);
1128           if (element == nullptr) {
1129             *error_msg = StringPrintf("Null dex element at index %d", i);
1130             return false;
1131           }
1132           mirror::String* const name = GetDexPathListElementName(soa, element);
1133           if (name == nullptr) {
1134             *error_msg = StringPrintf("Null name for dex element at index %d", i);
1135             return false;
1136           }
1137           out_dex_file_names->push_front(name);
1138         }
1139       }
1140     }
1141     class_loader = class_loader->GetParent();
1142   }
1143   return true;
1144 }
1145 
1146 class FixupArtMethodArrayVisitor : public ArtMethodVisitor {
1147  public:
FixupArtMethodArrayVisitor(const ImageHeader & header)1148   explicit FixupArtMethodArrayVisitor(const ImageHeader& header) : header_(header) {}
1149 
Visit(ArtMethod * method)1150   virtual void Visit(ArtMethod* method) SHARED_REQUIRES(Locks::mutator_lock_) {
1151     GcRoot<mirror::Class>* resolved_types = method->GetDexCacheResolvedTypes(sizeof(void*));
1152     const bool is_copied = method->IsCopied();
1153     if (resolved_types != nullptr) {
1154       bool in_image_space = false;
1155       if (kIsDebugBuild || is_copied) {
1156         in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1157             reinterpret_cast<const uint8_t*>(resolved_types) - header_.GetImageBegin());
1158       }
1159       // Must be in image space for non-miranda method.
1160       DCHECK(is_copied || in_image_space)
1161           << resolved_types << " is not in image starting at "
1162           << reinterpret_cast<void*>(header_.GetImageBegin());
1163       if (!is_copied || in_image_space) {
1164         // Go through the array so that we don't need to do a slow map lookup.
1165         method->SetDexCacheResolvedTypes(*reinterpret_cast<GcRoot<mirror::Class>**>(resolved_types),
1166                                          sizeof(void*));
1167       }
1168     }
1169     ArtMethod** resolved_methods = method->GetDexCacheResolvedMethods(sizeof(void*));
1170     if (resolved_methods != nullptr) {
1171       bool in_image_space = false;
1172       if (kIsDebugBuild || is_copied) {
1173         in_image_space = header_.GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1174               reinterpret_cast<const uint8_t*>(resolved_methods) - header_.GetImageBegin());
1175       }
1176       // Must be in image space for non-miranda method.
1177       DCHECK(is_copied || in_image_space)
1178           << resolved_methods << " is not in image starting at "
1179           << reinterpret_cast<void*>(header_.GetImageBegin());
1180       if (!is_copied || in_image_space) {
1181         // Go through the array so that we don't need to do a slow map lookup.
1182         method->SetDexCacheResolvedMethods(*reinterpret_cast<ArtMethod***>(resolved_methods),
1183                                            sizeof(void*));
1184       }
1185     }
1186   }
1187 
1188  private:
1189   const ImageHeader& header_;
1190 };
1191 
1192 class VerifyClassInTableArtMethodVisitor : public ArtMethodVisitor {
1193  public:
VerifyClassInTableArtMethodVisitor(ClassTable * table)1194   explicit VerifyClassInTableArtMethodVisitor(ClassTable* table) : table_(table) {}
1195 
Visit(ArtMethod * method)1196   virtual void Visit(ArtMethod* method)
1197       SHARED_REQUIRES(Locks::mutator_lock_, Locks::classlinker_classes_lock_) {
1198     mirror::Class* klass = method->GetDeclaringClass();
1199     if (klass != nullptr && !Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
1200       CHECK_EQ(table_->LookupByDescriptor(klass), klass) << PrettyClass(klass);
1201     }
1202   }
1203 
1204  private:
1205   ClassTable* const table_;
1206 };
1207 
1208 class VerifyDeclaringClassVisitor : public ArtMethodVisitor {
1209  public:
SHARED_REQUIRES(Locks::mutator_lock_,Locks::heap_bitmap_lock_)1210   VerifyDeclaringClassVisitor() SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_)
1211       : live_bitmap_(Runtime::Current()->GetHeap()->GetLiveBitmap()) {}
1212 
Visit(ArtMethod * method)1213   virtual void Visit(ArtMethod* method)
1214       SHARED_REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
1215     mirror::Class* klass = method->GetDeclaringClassUnchecked();
1216     if (klass != nullptr) {
1217       CHECK(live_bitmap_->Test(klass)) << "Image method has unmarked declaring class";
1218     }
1219   }
1220 
1221  private:
1222   gc::accounting::HeapBitmap* const live_bitmap_;
1223 };
1224 
UpdateAppImageClassLoadersAndDexCaches(gc::space::ImageSpace * space,Handle<mirror::ClassLoader> class_loader,Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,ClassTable::ClassSet * new_class_set,bool * out_forward_dex_cache_array,std::string * out_error_msg)1225 bool ClassLinker::UpdateAppImageClassLoadersAndDexCaches(
1226     gc::space::ImageSpace* space,
1227     Handle<mirror::ClassLoader> class_loader,
1228     Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches,
1229     ClassTable::ClassSet* new_class_set,
1230     bool* out_forward_dex_cache_array,
1231     std::string* out_error_msg) {
1232   DCHECK(out_forward_dex_cache_array != nullptr);
1233   DCHECK(out_error_msg != nullptr);
1234   Thread* const self = Thread::Current();
1235   gc::Heap* const heap = Runtime::Current()->GetHeap();
1236   const ImageHeader& header = space->GetImageHeader();
1237   {
1238     // Add image classes into the class table for the class loader, and fixup the dex caches and
1239     // class loader fields.
1240     WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1241     ClassTable* table = InsertClassTableForClassLoader(class_loader.Get());
1242     // Dex cache array fixup is all or nothing, we must reject app images that have mixed since we
1243     // rely on clobering the dex cache arrays in the image to forward to bss.
1244     size_t num_dex_caches_with_bss_arrays = 0;
1245     const size_t num_dex_caches = dex_caches->GetLength();
1246     for (size_t i = 0; i < num_dex_caches; i++) {
1247       mirror::DexCache* const dex_cache = dex_caches->Get(i);
1248       const DexFile* const dex_file = dex_cache->GetDexFile();
1249       const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1250       if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
1251         ++num_dex_caches_with_bss_arrays;
1252       }
1253     }
1254     *out_forward_dex_cache_array = num_dex_caches_with_bss_arrays != 0;
1255     if (*out_forward_dex_cache_array) {
1256       if (num_dex_caches_with_bss_arrays != num_dex_caches) {
1257         // Reject application image since we cannot forward only some of the dex cache arrays.
1258         // TODO: We could get around this by having a dedicated forwarding slot. It should be an
1259         // uncommon case.
1260         *out_error_msg = StringPrintf("Dex caches in bss does not match total: %zu vs %zu",
1261                                       num_dex_caches_with_bss_arrays,
1262                                       num_dex_caches);
1263         return false;
1264       }
1265     }
1266     // Only add the classes to the class loader after the points where we can return false.
1267     for (size_t i = 0; i < num_dex_caches; i++) {
1268       mirror::DexCache* const dex_cache = dex_caches->Get(i);
1269       const DexFile* const dex_file = dex_cache->GetDexFile();
1270       const OatFile::OatDexFile* oat_dex_file = dex_file->GetOatDexFile();
1271       if (oat_dex_file != nullptr && oat_dex_file->GetDexCacheArrays() != nullptr) {
1272       // If the oat file expects the dex cache arrays to be in the BSS, then allocate there and
1273         // copy over the arrays.
1274         DCHECK(dex_file != nullptr);
1275         const size_t num_strings = dex_file->NumStringIds();
1276         const size_t num_types = dex_file->NumTypeIds();
1277         const size_t num_methods = dex_file->NumMethodIds();
1278         const size_t num_fields = dex_file->NumFieldIds();
1279         CHECK_EQ(num_strings, dex_cache->NumStrings());
1280         CHECK_EQ(num_types, dex_cache->NumResolvedTypes());
1281         CHECK_EQ(num_methods, dex_cache->NumResolvedMethods());
1282         CHECK_EQ(num_fields, dex_cache->NumResolvedFields());
1283         DexCacheArraysLayout layout(image_pointer_size_, dex_file);
1284         uint8_t* const raw_arrays = oat_dex_file->GetDexCacheArrays();
1285         // The space is not yet visible to the GC, we can avoid the read barriers and use
1286         // std::copy_n.
1287         if (num_strings != 0u) {
1288           GcRoot<mirror::String>* const image_resolved_strings = dex_cache->GetStrings();
1289           GcRoot<mirror::String>* const strings =
1290               reinterpret_cast<GcRoot<mirror::String>*>(raw_arrays + layout.StringsOffset());
1291           for (size_t j = 0; kIsDebugBuild && j < num_strings; ++j) {
1292             DCHECK(strings[j].IsNull());
1293           }
1294           std::copy_n(image_resolved_strings, num_strings, strings);
1295           dex_cache->SetStrings(strings);
1296         }
1297         if (num_types != 0u) {
1298           GcRoot<mirror::Class>* const image_resolved_types = dex_cache->GetResolvedTypes();
1299           GcRoot<mirror::Class>* const types =
1300               reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
1301           for (size_t j = 0; kIsDebugBuild && j < num_types; ++j) {
1302             DCHECK(types[j].IsNull());
1303           }
1304           std::copy_n(image_resolved_types, num_types, types);
1305           // Store a pointer to the new location for fast ArtMethod patching without requiring map.
1306           // This leaves random garbage at the start of the dex cache array, but nobody should ever
1307           // read from it again.
1308           *reinterpret_cast<GcRoot<mirror::Class>**>(image_resolved_types) = types;
1309           dex_cache->SetResolvedTypes(types);
1310         }
1311         if (num_methods != 0u) {
1312           ArtMethod** const methods = reinterpret_cast<ArtMethod**>(
1313               raw_arrays + layout.MethodsOffset());
1314           ArtMethod** const image_resolved_methods = dex_cache->GetResolvedMethods();
1315           for (size_t j = 0; kIsDebugBuild && j < num_methods; ++j) {
1316             DCHECK(methods[j] == nullptr);
1317           }
1318           std::copy_n(image_resolved_methods, num_methods, methods);
1319           // Store a pointer to the new location for fast ArtMethod patching without requiring map.
1320           *reinterpret_cast<ArtMethod***>(image_resolved_methods) = methods;
1321           dex_cache->SetResolvedMethods(methods);
1322         }
1323         if (num_fields != 0u) {
1324           ArtField** const fields =
1325               reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
1326           for (size_t j = 0; kIsDebugBuild && j < num_fields; ++j) {
1327             DCHECK(fields[j] == nullptr);
1328           }
1329           std::copy_n(dex_cache->GetResolvedFields(), num_fields, fields);
1330           dex_cache->SetResolvedFields(fields);
1331         }
1332       }
1333       {
1334         WriterMutexLock mu2(self, dex_lock_);
1335         // Make sure to do this after we update the arrays since we store the resolved types array
1336         // in DexCacheData in RegisterDexFileLocked. We need the array pointer to be the one in the
1337         // BSS.
1338         mirror::DexCache* existing_dex_cache = FindDexCacheLocked(self,
1339                                                                   *dex_file,
1340                                                                   /*allow_failure*/true);
1341         CHECK(existing_dex_cache == nullptr);
1342         StackHandleScope<1> hs3(self);
1343         RegisterDexFileLocked(*dex_file, hs3.NewHandle(dex_cache));
1344       }
1345       GcRoot<mirror::Class>* const types = dex_cache->GetResolvedTypes();
1346       const size_t num_types = dex_cache->NumResolvedTypes();
1347       if (new_class_set == nullptr) {
1348         for (int32_t j = 0; j < static_cast<int32_t>(num_types); j++) {
1349           // The image space is not yet added to the heap, avoid read barriers.
1350           mirror::Class* klass = types[j].Read();
1351           // There may also be boot image classes,
1352           if (space->HasAddress(klass)) {
1353             DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1354             // Update the class loader from the one in the image class loader to the one that loaded
1355             // the app image.
1356             klass->SetClassLoader(class_loader.Get());
1357             // The resolved type could be from another dex cache, go through the dex cache just in
1358             // case. May be null for array classes.
1359             if (klass->GetDexCacheStrings() != nullptr) {
1360               DCHECK(!klass->IsArrayClass());
1361               klass->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1362             }
1363             // If there are multiple dex caches, there may be the same class multiple times
1364             // in different dex caches. Check for this since inserting will add duplicates
1365             // otherwise.
1366             if (num_dex_caches > 1) {
1367               mirror::Class* existing = table->LookupByDescriptor(klass);
1368               if (existing != nullptr) {
1369                 DCHECK_EQ(existing, klass) << PrettyClass(klass);
1370               } else {
1371                 table->Insert(klass);
1372               }
1373             } else {
1374               table->Insert(klass);
1375             }
1376             // Double checked VLOG to avoid overhead.
1377             if (VLOG_IS_ON(image)) {
1378               VLOG(image) << PrettyClass(klass) << " " << klass->GetStatus();
1379               if (!klass->IsArrayClass()) {
1380                 VLOG(image) << "From " << klass->GetDexCache()->GetDexFile()->GetBaseLocation();
1381               }
1382               VLOG(image) << "Direct methods";
1383               for (ArtMethod& m : klass->GetDirectMethods(sizeof(void*))) {
1384                 VLOG(image) << PrettyMethod(&m);
1385               }
1386               VLOG(image) << "Virtual methods";
1387               for (ArtMethod& m : klass->GetVirtualMethods(sizeof(void*))) {
1388                 VLOG(image) << PrettyMethod(&m);
1389               }
1390             }
1391           } else {
1392             DCHECK(klass == nullptr || heap->ObjectIsInBootImageSpace(klass))
1393                 << klass << " " << PrettyClass(klass);
1394           }
1395         }
1396       }
1397       if (kIsDebugBuild) {
1398         for (int32_t j = 0; j < static_cast<int32_t>(num_types); j++) {
1399           // The image space is not yet added to the heap, avoid read barriers.
1400           mirror::Class* klass = types[j].Read();
1401           if (space->HasAddress(klass)) {
1402             DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1403             if (kIsDebugBuild) {
1404               if (new_class_set != nullptr) {
1405                 auto it = new_class_set->Find(GcRoot<mirror::Class>(klass));
1406                 DCHECK(it != new_class_set->end());
1407                 DCHECK_EQ(it->Read(), klass);
1408                 mirror::Class* super_class = klass->GetSuperClass();
1409                 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
1410                   auto it2 = new_class_set->Find(GcRoot<mirror::Class>(super_class));
1411                   DCHECK(it2 != new_class_set->end());
1412                   DCHECK_EQ(it2->Read(), super_class);
1413                 }
1414               } else {
1415                 DCHECK_EQ(table->LookupByDescriptor(klass), klass);
1416                 mirror::Class* super_class = klass->GetSuperClass();
1417                 if (super_class != nullptr && !heap->ObjectIsInBootImageSpace(super_class)) {
1418                   CHECK_EQ(table->LookupByDescriptor(super_class), super_class);
1419                 }
1420               }
1421             }
1422             if (kIsDebugBuild) {
1423               for (ArtMethod& m : klass->GetDirectMethods(sizeof(void*))) {
1424                 const void* code = m.GetEntryPointFromQuickCompiledCode();
1425                 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code;
1426                 if (!IsQuickResolutionStub(code) &&
1427                     !IsQuickGenericJniStub(code) &&
1428                     !IsQuickToInterpreterBridge(code) &&
1429                     !m.IsNative()) {
1430                   DCHECK_EQ(code, oat_code) << PrettyMethod(&m);
1431                 }
1432               }
1433               for (ArtMethod& m : klass->GetVirtualMethods(sizeof(void*))) {
1434                 const void* code = m.GetEntryPointFromQuickCompiledCode();
1435                 const void* oat_code = m.IsInvokable() ? GetQuickOatCodeFor(&m) : code;
1436                 if (!IsQuickResolutionStub(code) &&
1437                     !IsQuickGenericJniStub(code) &&
1438                     !IsQuickToInterpreterBridge(code) &&
1439                     !m.IsNative()) {
1440                   DCHECK_EQ(code, oat_code) << PrettyMethod(&m);
1441                 }
1442               }
1443             }
1444           }
1445         }
1446       }
1447     }
1448   }
1449   if (*out_forward_dex_cache_array) {
1450     ScopedTrace timing("Fixup ArtMethod dex cache arrays");
1451     FixupArtMethodArrayVisitor visitor(header);
1452     header.VisitPackedArtMethods(&visitor, space->Begin(), sizeof(void*));
1453     Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader.Get());
1454   }
1455   if (kVerifyArtMethodDeclaringClasses) {
1456     ScopedTrace timing("Verify declaring classes");
1457     ReaderMutexLock rmu(self, *Locks::heap_bitmap_lock_);
1458     VerifyDeclaringClassVisitor visitor;
1459     header.VisitPackedArtMethods(&visitor, space->Begin(), sizeof(void*));
1460   }
1461   return true;
1462 }
1463 
1464 // Update the class loader and resolved string dex cache array of classes. Should only be used on
1465 // classes in the image space.
1466 class UpdateClassLoaderAndResolvedStringsVisitor {
1467  public:
UpdateClassLoaderAndResolvedStringsVisitor(gc::space::ImageSpace * space,mirror::ClassLoader * class_loader,bool forward_strings)1468   UpdateClassLoaderAndResolvedStringsVisitor(gc::space::ImageSpace* space,
1469                                              mirror::ClassLoader* class_loader,
1470                                              bool forward_strings)
1471       : space_(space),
1472         class_loader_(class_loader),
1473         forward_strings_(forward_strings) {}
1474 
operator ()(mirror::Class * klass) const1475   bool operator()(mirror::Class* klass) const SHARED_REQUIRES(Locks::mutator_lock_) {
1476     if (forward_strings_) {
1477       GcRoot<mirror::String>* strings = klass->GetDexCacheStrings();
1478       if (strings != nullptr) {
1479         DCHECK(
1480             space_->GetImageHeader().GetImageSection(ImageHeader::kSectionDexCacheArrays).Contains(
1481                 reinterpret_cast<uint8_t*>(strings) - space_->Begin()))
1482             << "String dex cache array for " << PrettyClass(klass) << " is not in app image";
1483         // Dex caches have already been updated, so take the strings pointer from there.
1484         GcRoot<mirror::String>* new_strings = klass->GetDexCache()->GetStrings();
1485         DCHECK_NE(strings, new_strings);
1486         klass->SetDexCacheStrings(new_strings);
1487       }
1488     }
1489     // Finally, update class loader.
1490     klass->SetClassLoader(class_loader_);
1491     return true;
1492   }
1493 
1494   gc::space::ImageSpace* const space_;
1495   mirror::ClassLoader* const class_loader_;
1496   const bool forward_strings_;
1497 };
1498 
OpenOatDexFile(const OatFile * oat_file,const char * location,std::string * error_msg)1499 static std::unique_ptr<const DexFile> OpenOatDexFile(const OatFile* oat_file,
1500                                                      const char* location,
1501                                                      std::string* error_msg)
1502     SHARED_REQUIRES(Locks::mutator_lock_) {
1503   DCHECK(error_msg != nullptr);
1504   std::unique_ptr<const DexFile> dex_file;
1505   const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(location, nullptr);
1506   if (oat_dex_file == nullptr) {
1507     *error_msg = StringPrintf("Failed finding oat dex file for %s %s",
1508                               oat_file->GetLocation().c_str(),
1509                               location);
1510     return std::unique_ptr<const DexFile>();
1511   }
1512   std::string inner_error_msg;
1513   dex_file = oat_dex_file->OpenDexFile(&inner_error_msg);
1514   if (dex_file == nullptr) {
1515     *error_msg = StringPrintf("Failed to open dex file %s from within oat file %s error '%s'",
1516                               location,
1517                               oat_file->GetLocation().c_str(),
1518                               inner_error_msg.c_str());
1519     return std::unique_ptr<const DexFile>();
1520   }
1521 
1522   if (dex_file->GetLocationChecksum() != oat_dex_file->GetDexFileLocationChecksum()) {
1523     *error_msg = StringPrintf("Checksums do not match for %s: %x vs %x",
1524                               location,
1525                               dex_file->GetLocationChecksum(),
1526                               oat_dex_file->GetDexFileLocationChecksum());
1527     return std::unique_ptr<const DexFile>();
1528   }
1529   return dex_file;
1530 }
1531 
OpenImageDexFiles(gc::space::ImageSpace * space,std::vector<std::unique_ptr<const DexFile>> * out_dex_files,std::string * error_msg)1532 bool ClassLinker::OpenImageDexFiles(gc::space::ImageSpace* space,
1533                                     std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1534                                     std::string* error_msg) {
1535   ScopedAssertNoThreadSuspension nts(Thread::Current(), __FUNCTION__);
1536   const ImageHeader& header = space->GetImageHeader();
1537   mirror::Object* dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
1538   DCHECK(dex_caches_object != nullptr);
1539   mirror::ObjectArray<mirror::DexCache>* dex_caches =
1540       dex_caches_object->AsObjectArray<mirror::DexCache>();
1541   const OatFile* oat_file = space->GetOatFile();
1542   for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1543     mirror::DexCache* dex_cache = dex_caches->Get(i);
1544     std::string dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1545     std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1546                                                              dex_file_location.c_str(),
1547                                                              error_msg);
1548     if (dex_file == nullptr) {
1549       return false;
1550     }
1551     dex_cache->SetDexFile(dex_file.get());
1552     out_dex_files->push_back(std::move(dex_file));
1553   }
1554   return true;
1555 }
1556 
AddImageSpace(gc::space::ImageSpace * space,Handle<mirror::ClassLoader> class_loader,jobjectArray dex_elements,const char * dex_location,std::vector<std::unique_ptr<const DexFile>> * out_dex_files,std::string * error_msg)1557 bool ClassLinker::AddImageSpace(
1558     gc::space::ImageSpace* space,
1559     Handle<mirror::ClassLoader> class_loader,
1560     jobjectArray dex_elements,
1561     const char* dex_location,
1562     std::vector<std::unique_ptr<const DexFile>>* out_dex_files,
1563     std::string* error_msg) {
1564   DCHECK(out_dex_files != nullptr);
1565   DCHECK(error_msg != nullptr);
1566   const uint64_t start_time = NanoTime();
1567   const bool app_image = class_loader.Get() != nullptr;
1568   const ImageHeader& header = space->GetImageHeader();
1569   mirror::Object* dex_caches_object = header.GetImageRoot(ImageHeader::kDexCaches);
1570   DCHECK(dex_caches_object != nullptr);
1571   Runtime* const runtime = Runtime::Current();
1572   gc::Heap* const heap = runtime->GetHeap();
1573   Thread* const self = Thread::Current();
1574   StackHandleScope<2> hs(self);
1575   Handle<mirror::ObjectArray<mirror::DexCache>> dex_caches(
1576       hs.NewHandle(dex_caches_object->AsObjectArray<mirror::DexCache>()));
1577   Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1578       header.GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>()));
1579   const OatFile* oat_file = space->GetOatFile();
1580   std::unordered_set<mirror::ClassLoader*> image_class_loaders;
1581   // Check that the image is what we are expecting.
1582   if (image_pointer_size_ != space->GetImageHeader().GetPointerSize()) {
1583     *error_msg = StringPrintf("Application image pointer size does not match runtime: %zu vs %zu",
1584                               static_cast<size_t>(space->GetImageHeader().GetPointerSize()),
1585                               image_pointer_size_);
1586     return false;
1587   }
1588   DCHECK(class_roots.Get() != nullptr);
1589   if (class_roots->GetLength() != static_cast<int32_t>(kClassRootsMax)) {
1590     *error_msg = StringPrintf("Expected %d class roots but got %d",
1591                               class_roots->GetLength(),
1592                               static_cast<int32_t>(kClassRootsMax));
1593     return false;
1594   }
1595   // Check against existing class roots to make sure they match the ones in the boot image.
1596   for (size_t i = 0; i < kClassRootsMax; i++) {
1597     if (class_roots->Get(i) != GetClassRoot(static_cast<ClassRoot>(i))) {
1598       *error_msg = "App image class roots must have pointer equality with runtime ones.";
1599       return false;
1600     }
1601   }
1602   if (oat_file->GetOatHeader().GetDexFileCount() !=
1603       static_cast<uint32_t>(dex_caches->GetLength())) {
1604     *error_msg = "Dex cache count and dex file count mismatch while trying to initialize from "
1605                  "image";
1606     return false;
1607   }
1608 
1609   StackHandleScope<1> hs2(self);
1610   MutableHandle<mirror::DexCache> h_dex_cache(hs2.NewHandle<mirror::DexCache>(nullptr));
1611   for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1612     h_dex_cache.Assign(dex_caches->Get(i));
1613     std::string dex_file_location(h_dex_cache->GetLocation()->ToModifiedUtf8());
1614     // TODO: Only store qualified paths.
1615     // If non qualified, qualify it.
1616     if (dex_file_location.find('/') == std::string::npos) {
1617       std::string dex_location_path = dex_location;
1618       const size_t pos = dex_location_path.find_last_of('/');
1619       CHECK_NE(pos, std::string::npos);
1620       dex_location_path = dex_location_path.substr(0, pos + 1);  // Keep trailing '/'
1621       dex_file_location = dex_location_path + dex_file_location;
1622     }
1623     std::unique_ptr<const DexFile> dex_file = OpenOatDexFile(oat_file,
1624                                                              dex_file_location.c_str(),
1625                                                              error_msg);
1626     if (dex_file == nullptr) {
1627       return false;
1628     }
1629 
1630     if (app_image) {
1631       // The current dex file field is bogus, overwrite it so that we can get the dex file in the
1632       // loop below.
1633       h_dex_cache->SetDexFile(dex_file.get());
1634       // Check that each class loader resolved the same way.
1635       // TODO: Store image class loaders as image roots.
1636       GcRoot<mirror::Class>* const types = h_dex_cache->GetResolvedTypes();
1637       for (int32_t j = 0, num_types = h_dex_cache->NumResolvedTypes(); j < num_types; j++) {
1638         mirror::Class* klass = types[j].Read();
1639         if (klass != nullptr) {
1640           DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1641           mirror::ClassLoader* image_class_loader = klass->GetClassLoader();
1642           image_class_loaders.insert(image_class_loader);
1643         }
1644       }
1645     } else {
1646       if (kSanityCheckObjects) {
1647         SanityCheckArtMethodPointerArray(h_dex_cache->GetResolvedMethods(),
1648                                          h_dex_cache->NumResolvedMethods(),
1649                                          image_pointer_size_,
1650                                          heap->GetBootImageSpaces());
1651       }
1652       // Register dex files, keep track of existing ones that are conflicts.
1653       AppendToBootClassPath(*dex_file.get(), h_dex_cache);
1654     }
1655     out_dex_files->push_back(std::move(dex_file));
1656   }
1657 
1658   if (app_image) {
1659     ScopedObjectAccessUnchecked soa(Thread::Current());
1660     // Check that the class loader resolves the same way as the ones in the image.
1661     // Image class loader [A][B][C][image dex files]
1662     // Class loader = [???][dex_elements][image dex files]
1663     // Need to ensure that [???][dex_elements] == [A][B][C].
1664     // For each class loader, PathClassLoader, the laoder checks the parent first. Also the logic
1665     // for PathClassLoader does this by looping through the array of dex files. To ensure they
1666     // resolve the same way, simply flatten the hierarchy in the way the resolution order would be,
1667     // and check that the dex file names are the same.
1668     for (mirror::ClassLoader* image_class_loader : image_class_loaders) {
1669       if (IsBootClassLoader(soa, image_class_loader)) {
1670         // The dex cache can reference types from the boot class loader.
1671         continue;
1672       }
1673       std::list<mirror::String*> image_dex_file_names;
1674       std::string temp_error_msg;
1675       if (!FlattenPathClassLoader(image_class_loader, &image_dex_file_names, &temp_error_msg)) {
1676         *error_msg = StringPrintf("Failed to flatten image class loader hierarchy '%s'",
1677                                   temp_error_msg.c_str());
1678         return false;
1679       }
1680       std::list<mirror::String*> loader_dex_file_names;
1681       if (!FlattenPathClassLoader(class_loader.Get(), &loader_dex_file_names, &temp_error_msg)) {
1682         *error_msg = StringPrintf("Failed to flatten class loader hierarchy '%s'",
1683                                   temp_error_msg.c_str());
1684         return false;
1685       }
1686       // Add the temporary dex path list elements at the end.
1687       auto* elements = soa.Decode<mirror::ObjectArray<mirror::Object>*>(dex_elements);
1688       for (size_t i = 0, num_elems = elements->GetLength(); i < num_elems; ++i) {
1689         mirror::Object* element = elements->GetWithoutChecks(i);
1690         if (element != nullptr) {
1691           // If we are somewhere in the middle of the array, there may be nulls at the end.
1692           loader_dex_file_names.push_back(GetDexPathListElementName(soa, element));
1693         }
1694       }
1695       // Ignore the number of image dex files since we are adding those to the class loader anyways.
1696       CHECK_GE(static_cast<size_t>(image_dex_file_names.size()),
1697                static_cast<size_t>(dex_caches->GetLength()));
1698       size_t image_count = image_dex_file_names.size() - dex_caches->GetLength();
1699       // Check that the dex file names match.
1700       bool equal = image_count == loader_dex_file_names.size();
1701       if (equal) {
1702         auto it1 = image_dex_file_names.begin();
1703         auto it2 = loader_dex_file_names.begin();
1704         for (size_t i = 0; equal && i < image_count; ++i, ++it1, ++it2) {
1705           equal = equal && (*it1)->Equals(*it2);
1706         }
1707       }
1708       if (!equal) {
1709         VLOG(image) << "Image dex files " << image_dex_file_names.size();
1710         for (mirror::String* name : image_dex_file_names) {
1711           VLOG(image) << name->ToModifiedUtf8();
1712         }
1713         VLOG(image) << "Loader dex files " << loader_dex_file_names.size();
1714         for (mirror::String* name : loader_dex_file_names) {
1715           VLOG(image) << name->ToModifiedUtf8();
1716         }
1717         *error_msg = "Rejecting application image due to class loader mismatch";
1718         // Ignore class loader mismatch for now since these would just use possibly incorrect
1719         // oat code anyways. The structural class check should be done in the parent.
1720       }
1721     }
1722   }
1723 
1724   if (kSanityCheckObjects) {
1725     for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1726       auto* dex_cache = dex_caches->Get(i);
1727       for (size_t j = 0; j < dex_cache->NumResolvedFields(); ++j) {
1728         auto* field = dex_cache->GetResolvedField(j, image_pointer_size_);
1729         if (field != nullptr) {
1730           CHECK(field->GetDeclaringClass()->GetClass() != nullptr);
1731         }
1732       }
1733     }
1734     if (!app_image) {
1735       heap->VisitObjects(SanityCheckObjectsCallback, nullptr);
1736     }
1737   }
1738 
1739   // Set entry point to interpreter if in InterpretOnly mode.
1740   if (!runtime->IsAotCompiler() && runtime->GetInstrumentation()->InterpretOnly()) {
1741     SetInterpreterEntrypointArtMethodVisitor visitor(image_pointer_size_);
1742     header.VisitPackedArtMethods(&visitor, space->Begin(), image_pointer_size_);
1743   }
1744 
1745   ClassTable* class_table = nullptr;
1746   {
1747     WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1748     class_table = InsertClassTableForClassLoader(class_loader.Get());
1749   }
1750   // If we have a class table section, read it and use it for verification in
1751   // UpdateAppImageClassLoadersAndDexCaches.
1752   ClassTable::ClassSet temp_set;
1753   const ImageSection& class_table_section = header.GetImageSection(ImageHeader::kSectionClassTable);
1754   const bool added_class_table = class_table_section.Size() > 0u;
1755   if (added_class_table) {
1756     const uint64_t start_time2 = NanoTime();
1757     size_t read_count = 0;
1758     temp_set = ClassTable::ClassSet(space->Begin() + class_table_section.Offset(),
1759                                     /*make copy*/false,
1760                                     &read_count);
1761     if (!app_image) {
1762       dex_cache_boot_image_class_lookup_required_ = false;
1763     }
1764     VLOG(image) << "Adding class table classes took " << PrettyDuration(NanoTime() - start_time2);
1765   }
1766   if (app_image) {
1767     bool forward_dex_cache_arrays = false;
1768     if (!UpdateAppImageClassLoadersAndDexCaches(space,
1769                                                 class_loader,
1770                                                 dex_caches,
1771                                                 added_class_table ? &temp_set : nullptr,
1772                                                 /*out*/&forward_dex_cache_arrays,
1773                                                 /*out*/error_msg)) {
1774       return false;
1775     }
1776     // Update class loader and resolved strings. If added_class_table is false, the resolved
1777     // strings were forwarded UpdateAppImageClassLoadersAndDexCaches.
1778     UpdateClassLoaderAndResolvedStringsVisitor visitor(space,
1779                                                        class_loader.Get(),
1780                                                        forward_dex_cache_arrays);
1781     if (added_class_table) {
1782       for (GcRoot<mirror::Class>& root : temp_set) {
1783         visitor(root.Read());
1784       }
1785     }
1786     // forward_dex_cache_arrays is true iff we copied all of the dex cache arrays into the .bss.
1787     // In this case, madvise away the dex cache arrays section of the image to reduce RAM usage and
1788     // mark as PROT_NONE to catch any invalid accesses.
1789     if (forward_dex_cache_arrays) {
1790       const ImageSection& dex_cache_section = header.GetImageSection(
1791           ImageHeader::kSectionDexCacheArrays);
1792       uint8_t* section_begin = AlignUp(space->Begin() + dex_cache_section.Offset(), kPageSize);
1793       uint8_t* section_end = AlignDown(space->Begin() + dex_cache_section.End(), kPageSize);
1794       if (section_begin < section_end) {
1795         madvise(section_begin, section_end - section_begin, MADV_DONTNEED);
1796         mprotect(section_begin, section_end - section_begin, PROT_NONE);
1797         VLOG(image) << "Released and protected dex cache array image section from "
1798                     << reinterpret_cast<const void*>(section_begin) << "-"
1799                     << reinterpret_cast<const void*>(section_end);
1800       }
1801     }
1802   }
1803   if (added_class_table) {
1804     WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1805     class_table->AddClassSet(std::move(temp_set));
1806   }
1807   if (kIsDebugBuild && app_image) {
1808     // This verification needs to happen after the classes have been added to the class loader.
1809     // Since it ensures classes are in the class table.
1810     VerifyClassInTableArtMethodVisitor visitor2(class_table);
1811     header.VisitPackedArtMethods(&visitor2, space->Begin(), sizeof(void*));
1812   }
1813   VLOG(class_linker) << "Adding image space took " << PrettyDuration(NanoTime() - start_time);
1814   return true;
1815 }
1816 
ClassInClassTable(mirror::Class * klass)1817 bool ClassLinker::ClassInClassTable(mirror::Class* klass) {
1818   ClassTable* const class_table = ClassTableForClassLoader(klass->GetClassLoader());
1819   return class_table != nullptr && class_table->Contains(klass);
1820 }
1821 
VisitClassRoots(RootVisitor * visitor,VisitRootFlags flags)1822 void ClassLinker::VisitClassRoots(RootVisitor* visitor, VisitRootFlags flags) {
1823   // Acquire tracing_enabled before locking class linker lock to prevent lock order violation. Since
1824   // enabling tracing requires the mutator lock, there are no race conditions here.
1825   const bool tracing_enabled = Trace::IsTracingEnabled();
1826   Thread* const self = Thread::Current();
1827   WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1828   BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(
1829       visitor, RootInfo(kRootStickyClass));
1830   if ((flags & kVisitRootFlagAllRoots) != 0) {
1831     // Argument for how root visiting deals with ArtField and ArtMethod roots.
1832     // There is 3 GC cases to handle:
1833     // Non moving concurrent:
1834     // This case is easy to handle since the reference members of ArtMethod and ArtFields are held
1835     // live by the class and class roots.
1836     //
1837     // Moving non-concurrent:
1838     // This case needs to call visit VisitNativeRoots in case the classes or dex cache arrays move.
1839     // To prevent missing roots, this case needs to ensure that there is no
1840     // suspend points between the point which we allocate ArtMethod arrays and place them in a
1841     // class which is in the class table.
1842     //
1843     // Moving concurrent:
1844     // Need to make sure to not copy ArtMethods without doing read barriers since the roots are
1845     // marked concurrently and we don't hold the classlinker_classes_lock_ when we do the copy.
1846     boot_class_table_.VisitRoots(buffered_visitor);
1847 
1848     // If tracing is enabled, then mark all the class loaders to prevent unloading.
1849     if (tracing_enabled) {
1850       for (const ClassLoaderData& data : class_loaders_) {
1851         GcRoot<mirror::Object> root(GcRoot<mirror::Object>(self->DecodeJObject(data.weak_root)));
1852         root.VisitRoot(visitor, RootInfo(kRootVMInternal));
1853       }
1854     }
1855   } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1856     for (auto& root : new_class_roots_) {
1857       mirror::Class* old_ref = root.Read<kWithoutReadBarrier>();
1858       root.VisitRoot(visitor, RootInfo(kRootStickyClass));
1859       mirror::Class* new_ref = root.Read<kWithoutReadBarrier>();
1860       // Concurrent moving GC marked new roots through the to-space invariant.
1861       CHECK_EQ(new_ref, old_ref);
1862     }
1863   }
1864   buffered_visitor.Flush();  // Flush before clearing new_class_roots_.
1865   if ((flags & kVisitRootFlagClearRootLog) != 0) {
1866     new_class_roots_.clear();
1867   }
1868   if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1869     log_new_class_table_roots_ = true;
1870   } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1871     log_new_class_table_roots_ = false;
1872   }
1873   // We deliberately ignore the class roots in the image since we
1874   // handle image roots by using the MS/CMS rescanning of dirty cards.
1875 }
1876 
1877 // Keep in sync with InitCallback. Anything we visit, we need to
1878 // reinit references to when reinitializing a ClassLinker from a
1879 // mapped image.
VisitRoots(RootVisitor * visitor,VisitRootFlags flags)1880 void ClassLinker::VisitRoots(RootVisitor* visitor, VisitRootFlags flags) {
1881   class_roots_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1882   VisitClassRoots(visitor, flags);
1883   array_iftable_.VisitRootIfNonNull(visitor, RootInfo(kRootVMInternal));
1884   // Instead of visiting the find_array_class_cache_ drop it so that it doesn't prevent class
1885   // unloading if we are marking roots.
1886   DropFindArrayClassCache();
1887 }
1888 
1889 class VisitClassLoaderClassesVisitor : public ClassLoaderVisitor {
1890  public:
VisitClassLoaderClassesVisitor(ClassVisitor * visitor)1891   explicit VisitClassLoaderClassesVisitor(ClassVisitor* visitor)
1892       : visitor_(visitor),
1893         done_(false) {}
1894 
Visit(mirror::ClassLoader * class_loader)1895   void Visit(mirror::ClassLoader* class_loader)
1896       SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
1897     ClassTable* const class_table = class_loader->GetClassTable();
1898     if (!done_ && class_table != nullptr && !class_table->Visit(*visitor_)) {
1899       // If the visitor ClassTable returns false it means that we don't need to continue.
1900       done_ = true;
1901     }
1902   }
1903 
1904  private:
1905   ClassVisitor* const visitor_;
1906   // If done is true then we don't need to do any more visiting.
1907   bool done_;
1908 };
1909 
VisitClassesInternal(ClassVisitor * visitor)1910 void ClassLinker::VisitClassesInternal(ClassVisitor* visitor) {
1911   if (boot_class_table_.Visit(*visitor)) {
1912     VisitClassLoaderClassesVisitor loader_visitor(visitor);
1913     VisitClassLoaders(&loader_visitor);
1914   }
1915 }
1916 
VisitClasses(ClassVisitor * visitor)1917 void ClassLinker::VisitClasses(ClassVisitor* visitor) {
1918   if (dex_cache_boot_image_class_lookup_required_) {
1919     AddBootImageClassesToClassTable();
1920   }
1921   Thread* const self = Thread::Current();
1922   ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1923   // Not safe to have thread suspension when we are holding a lock.
1924   if (self != nullptr) {
1925     ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
1926     VisitClassesInternal(visitor);
1927   } else {
1928     VisitClassesInternal(visitor);
1929   }
1930 }
1931 
1932 class GetClassesInToVector : public ClassVisitor {
1933  public:
operator ()(mirror::Class * klass)1934   bool operator()(mirror::Class* klass) OVERRIDE {
1935     classes_.push_back(klass);
1936     return true;
1937   }
1938   std::vector<mirror::Class*> classes_;
1939 };
1940 
1941 class GetClassInToObjectArray : public ClassVisitor {
1942  public:
GetClassInToObjectArray(mirror::ObjectArray<mirror::Class> * arr)1943   explicit GetClassInToObjectArray(mirror::ObjectArray<mirror::Class>* arr)
1944       : arr_(arr), index_(0) {}
1945 
operator ()(mirror::Class * klass)1946   bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
1947     ++index_;
1948     if (index_ <= arr_->GetLength()) {
1949       arr_->Set(index_ - 1, klass);
1950       return true;
1951     }
1952     return false;
1953   }
1954 
Succeeded() const1955   bool Succeeded() const SHARED_REQUIRES(Locks::mutator_lock_) {
1956     return index_ <= arr_->GetLength();
1957   }
1958 
1959  private:
1960   mirror::ObjectArray<mirror::Class>* const arr_;
1961   int32_t index_;
1962 };
1963 
VisitClassesWithoutClassesLock(ClassVisitor * visitor)1964 void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor) {
1965   // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1966   // is avoiding duplicates.
1967   Thread* const self = Thread::Current();
1968   if (!kMovingClasses) {
1969     ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
1970     GetClassesInToVector accumulator;
1971     VisitClasses(&accumulator);
1972     for (mirror::Class* klass : accumulator.classes_) {
1973       if (!visitor->operator()(klass)) {
1974         return;
1975       }
1976     }
1977   } else {
1978     StackHandleScope<1> hs(self);
1979     auto classes = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1980     // We size the array assuming classes won't be added to the class table during the visit.
1981     // If this assumption fails we iterate again.
1982     while (true) {
1983       size_t class_table_size;
1984       {
1985         ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1986         // Add 100 in case new classes get loaded when we are filling in the object array.
1987         class_table_size = NumZygoteClasses() + NumNonZygoteClasses() + 100;
1988       }
1989       mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1990       mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1991       classes.Assign(
1992           mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1993       CHECK(classes.Get() != nullptr);  // OOME.
1994       GetClassInToObjectArray accumulator(classes.Get());
1995       VisitClasses(&accumulator);
1996       if (accumulator.Succeeded()) {
1997         break;
1998       }
1999     }
2000     for (int32_t i = 0; i < classes->GetLength(); ++i) {
2001       // If the class table shrank during creation of the clases array we expect null elements. If
2002       // the class table grew then the loop repeats. If classes are created after the loop has
2003       // finished then we don't visit.
2004       mirror::Class* klass = classes->Get(i);
2005       if (klass != nullptr && !visitor->operator()(klass)) {
2006         return;
2007       }
2008     }
2009   }
2010 }
2011 
~ClassLinker()2012 ClassLinker::~ClassLinker() {
2013   mirror::Class::ResetClass();
2014   mirror::Constructor::ResetClass();
2015   mirror::Field::ResetClass();
2016   mirror::Method::ResetClass();
2017   mirror::Reference::ResetClass();
2018   mirror::StackTraceElement::ResetClass();
2019   mirror::String::ResetClass();
2020   mirror::Throwable::ResetClass();
2021   mirror::BooleanArray::ResetArrayClass();
2022   mirror::ByteArray::ResetArrayClass();
2023   mirror::CharArray::ResetArrayClass();
2024   mirror::Constructor::ResetArrayClass();
2025   mirror::DoubleArray::ResetArrayClass();
2026   mirror::Field::ResetArrayClass();
2027   mirror::FloatArray::ResetArrayClass();
2028   mirror::Method::ResetArrayClass();
2029   mirror::IntArray::ResetArrayClass();
2030   mirror::LongArray::ResetArrayClass();
2031   mirror::ShortArray::ResetArrayClass();
2032   Thread* const self = Thread::Current();
2033   for (const ClassLoaderData& data : class_loaders_) {
2034     DeleteClassLoader(self, data);
2035   }
2036   class_loaders_.clear();
2037 }
2038 
DeleteClassLoader(Thread * self,const ClassLoaderData & data)2039 void ClassLinker::DeleteClassLoader(Thread* self, const ClassLoaderData& data) {
2040   Runtime* const runtime = Runtime::Current();
2041   JavaVMExt* const vm = runtime->GetJavaVM();
2042   vm->DeleteWeakGlobalRef(self, data.weak_root);
2043   // Notify the JIT that we need to remove the methods and/or profiling info.
2044   if (runtime->GetJit() != nullptr) {
2045     jit::JitCodeCache* code_cache = runtime->GetJit()->GetCodeCache();
2046     if (code_cache != nullptr) {
2047       code_cache->RemoveMethodsIn(self, *data.allocator);
2048     }
2049   }
2050   delete data.allocator;
2051   delete data.class_table;
2052 }
2053 
AllocPointerArray(Thread * self,size_t length)2054 mirror::PointerArray* ClassLinker::AllocPointerArray(Thread* self, size_t length) {
2055   return down_cast<mirror::PointerArray*>(image_pointer_size_ == 8u ?
2056       static_cast<mirror::Array*>(mirror::LongArray::Alloc(self, length)) :
2057       static_cast<mirror::Array*>(mirror::IntArray::Alloc(self, length)));
2058 }
2059 
AllocDexCache(Thread * self,const DexFile & dex_file,LinearAlloc * linear_alloc)2060 mirror::DexCache* ClassLinker::AllocDexCache(Thread* self,
2061                                              const DexFile& dex_file,
2062                                              LinearAlloc* linear_alloc) {
2063   StackHandleScope<6> hs(self);
2064   auto dex_cache(hs.NewHandle(down_cast<mirror::DexCache*>(
2065       GetClassRoot(kJavaLangDexCache)->AllocObject(self))));
2066   if (dex_cache.Get() == nullptr) {
2067     self->AssertPendingOOMException();
2068     return nullptr;
2069   }
2070   auto location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
2071   if (location.Get() == nullptr) {
2072     self->AssertPendingOOMException();
2073     return nullptr;
2074   }
2075   DexCacheArraysLayout layout(image_pointer_size_, &dex_file);
2076   uint8_t* raw_arrays = nullptr;
2077   if (dex_file.GetOatDexFile() != nullptr &&
2078       dex_file.GetOatDexFile()->GetDexCacheArrays() != nullptr) {
2079     raw_arrays = dex_file.GetOatDexFile()->GetDexCacheArrays();
2080   } else if (dex_file.NumStringIds() != 0u || dex_file.NumTypeIds() != 0u ||
2081       dex_file.NumMethodIds() != 0u || dex_file.NumFieldIds() != 0u) {
2082     // NOTE: We "leak" the raw_arrays because we never destroy the dex cache.
2083     DCHECK(image_pointer_size_ == 4u || image_pointer_size_ == 8u);
2084     // Zero-initialized.
2085     raw_arrays = reinterpret_cast<uint8_t*>(linear_alloc->Alloc(self, layout.Size()));
2086   }
2087   GcRoot<mirror::String>* strings = (dex_file.NumStringIds() == 0u) ? nullptr :
2088       reinterpret_cast<GcRoot<mirror::String>*>(raw_arrays + layout.StringsOffset());
2089   GcRoot<mirror::Class>* types = (dex_file.NumTypeIds() == 0u) ? nullptr :
2090       reinterpret_cast<GcRoot<mirror::Class>*>(raw_arrays + layout.TypesOffset());
2091   ArtMethod** methods = (dex_file.NumMethodIds() == 0u) ? nullptr :
2092       reinterpret_cast<ArtMethod**>(raw_arrays + layout.MethodsOffset());
2093   ArtField** fields = (dex_file.NumFieldIds() == 0u) ? nullptr :
2094       reinterpret_cast<ArtField**>(raw_arrays + layout.FieldsOffset());
2095   if (kIsDebugBuild) {
2096     // Sanity check to make sure all the dex cache arrays are empty. b/28992179
2097     for (size_t i = 0; i < dex_file.NumStringIds(); ++i) {
2098       CHECK(strings[i].Read<kWithoutReadBarrier>() == nullptr);
2099     }
2100     for (size_t i = 0; i < dex_file.NumTypeIds(); ++i) {
2101       CHECK(types[i].Read<kWithoutReadBarrier>() == nullptr);
2102     }
2103     for (size_t i = 0; i < dex_file.NumMethodIds(); ++i) {
2104       CHECK(mirror::DexCache::GetElementPtrSize(methods, i, image_pointer_size_) == nullptr);
2105     }
2106     for (size_t i = 0; i < dex_file.NumFieldIds(); ++i) {
2107       CHECK(mirror::DexCache::GetElementPtrSize(fields, i, image_pointer_size_) == nullptr);
2108     }
2109   }
2110   dex_cache->Init(&dex_file,
2111                   location.Get(),
2112                   strings,
2113                   dex_file.NumStringIds(),
2114                   types,
2115                   dex_file.NumTypeIds(),
2116                   methods,
2117                   dex_file.NumMethodIds(),
2118                   fields,
2119                   dex_file.NumFieldIds(),
2120                   image_pointer_size_);
2121   return dex_cache.Get();
2122 }
2123 
AllocClass(Thread * self,mirror::Class * java_lang_Class,uint32_t class_size)2124 mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
2125                                        uint32_t class_size) {
2126   DCHECK_GE(class_size, sizeof(mirror::Class));
2127   gc::Heap* heap = Runtime::Current()->GetHeap();
2128   mirror::Class::InitializeClassVisitor visitor(class_size);
2129   mirror::Object* k = kMovingClasses ?
2130       heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
2131       heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
2132   if (UNLIKELY(k == nullptr)) {
2133     self->AssertPendingOOMException();
2134     return nullptr;
2135   }
2136   return k->AsClass();
2137 }
2138 
AllocClass(Thread * self,uint32_t class_size)2139 mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
2140   return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
2141 }
2142 
AllocStackTraceElementArray(Thread * self,size_t length)2143 mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
2144     Thread* self,
2145     size_t length) {
2146   return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
2147       self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
2148 }
2149 
EnsureResolved(Thread * self,const char * descriptor,mirror::Class * klass)2150 mirror::Class* ClassLinker::EnsureResolved(Thread* self,
2151                                            const char* descriptor,
2152                                            mirror::Class* klass) {
2153   DCHECK(klass != nullptr);
2154 
2155   // For temporary classes we must wait for them to be retired.
2156   if (init_done_ && klass->IsTemp()) {
2157     CHECK(!klass->IsResolved());
2158     if (klass->IsErroneous()) {
2159       ThrowEarlierClassFailure(klass);
2160       return nullptr;
2161     }
2162     StackHandleScope<1> hs(self);
2163     Handle<mirror::Class> h_class(hs.NewHandle(klass));
2164     ObjectLock<mirror::Class> lock(self, h_class);
2165     // Loop and wait for the resolving thread to retire this class.
2166     while (!h_class->IsRetired() && !h_class->IsErroneous()) {
2167       lock.WaitIgnoringInterrupts();
2168     }
2169     if (h_class->IsErroneous()) {
2170       ThrowEarlierClassFailure(h_class.Get());
2171       return nullptr;
2172     }
2173     CHECK(h_class->IsRetired());
2174     // Get the updated class from class table.
2175     klass = LookupClass(self, descriptor, ComputeModifiedUtf8Hash(descriptor),
2176                         h_class.Get()->GetClassLoader());
2177   }
2178 
2179   // Wait for the class if it has not already been linked.
2180   if (!klass->IsResolved() && !klass->IsErroneous()) {
2181     StackHandleScope<1> hs(self);
2182     HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
2183     ObjectLock<mirror::Class> lock(self, h_class);
2184     // Check for circular dependencies between classes.
2185     if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
2186       ThrowClassCircularityError(h_class.Get());
2187       mirror::Class::SetStatus(h_class, mirror::Class::kStatusError, self);
2188       return nullptr;
2189     }
2190     // Wait for the pending initialization to complete.
2191     while (!h_class->IsResolved() && !h_class->IsErroneous()) {
2192       lock.WaitIgnoringInterrupts();
2193     }
2194   }
2195 
2196   if (klass->IsErroneous()) {
2197     ThrowEarlierClassFailure(klass);
2198     return nullptr;
2199   }
2200   // Return the loaded class.  No exceptions should be pending.
2201   CHECK(klass->IsResolved()) << PrettyClass(klass);
2202   self->AssertNoPendingException();
2203   return klass;
2204 }
2205 
2206 typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
2207 
2208 // Search a collection of DexFiles for a descriptor
FindInClassPath(const char * descriptor,size_t hash,const std::vector<const DexFile * > & class_path)2209 ClassPathEntry FindInClassPath(const char* descriptor,
2210                                size_t hash, const std::vector<const DexFile*>& class_path) {
2211   for (const DexFile* dex_file : class_path) {
2212     const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor, hash);
2213     if (dex_class_def != nullptr) {
2214       return ClassPathEntry(dex_file, dex_class_def);
2215     }
2216   }
2217   return ClassPathEntry(nullptr, nullptr);
2218 }
2219 
FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable & soa,Thread * self,const char * descriptor,size_t hash,Handle<mirror::ClassLoader> class_loader,mirror::Class ** result)2220 bool ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2221                                              Thread* self,
2222                                              const char* descriptor,
2223                                              size_t hash,
2224                                              Handle<mirror::ClassLoader> class_loader,
2225                                              mirror::Class** result) {
2226   // Termination case: boot class-loader.
2227   if (IsBootClassLoader(soa, class_loader.Get())) {
2228     // The boot class loader, search the boot class path.
2229     ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2230     if (pair.second != nullptr) {
2231       mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
2232       if (klass != nullptr) {
2233         *result = EnsureResolved(self, descriptor, klass);
2234       } else {
2235         *result = DefineClass(self,
2236                               descriptor,
2237                               hash,
2238                               ScopedNullHandle<mirror::ClassLoader>(),
2239                               *pair.first,
2240                               *pair.second);
2241       }
2242       if (*result == nullptr) {
2243         CHECK(self->IsExceptionPending()) << descriptor;
2244         self->ClearException();
2245       }
2246     } else {
2247       *result = nullptr;
2248     }
2249     return true;
2250   }
2251 
2252   // Unsupported class-loader?
2253   if (class_loader->GetClass() !=
2254       soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader)) {
2255     *result = nullptr;
2256     return false;
2257   }
2258 
2259   // Handles as RegisterDexFile may allocate dex caches (and cause thread suspension).
2260   StackHandleScope<4> hs(self);
2261   Handle<mirror::ClassLoader> h_parent(hs.NewHandle(class_loader->GetParent()));
2262   bool recursive_result = FindClassInPathClassLoader(soa, self, descriptor, hash, h_parent, result);
2263 
2264   if (!recursive_result) {
2265     // Something wrong up the chain.
2266     return false;
2267   }
2268 
2269   if (*result != nullptr) {
2270     // Found the class up the chain.
2271     return true;
2272   }
2273 
2274   // Handle this step.
2275   // Handle as if this is the child PathClassLoader.
2276   // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2277   // We need to get the DexPathList and loop through it.
2278   ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
2279   ArtField* const dex_file_field =
2280       soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
2281   mirror::Object* dex_path_list =
2282       soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2283       GetObject(class_loader.Get());
2284   if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
2285     // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2286     mirror::Object* dex_elements_obj =
2287         soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2288         GetObject(dex_path_list);
2289     // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2290     // at the mCookie which is a DexFile vector.
2291     if (dex_elements_obj != nullptr) {
2292       Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2293           hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2294       for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2295         mirror::Object* element = dex_elements->GetWithoutChecks(i);
2296         if (element == nullptr) {
2297           // Should never happen, fall back to java code to throw a NPE.
2298           break;
2299         }
2300         mirror::Object* dex_file = dex_file_field->GetObject(element);
2301         if (dex_file != nullptr) {
2302           mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
2303           if (long_array == nullptr) {
2304             // This should never happen so log a warning.
2305             LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2306             break;
2307           }
2308           int32_t long_array_size = long_array->GetLength();
2309           // First element is the oat file.
2310           for (int32_t j = kDexFileIndexStart; j < long_array_size; ++j) {
2311             const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
2312                 long_array->GetWithoutChecks(j)));
2313             const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
2314             if (dex_class_def != nullptr) {
2315               mirror::Class* klass = DefineClass(self,
2316                                                  descriptor,
2317                                                  hash,
2318                                                  class_loader,
2319                                                  *cp_dex_file,
2320                                                  *dex_class_def);
2321               if (klass == nullptr) {
2322                 CHECK(self->IsExceptionPending()) << descriptor;
2323                 self->ClearException();
2324                 // TODO: Is it really right to break here, and not check the other dex files?
2325                 return true;
2326               }
2327               *result = klass;
2328               return true;
2329             }
2330           }
2331         }
2332       }
2333     }
2334     self->AssertNoPendingException();
2335   }
2336 
2337   // Result is still null from the parent call, no need to set it again...
2338   return true;
2339 }
2340 
FindClass(Thread * self,const char * descriptor,Handle<mirror::ClassLoader> class_loader)2341 mirror::Class* ClassLinker::FindClass(Thread* self,
2342                                       const char* descriptor,
2343                                       Handle<mirror::ClassLoader> class_loader) {
2344   DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
2345   DCHECK(self != nullptr);
2346   self->AssertNoPendingException();
2347   if (descriptor[1] == '\0') {
2348     // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2349     // for primitive classes that aren't backed by dex files.
2350     return FindPrimitiveClass(descriptor[0]);
2351   }
2352   const size_t hash = ComputeModifiedUtf8Hash(descriptor);
2353   // Find the class in the loaded classes table.
2354   mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
2355   if (klass != nullptr) {
2356     return EnsureResolved(self, descriptor, klass);
2357   }
2358   // Class is not yet loaded.
2359   if (descriptor[0] == '[') {
2360     return CreateArrayClass(self, descriptor, hash, class_loader);
2361   } else if (class_loader.Get() == nullptr) {
2362     // The boot class loader, search the boot class path.
2363     ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2364     if (pair.second != nullptr) {
2365       return DefineClass(self,
2366                          descriptor,
2367                          hash,
2368                          ScopedNullHandle<mirror::ClassLoader>(),
2369                          *pair.first,
2370                          *pair.second);
2371     } else {
2372       // The boot class loader is searched ahead of the application class loader, failures are
2373       // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2374       // trigger the chaining with a proper stack trace.
2375       mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2376       self->SetException(pre_allocated);
2377       return nullptr;
2378     }
2379   } else {
2380     ScopedObjectAccessUnchecked soa(self);
2381     mirror::Class* cp_klass;
2382     if (FindClassInPathClassLoader(soa, self, descriptor, hash, class_loader, &cp_klass)) {
2383       // The chain was understood. So the value in cp_klass is either the class we were looking
2384       // for, or not found.
2385       if (cp_klass != nullptr) {
2386         return cp_klass;
2387       }
2388       // TODO: We handle the boot classpath loader in FindClassInPathClassLoader. Try to unify this
2389       //       and the branch above. TODO: throw the right exception here.
2390 
2391       // We'll let the Java-side rediscover all this and throw the exception with the right stack
2392       // trace.
2393     }
2394 
2395     if (Runtime::Current()->IsAotCompiler()) {
2396       // Oops, compile-time, can't run actual class-loader code.
2397       mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2398       self->SetException(pre_allocated);
2399       return nullptr;
2400     }
2401 
2402     ScopedLocalRef<jobject> class_loader_object(soa.Env(),
2403                                                 soa.AddLocalReference<jobject>(class_loader.Get()));
2404     std::string class_name_string(DescriptorToDot(descriptor));
2405     ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2406     {
2407       ScopedThreadStateChange tsc(self, kNative);
2408       ScopedLocalRef<jobject> class_name_object(soa.Env(),
2409                                                 soa.Env()->NewStringUTF(class_name_string.c_str()));
2410       if (class_name_object.get() == nullptr) {
2411         DCHECK(self->IsExceptionPending());  // OOME.
2412         return nullptr;
2413       }
2414       CHECK(class_loader_object.get() != nullptr);
2415       result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2416                                                WellKnownClasses::java_lang_ClassLoader_loadClass,
2417                                                class_name_object.get()));
2418     }
2419     if (self->IsExceptionPending()) {
2420       // If the ClassLoader threw, pass that exception up.
2421       return nullptr;
2422     } else if (result.get() == nullptr) {
2423       // broken loader - throw NPE to be compatible with Dalvik
2424       ThrowNullPointerException(StringPrintf("ClassLoader.loadClass returned null for %s",
2425                                              class_name_string.c_str()).c_str());
2426       return nullptr;
2427     } else {
2428       // success, return mirror::Class*
2429       return soa.Decode<mirror::Class*>(result.get());
2430     }
2431   }
2432   UNREACHABLE();
2433 }
2434 
DefineClass(Thread * self,const char * descriptor,size_t hash,Handle<mirror::ClassLoader> class_loader,const DexFile & dex_file,const DexFile::ClassDef & dex_class_def)2435 mirror::Class* ClassLinker::DefineClass(Thread* self,
2436                                         const char* descriptor,
2437                                         size_t hash,
2438                                         Handle<mirror::ClassLoader> class_loader,
2439                                         const DexFile& dex_file,
2440                                         const DexFile::ClassDef& dex_class_def) {
2441   StackHandleScope<3> hs(self);
2442   auto klass = hs.NewHandle<mirror::Class>(nullptr);
2443 
2444   // Load the class from the dex file.
2445   if (UNLIKELY(!init_done_)) {
2446     // finish up init of hand crafted class_roots_
2447     if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
2448       klass.Assign(GetClassRoot(kJavaLangObject));
2449     } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
2450       klass.Assign(GetClassRoot(kJavaLangClass));
2451     } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2452       klass.Assign(GetClassRoot(kJavaLangString));
2453     } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2454       klass.Assign(GetClassRoot(kJavaLangRefReference));
2455     } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
2456       klass.Assign(GetClassRoot(kJavaLangDexCache));
2457     }
2458   }
2459 
2460   if (klass.Get() == nullptr) {
2461     // Allocate a class with the status of not ready.
2462     // Interface object should get the right size here. Regular class will
2463     // figure out the right size later and be replaced with one of the right
2464     // size when the class becomes resolved.
2465     klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
2466   }
2467   if (UNLIKELY(klass.Get() == nullptr)) {
2468     self->AssertPendingOOMException();
2469     return nullptr;
2470   }
2471   mirror::DexCache* dex_cache = RegisterDexFile(dex_file, class_loader.Get());
2472   if (dex_cache == nullptr) {
2473     self->AssertPendingOOMException();
2474     return nullptr;
2475   }
2476   klass->SetDexCache(dex_cache);
2477   SetupClass(dex_file, dex_class_def, klass, class_loader.Get());
2478 
2479   // Mark the string class by setting its access flag.
2480   if (UNLIKELY(!init_done_)) {
2481     if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2482       klass->SetStringClass();
2483     }
2484   }
2485 
2486   ObjectLock<mirror::Class> lock(self, klass);
2487   klass->SetClinitThreadId(self->GetTid());
2488 
2489   // Add the newly loaded class to the loaded classes table.
2490   mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
2491   if (existing != nullptr) {
2492     // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2493     // this thread to block.
2494     return EnsureResolved(self, descriptor, existing);
2495   }
2496 
2497   // Load the fields and other things after we are inserted in the table. This is so that we don't
2498   // end up allocating unfree-able linear alloc resources and then lose the race condition. The
2499   // other reason is that the field roots are only visited from the class table. So we need to be
2500   // inserted before we allocate / fill in these fields.
2501   LoadClass(self, dex_file, dex_class_def, klass);
2502   if (self->IsExceptionPending()) {
2503     VLOG(class_linker) << self->GetException()->Dump();
2504     // An exception occured during load, set status to erroneous while holding klass' lock in case
2505     // notification is necessary.
2506     if (!klass->IsErroneous()) {
2507       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
2508     }
2509     return nullptr;
2510   }
2511 
2512   // Finish loading (if necessary) by finding parents
2513   CHECK(!klass->IsLoaded());
2514   if (!LoadSuperAndInterfaces(klass, dex_file)) {
2515     // Loading failed.
2516     if (!klass->IsErroneous()) {
2517       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
2518     }
2519     return nullptr;
2520   }
2521   CHECK(klass->IsLoaded());
2522   // Link the class (if necessary)
2523   CHECK(!klass->IsResolved());
2524   // TODO: Use fast jobjects?
2525   auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
2526 
2527   MutableHandle<mirror::Class> h_new_class = hs.NewHandle<mirror::Class>(nullptr);
2528   if (!LinkClass(self, descriptor, klass, interfaces, &h_new_class)) {
2529     // Linking failed.
2530     if (!klass->IsErroneous()) {
2531       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
2532     }
2533     return nullptr;
2534   }
2535   self->AssertNoPendingException();
2536   CHECK(h_new_class.Get() != nullptr) << descriptor;
2537   CHECK(h_new_class->IsResolved()) << descriptor;
2538 
2539   // Instrumentation may have updated entrypoints for all methods of all
2540   // classes. However it could not update methods of this class while we
2541   // were loading it. Now the class is resolved, we can update entrypoints
2542   // as required by instrumentation.
2543   if (Runtime::Current()->GetInstrumentation()->AreExitStubsInstalled()) {
2544     // We must be in the kRunnable state to prevent instrumentation from
2545     // suspending all threads to update entrypoints while we are doing it
2546     // for this class.
2547     DCHECK_EQ(self->GetState(), kRunnable);
2548     Runtime::Current()->GetInstrumentation()->InstallStubsForClass(h_new_class.Get());
2549   }
2550 
2551   /*
2552    * We send CLASS_PREPARE events to the debugger from here.  The
2553    * definition of "preparation" is creating the static fields for a
2554    * class and initializing them to the standard default values, but not
2555    * executing any code (that comes later, during "initialization").
2556    *
2557    * We did the static preparation in LinkClass.
2558    *
2559    * The class has been prepared and resolved but possibly not yet verified
2560    * at this point.
2561    */
2562   Dbg::PostClassPrepare(h_new_class.Get());
2563 
2564   // Notify native debugger of the new class and its layout.
2565   jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get());
2566 
2567   return h_new_class.Get();
2568 }
2569 
SizeOfClassWithoutEmbeddedTables(const DexFile & dex_file,const DexFile::ClassDef & dex_class_def)2570 uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2571                                                        const DexFile::ClassDef& dex_class_def) {
2572   const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
2573   size_t num_ref = 0;
2574   size_t num_8 = 0;
2575   size_t num_16 = 0;
2576   size_t num_32 = 0;
2577   size_t num_64 = 0;
2578   if (class_data != nullptr) {
2579     // We allow duplicate definitions of the same field in a class_data_item
2580     // but ignore the repeated indexes here, b/21868015.
2581     uint32_t last_field_idx = DexFile::kDexNoIndex;
2582     for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2583       uint32_t field_idx = it.GetMemberIndex();
2584       // Ordering enforced by DexFileVerifier.
2585       DCHECK(last_field_idx == DexFile::kDexNoIndex || last_field_idx <= field_idx);
2586       if (UNLIKELY(field_idx == last_field_idx)) {
2587         continue;
2588       }
2589       last_field_idx = field_idx;
2590       const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2591       const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
2592       char c = descriptor[0];
2593       switch (c) {
2594         case 'L':
2595         case '[':
2596           num_ref++;
2597           break;
2598         case 'J':
2599         case 'D':
2600           num_64++;
2601           break;
2602         case 'I':
2603         case 'F':
2604           num_32++;
2605           break;
2606         case 'S':
2607         case 'C':
2608           num_16++;
2609           break;
2610         case 'B':
2611         case 'Z':
2612           num_8++;
2613           break;
2614         default:
2615           LOG(FATAL) << "Unknown descriptor: " << c;
2616           UNREACHABLE();
2617       }
2618     }
2619   }
2620   return mirror::Class::ComputeClassSize(false,
2621                                          0,
2622                                          num_8,
2623                                          num_16,
2624                                          num_32,
2625                                          num_64,
2626                                          num_ref,
2627                                          image_pointer_size_);
2628 }
2629 
FindOatClass(const DexFile & dex_file,uint16_t class_def_idx,bool * found)2630 OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file,
2631                                             uint16_t class_def_idx,
2632                                             bool* found) {
2633   DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
2634   const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
2635   if (oat_dex_file == nullptr) {
2636     *found = false;
2637     return OatFile::OatClass::Invalid();
2638   }
2639   *found = true;
2640   return oat_dex_file->GetOatClass(class_def_idx);
2641 }
2642 
GetOatMethodIndexFromMethodIndex(const DexFile & dex_file,uint16_t class_def_idx,uint32_t method_idx)2643 static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file,
2644                                                  uint16_t class_def_idx,
2645                                                  uint32_t method_idx) {
2646   const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2647   const uint8_t* class_data = dex_file.GetClassData(class_def);
2648   CHECK(class_data != nullptr);
2649   ClassDataItemIterator it(dex_file, class_data);
2650   // Skip fields
2651   while (it.HasNextStaticField()) {
2652     it.Next();
2653   }
2654   while (it.HasNextInstanceField()) {
2655     it.Next();
2656   }
2657   // Process methods
2658   size_t class_def_method_index = 0;
2659   while (it.HasNextDirectMethod()) {
2660     if (it.GetMemberIndex() == method_idx) {
2661       return class_def_method_index;
2662     }
2663     class_def_method_index++;
2664     it.Next();
2665   }
2666   while (it.HasNextVirtualMethod()) {
2667     if (it.GetMemberIndex() == method_idx) {
2668       return class_def_method_index;
2669     }
2670     class_def_method_index++;
2671     it.Next();
2672   }
2673   DCHECK(!it.HasNext());
2674   LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2675   UNREACHABLE();
2676 }
2677 
FindOatMethodFor(ArtMethod * method,bool * found)2678 const OatFile::OatMethod ClassLinker::FindOatMethodFor(ArtMethod* method, bool* found) {
2679   // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
2680   // method for direct methods (or virtual methods made direct).
2681   mirror::Class* declaring_class = method->GetDeclaringClass();
2682   size_t oat_method_index;
2683   if (method->IsStatic() || method->IsDirect()) {
2684     // Simple case where the oat method index was stashed at load time.
2685     oat_method_index = method->GetMethodIndex();
2686   } else {
2687     // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2688     // by search for its position in the declared virtual methods.
2689     oat_method_index = declaring_class->NumDirectMethods();
2690     bool found_virtual = false;
2691     for (ArtMethod& art_method : declaring_class->GetVirtualMethods(image_pointer_size_)) {
2692       // Check method index instead of identity in case of duplicate method definitions.
2693       if (method->GetDexMethodIndex() == art_method.GetDexMethodIndex()) {
2694         found_virtual = true;
2695         break;
2696       }
2697       oat_method_index++;
2698     }
2699     CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2700                          << PrettyMethod(method);
2701   }
2702   DCHECK_EQ(oat_method_index,
2703             GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
2704                                              method->GetDeclaringClass()->GetDexClassDefIndex(),
2705                                              method->GetDexMethodIndex()));
2706   OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2707                                              declaring_class->GetDexClassDefIndex(),
2708                                              found);
2709   if (!(*found)) {
2710     return OatFile::OatMethod::Invalid();
2711   }
2712   return oat_class.GetOatMethod(oat_method_index);
2713 }
2714 
2715 // Special case to get oat code without overwriting a trampoline.
GetQuickOatCodeFor(ArtMethod * method)2716 const void* ClassLinker::GetQuickOatCodeFor(ArtMethod* method) {
2717   CHECK(method->IsInvokable()) << PrettyMethod(method);
2718   if (method->IsProxyMethod()) {
2719     return GetQuickProxyInvokeHandler();
2720   }
2721   bool found;
2722   OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2723   if (found) {
2724     auto* code = oat_method.GetQuickCode();
2725     if (code != nullptr) {
2726       return code;
2727     }
2728   }
2729   if (method->IsNative()) {
2730     // No code and native? Use generic trampoline.
2731     return GetQuickGenericJniStub();
2732   }
2733   return GetQuickToInterpreterBridge();
2734 }
2735 
GetOatMethodQuickCodeFor(ArtMethod * method)2736 const void* ClassLinker::GetOatMethodQuickCodeFor(ArtMethod* method) {
2737   if (method->IsNative() || !method->IsInvokable() || method->IsProxyMethod()) {
2738     return nullptr;
2739   }
2740   bool found;
2741   OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2742   if (found) {
2743     return oat_method.GetQuickCode();
2744   }
2745   return nullptr;
2746 }
2747 
ShouldUseInterpreterEntrypoint(ArtMethod * method,const void * quick_code)2748 bool ClassLinker::ShouldUseInterpreterEntrypoint(ArtMethod* method, const void* quick_code) {
2749   if (UNLIKELY(method->IsNative() || method->IsProxyMethod())) {
2750     return false;
2751   }
2752 
2753   if (quick_code == nullptr) {
2754     return true;
2755   }
2756 
2757   Runtime* runtime = Runtime::Current();
2758   instrumentation::Instrumentation* instr = runtime->GetInstrumentation();
2759   if (instr->InterpretOnly()) {
2760     return true;
2761   }
2762 
2763   if (runtime->GetClassLinker()->IsQuickToInterpreterBridge(quick_code)) {
2764     // Doing this check avoids doing compiled/interpreter transitions.
2765     return true;
2766   }
2767 
2768   if (Dbg::IsForcedInterpreterNeededForCalling(Thread::Current(), method)) {
2769     // Force the use of interpreter when it is required by the debugger.
2770     return true;
2771   }
2772 
2773   if (runtime->IsNativeDebuggable()) {
2774     DCHECK(runtime->UseJitCompilation() && runtime->GetJit()->JitAtFirstUse());
2775     // If we are doing native debugging, ignore application's AOT code,
2776     // since we want to JIT it with extra stackmaps for native debugging.
2777     // On the other hand, keep all AOT code from the boot image, since the
2778     // blocking JIT would results in non-negligible performance impact.
2779     return !runtime->GetHeap()->IsInBootImageOatFile(quick_code);
2780   }
2781 
2782   if (Dbg::IsDebuggerActive()) {
2783     // Boot image classes may be AOT-compiled as non-debuggable.
2784     // This is not suitable for the Java debugger, so ignore the AOT code.
2785     return runtime->GetHeap()->IsInBootImageOatFile(quick_code);
2786   }
2787 
2788   return false;
2789 }
2790 
FixupStaticTrampolines(mirror::Class * klass)2791 void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
2792   DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
2793   if (klass->NumDirectMethods() == 0) {
2794     return;  // No direct methods => no static methods.
2795   }
2796   Runtime* runtime = Runtime::Current();
2797   if (!runtime->IsStarted()) {
2798     if (runtime->IsAotCompiler() || runtime->GetHeap()->HasBootImageSpace()) {
2799       return;  // OAT file unavailable.
2800     }
2801   }
2802 
2803   const DexFile& dex_file = klass->GetDexFile();
2804   const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
2805   CHECK(dex_class_def != nullptr);
2806   const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
2807   // There should always be class data if there were direct methods.
2808   CHECK(class_data != nullptr) << PrettyDescriptor(klass);
2809   ClassDataItemIterator it(dex_file, class_data);
2810   // Skip fields
2811   while (it.HasNextStaticField()) {
2812     it.Next();
2813   }
2814   while (it.HasNextInstanceField()) {
2815     it.Next();
2816   }
2817   bool has_oat_class;
2818   OatFile::OatClass oat_class = FindOatClass(dex_file,
2819                                              klass->GetDexClassDefIndex(),
2820                                              &has_oat_class);
2821   // Link the code of methods skipped by LinkCode.
2822   for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
2823     ArtMethod* method = klass->GetDirectMethod(method_index, image_pointer_size_);
2824     if (!method->IsStatic()) {
2825       // Only update static methods.
2826       continue;
2827     }
2828     const void* quick_code = nullptr;
2829     if (has_oat_class) {
2830       OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2831       quick_code = oat_method.GetQuickCode();
2832     }
2833     // Check whether the method is native, in which case it's generic JNI.
2834     if (quick_code == nullptr && method->IsNative()) {
2835       quick_code = GetQuickGenericJniStub();
2836     } else if (ShouldUseInterpreterEntrypoint(method, quick_code)) {
2837       // Use interpreter entry point.
2838       quick_code = GetQuickToInterpreterBridge();
2839     }
2840     runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code);
2841   }
2842   // Ignore virtual methods on the iterator.
2843 }
2844 
EnsureThrowsInvocationError(ArtMethod * method)2845 void ClassLinker::EnsureThrowsInvocationError(ArtMethod* method) {
2846   DCHECK(method != nullptr);
2847   DCHECK(!method->IsInvokable());
2848   method->SetEntryPointFromQuickCompiledCodePtrSize(quick_to_interpreter_bridge_trampoline_,
2849                                                     image_pointer_size_);
2850 }
2851 
LinkCode(ArtMethod * method,const OatFile::OatClass * oat_class,uint32_t class_def_method_index)2852 void ClassLinker::LinkCode(ArtMethod* method, const OatFile::OatClass* oat_class,
2853                            uint32_t class_def_method_index) {
2854   Runtime* const runtime = Runtime::Current();
2855   if (runtime->IsAotCompiler()) {
2856     // The following code only applies to a non-compiler runtime.
2857     return;
2858   }
2859   // Method shouldn't have already been linked.
2860   DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2861   if (oat_class != nullptr) {
2862     // Every kind of method should at least get an invoke stub from the oat_method.
2863     // non-abstract methods also get their code pointers.
2864     const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
2865     oat_method.LinkMethod(method);
2866   }
2867 
2868   // Install entry point from interpreter.
2869   const void* quick_code = method->GetEntryPointFromQuickCompiledCode();
2870   bool enter_interpreter = ShouldUseInterpreterEntrypoint(method, quick_code);
2871 
2872   if (!method->IsInvokable()) {
2873     EnsureThrowsInvocationError(method);
2874     return;
2875   }
2876 
2877   if (method->IsStatic() && !method->IsConstructor()) {
2878     // For static methods excluding the class initializer, install the trampoline.
2879     // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2880     // after initializing class (see ClassLinker::InitializeClass method).
2881     method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2882   } else if (quick_code == nullptr && method->IsNative()) {
2883     method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
2884   } else if (enter_interpreter) {
2885     // Set entry point from compiled code if there's no code or in interpreter only mode.
2886     method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2887   }
2888 
2889   if (method->IsNative()) {
2890     // Unregistering restores the dlsym lookup stub.
2891     method->UnregisterNative();
2892 
2893     if (enter_interpreter || quick_code == nullptr) {
2894       // We have a native method here without code. Then it should have either the generic JNI
2895       // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2896       // TODO: this doesn't handle all the cases where trampolines may be installed.
2897       const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2898       DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
2899     }
2900   }
2901 }
2902 
SetupClass(const DexFile & dex_file,const DexFile::ClassDef & dex_class_def,Handle<mirror::Class> klass,mirror::ClassLoader * class_loader)2903 void ClassLinker::SetupClass(const DexFile& dex_file,
2904                              const DexFile::ClassDef& dex_class_def,
2905                              Handle<mirror::Class> klass,
2906                              mirror::ClassLoader* class_loader) {
2907   CHECK(klass.Get() != nullptr);
2908   CHECK(klass->GetDexCache() != nullptr);
2909   CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
2910   const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
2911   CHECK(descriptor != nullptr);
2912 
2913   klass->SetClass(GetClassRoot(kJavaLangClass));
2914   uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
2915   CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
2916   klass->SetAccessFlags(access_flags);
2917   klass->SetClassLoader(class_loader);
2918   DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
2919   mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, nullptr);
2920 
2921   klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
2922   klass->SetDexTypeIndex(dex_class_def.class_idx_);
2923   CHECK(klass->GetDexCacheStrings() != nullptr);
2924 }
2925 
LoadClass(Thread * self,const DexFile & dex_file,const DexFile::ClassDef & dex_class_def,Handle<mirror::Class> klass)2926 void ClassLinker::LoadClass(Thread* self,
2927                             const DexFile& dex_file,
2928                             const DexFile::ClassDef& dex_class_def,
2929                             Handle<mirror::Class> klass) {
2930   const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
2931   if (class_data == nullptr) {
2932     return;  // no fields or methods - for example a marker interface
2933   }
2934   bool has_oat_class = false;
2935   if (Runtime::Current()->IsStarted() && !Runtime::Current()->IsAotCompiler()) {
2936     OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2937                                                &has_oat_class);
2938     if (has_oat_class) {
2939       LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
2940     }
2941   }
2942   if (!has_oat_class) {
2943     LoadClassMembers(self, dex_file, class_data, klass, nullptr);
2944   }
2945 }
2946 
AllocArtFieldArray(Thread * self,LinearAlloc * allocator,size_t length)2947 LengthPrefixedArray<ArtField>* ClassLinker::AllocArtFieldArray(Thread* self,
2948                                                                LinearAlloc* allocator,
2949                                                                size_t length) {
2950   if (length == 0) {
2951     return nullptr;
2952   }
2953   // If the ArtField alignment changes, review all uses of LengthPrefixedArray<ArtField>.
2954   static_assert(alignof(ArtField) == 4, "ArtField alignment is expected to be 4.");
2955   size_t storage_size = LengthPrefixedArray<ArtField>::ComputeSize(length);
2956   void* array_storage = allocator->Alloc(self, storage_size);
2957   auto* ret = new(array_storage) LengthPrefixedArray<ArtField>(length);
2958   CHECK(ret != nullptr);
2959   std::uninitialized_fill_n(&ret->At(0), length, ArtField());
2960   return ret;
2961 }
2962 
AllocArtMethodArray(Thread * self,LinearAlloc * allocator,size_t length)2963 LengthPrefixedArray<ArtMethod>* ClassLinker::AllocArtMethodArray(Thread* self,
2964                                                                  LinearAlloc* allocator,
2965                                                                  size_t length) {
2966   if (length == 0) {
2967     return nullptr;
2968   }
2969   const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
2970   const size_t method_size = ArtMethod::Size(image_pointer_size_);
2971   const size_t storage_size =
2972       LengthPrefixedArray<ArtMethod>::ComputeSize(length, method_size, method_alignment);
2973   void* array_storage = allocator->Alloc(self, storage_size);
2974   auto* ret = new (array_storage) LengthPrefixedArray<ArtMethod>(length);
2975   CHECK(ret != nullptr);
2976   for (size_t i = 0; i < length; ++i) {
2977     new(reinterpret_cast<void*>(&ret->At(i, method_size, method_alignment))) ArtMethod;
2978   }
2979   return ret;
2980 }
2981 
GetAllocatorForClassLoader(mirror::ClassLoader * class_loader)2982 LinearAlloc* ClassLinker::GetAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2983   if (class_loader == nullptr) {
2984     return Runtime::Current()->GetLinearAlloc();
2985   }
2986   LinearAlloc* allocator = class_loader->GetAllocator();
2987   DCHECK(allocator != nullptr);
2988   return allocator;
2989 }
2990 
GetOrCreateAllocatorForClassLoader(mirror::ClassLoader * class_loader)2991 LinearAlloc* ClassLinker::GetOrCreateAllocatorForClassLoader(mirror::ClassLoader* class_loader) {
2992   if (class_loader == nullptr) {
2993     return Runtime::Current()->GetLinearAlloc();
2994   }
2995   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2996   LinearAlloc* allocator = class_loader->GetAllocator();
2997   if (allocator == nullptr) {
2998     RegisterClassLoader(class_loader);
2999     allocator = class_loader->GetAllocator();
3000     CHECK(allocator != nullptr);
3001   }
3002   return allocator;
3003 }
3004 
LoadClassMembers(Thread * self,const DexFile & dex_file,const uint8_t * class_data,Handle<mirror::Class> klass,const OatFile::OatClass * oat_class)3005 void ClassLinker::LoadClassMembers(Thread* self,
3006                                    const DexFile& dex_file,
3007                                    const uint8_t* class_data,
3008                                    Handle<mirror::Class> klass,
3009                                    const OatFile::OatClass* oat_class) {
3010   {
3011     // Note: We cannot have thread suspension until the field and method arrays are setup or else
3012     // Class::VisitFieldRoots may miss some fields or methods.
3013     ScopedAssertNoThreadSuspension nts(self, __FUNCTION__);
3014     // Load static fields.
3015     // We allow duplicate definitions of the same field in a class_data_item
3016     // but ignore the repeated indexes here, b/21868015.
3017     LinearAlloc* const allocator = GetAllocatorForClassLoader(klass->GetClassLoader());
3018     ClassDataItemIterator it(dex_file, class_data);
3019     LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self,
3020                                                                 allocator,
3021                                                                 it.NumStaticFields());
3022     size_t num_sfields = 0;
3023     uint32_t last_field_idx = 0u;
3024     for (; it.HasNextStaticField(); it.Next()) {
3025       uint32_t field_idx = it.GetMemberIndex();
3026       DCHECK_GE(field_idx, last_field_idx);  // Ordering enforced by DexFileVerifier.
3027       if (num_sfields == 0 || LIKELY(field_idx > last_field_idx)) {
3028         DCHECK_LT(num_sfields, it.NumStaticFields());
3029         LoadField(it, klass, &sfields->At(num_sfields));
3030         ++num_sfields;
3031         last_field_idx = field_idx;
3032       }
3033     }
3034     // Load instance fields.
3035     LengthPrefixedArray<ArtField>* ifields = AllocArtFieldArray(self,
3036                                                                 allocator,
3037                                                                 it.NumInstanceFields());
3038     size_t num_ifields = 0u;
3039     last_field_idx = 0u;
3040     for (; it.HasNextInstanceField(); it.Next()) {
3041       uint32_t field_idx = it.GetMemberIndex();
3042       DCHECK_GE(field_idx, last_field_idx);  // Ordering enforced by DexFileVerifier.
3043       if (num_ifields == 0 || LIKELY(field_idx > last_field_idx)) {
3044         DCHECK_LT(num_ifields, it.NumInstanceFields());
3045         LoadField(it, klass, &ifields->At(num_ifields));
3046         ++num_ifields;
3047         last_field_idx = field_idx;
3048       }
3049     }
3050     if (UNLIKELY(num_sfields != it.NumStaticFields()) ||
3051         UNLIKELY(num_ifields != it.NumInstanceFields())) {
3052       LOG(WARNING) << "Duplicate fields in class " << PrettyDescriptor(klass.Get())
3053           << " (unique static fields: " << num_sfields << "/" << it.NumStaticFields()
3054           << ", unique instance fields: " << num_ifields << "/" << it.NumInstanceFields() << ")";
3055       // NOTE: Not shrinking the over-allocated sfields/ifields, just setting size.
3056       if (sfields != nullptr) {
3057         sfields->SetSize(num_sfields);
3058       }
3059       if (ifields != nullptr) {
3060         ifields->SetSize(num_ifields);
3061       }
3062     }
3063     // Set the field arrays.
3064     klass->SetSFieldsPtr(sfields);
3065     DCHECK_EQ(klass->NumStaticFields(), num_sfields);
3066     klass->SetIFieldsPtr(ifields);
3067     DCHECK_EQ(klass->NumInstanceFields(), num_ifields);
3068     // Load methods.
3069     klass->SetMethodsPtr(
3070         AllocArtMethodArray(self, allocator, it.NumDirectMethods() + it.NumVirtualMethods()),
3071         it.NumDirectMethods(),
3072         it.NumVirtualMethods());
3073     size_t class_def_method_index = 0;
3074     uint32_t last_dex_method_index = DexFile::kDexNoIndex;
3075     size_t last_class_def_method_index = 0;
3076     // TODO These should really use the iterators.
3077     for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
3078       ArtMethod* method = klass->GetDirectMethodUnchecked(i, image_pointer_size_);
3079       LoadMethod(self, dex_file, it, klass, method);
3080       LinkCode(method, oat_class, class_def_method_index);
3081       uint32_t it_method_index = it.GetMemberIndex();
3082       if (last_dex_method_index == it_method_index) {
3083         // duplicate case
3084         method->SetMethodIndex(last_class_def_method_index);
3085       } else {
3086         method->SetMethodIndex(class_def_method_index);
3087         last_dex_method_index = it_method_index;
3088         last_class_def_method_index = class_def_method_index;
3089       }
3090       class_def_method_index++;
3091     }
3092     for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
3093       ArtMethod* method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
3094       LoadMethod(self, dex_file, it, klass, method);
3095       DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
3096       LinkCode(method, oat_class, class_def_method_index);
3097       class_def_method_index++;
3098     }
3099     DCHECK(!it.HasNext());
3100   }
3101   // Ensure that the card is marked so that remembered sets pick up native roots.
3102   Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass.Get());
3103   self->AllowThreadSuspension();
3104 }
3105 
LoadField(const ClassDataItemIterator & it,Handle<mirror::Class> klass,ArtField * dst)3106 void ClassLinker::LoadField(const ClassDataItemIterator& it,
3107                             Handle<mirror::Class> klass,
3108                             ArtField* dst) {
3109   const uint32_t field_idx = it.GetMemberIndex();
3110   dst->SetDexFieldIndex(field_idx);
3111   dst->SetDeclaringClass(klass.Get());
3112   dst->SetAccessFlags(it.GetFieldAccessFlags());
3113 }
3114 
LoadMethod(Thread * self,const DexFile & dex_file,const ClassDataItemIterator & it,Handle<mirror::Class> klass,ArtMethod * dst)3115 void ClassLinker::LoadMethod(Thread* self,
3116                              const DexFile& dex_file,
3117                              const ClassDataItemIterator& it,
3118                              Handle<mirror::Class> klass,
3119                              ArtMethod* dst) {
3120   uint32_t dex_method_idx = it.GetMemberIndex();
3121   const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
3122   const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
3123 
3124   ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
3125   dst->SetDexMethodIndex(dex_method_idx);
3126   dst->SetDeclaringClass(klass.Get());
3127   dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
3128 
3129   dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods(), image_pointer_size_);
3130   dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes(), image_pointer_size_);
3131 
3132   uint32_t access_flags = it.GetMethodAccessFlags();
3133 
3134   if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
3135     // Set finalizable flag on declaring class.
3136     if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
3137       // Void return type.
3138       if (klass->GetClassLoader() != nullptr) {  // All non-boot finalizer methods are flagged.
3139         klass->SetFinalizable();
3140       } else {
3141         std::string temp;
3142         const char* klass_descriptor = klass->GetDescriptor(&temp);
3143         // The Enum class declares a "final" finalize() method to prevent subclasses from
3144         // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
3145         // subclasses, so we exclude it here.
3146         // We also want to avoid setting the flag on Object, where we know that finalize() is
3147         // empty.
3148         if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
3149             strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
3150           klass->SetFinalizable();
3151         }
3152       }
3153     }
3154   } else if (method_name[0] == '<') {
3155     // Fix broken access flags for initializers. Bug 11157540.
3156     bool is_init = (strcmp("<init>", method_name) == 0);
3157     bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
3158     if (UNLIKELY(!is_init && !is_clinit)) {
3159       LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
3160     } else {
3161       if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
3162         LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
3163             << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
3164         access_flags |= kAccConstructor;
3165       }
3166     }
3167   }
3168   dst->SetAccessFlags(access_flags);
3169 }
3170 
AppendToBootClassPath(Thread * self,const DexFile & dex_file)3171 void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
3172   StackHandleScope<1> hs(self);
3173   Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(
3174       self,
3175       dex_file,
3176       Runtime::Current()->GetLinearAlloc())));
3177   CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3178                                     << dex_file.GetLocation();
3179   AppendToBootClassPath(dex_file, dex_cache);
3180 }
3181 
AppendToBootClassPath(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)3182 void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
3183                                         Handle<mirror::DexCache> dex_cache) {
3184   CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
3185   boot_class_path_.push_back(&dex_file);
3186   RegisterDexFile(dex_file, dex_cache);
3187 }
3188 
RegisterDexFileLocked(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)3189 void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
3190                                         Handle<mirror::DexCache> dex_cache) {
3191   Thread* const self = Thread::Current();
3192   dex_lock_.AssertExclusiveHeld(self);
3193   CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
3194   // For app images, the dex cache location may be a suffix of the dex file location since the
3195   // dex file location is an absolute path.
3196   const std::string dex_cache_location = dex_cache->GetLocation()->ToModifiedUtf8();
3197   const size_t dex_cache_length = dex_cache_location.length();
3198   CHECK_GT(dex_cache_length, 0u) << dex_file.GetLocation();
3199   std::string dex_file_location = dex_file.GetLocation();
3200   CHECK_GE(dex_file_location.length(), dex_cache_length)
3201       << dex_cache_location << " " << dex_file.GetLocation();
3202   // Take suffix.
3203   const std::string dex_file_suffix = dex_file_location.substr(
3204       dex_file_location.length() - dex_cache_length,
3205       dex_cache_length);
3206   // Example dex_cache location is SettingsProvider.apk and
3207   // dex file location is /system/priv-app/SettingsProvider/SettingsProvider.apk
3208   CHECK_EQ(dex_cache_location, dex_file_suffix);
3209   // Clean up pass to remove null dex caches.
3210   // Null dex caches can occur due to class unloading and we are lazily removing null entries.
3211   JavaVMExt* const vm = self->GetJniEnv()->vm;
3212   for (auto it = dex_caches_.begin(); it != dex_caches_.end(); ) {
3213     DexCacheData data = *it;
3214     if (self->IsJWeakCleared(data.weak_root)) {
3215       vm->DeleteWeakGlobalRef(self, data.weak_root);
3216       it = dex_caches_.erase(it);
3217     } else {
3218       ++it;
3219     }
3220   }
3221   jweak dex_cache_jweak = vm->AddWeakGlobalRef(self, dex_cache.Get());
3222   dex_cache->SetDexFile(&dex_file);
3223   DexCacheData data;
3224   data.weak_root = dex_cache_jweak;
3225   data.dex_file = dex_cache->GetDexFile();
3226   data.resolved_types = dex_cache->GetResolvedTypes();
3227   dex_caches_.push_back(data);
3228 }
3229 
RegisterDexFile(const DexFile & dex_file,mirror::ClassLoader * class_loader)3230 mirror::DexCache* ClassLinker::RegisterDexFile(const DexFile& dex_file,
3231                                                mirror::ClassLoader* class_loader) {
3232   Thread* self = Thread::Current();
3233   {
3234     ReaderMutexLock mu(self, dex_lock_);
3235     mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
3236     if (dex_cache != nullptr) {
3237       return dex_cache;
3238     }
3239   }
3240   LinearAlloc* const linear_alloc = GetOrCreateAllocatorForClassLoader(class_loader);
3241   DCHECK(linear_alloc != nullptr);
3242   ClassTable* table;
3243   {
3244     WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3245     table = InsertClassTableForClassLoader(class_loader);
3246   }
3247   // Don't alloc while holding the lock, since allocation may need to
3248   // suspend all threads and another thread may need the dex_lock_ to
3249   // get to a suspend point.
3250   StackHandleScope<1> hs(self);
3251   Handle<mirror::DexCache> h_dex_cache(hs.NewHandle(AllocDexCache(self, dex_file, linear_alloc)));
3252   {
3253     WriterMutexLock mu(self, dex_lock_);
3254     mirror::DexCache* dex_cache = FindDexCacheLocked(self, dex_file, true);
3255     if (dex_cache != nullptr) {
3256       return dex_cache;
3257     }
3258     if (h_dex_cache.Get() == nullptr) {
3259       self->AssertPendingOOMException();
3260       return nullptr;
3261     }
3262     RegisterDexFileLocked(dex_file, h_dex_cache);
3263   }
3264   table->InsertStrongRoot(h_dex_cache.Get());
3265   return h_dex_cache.Get();
3266 }
3267 
RegisterDexFile(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)3268 void ClassLinker::RegisterDexFile(const DexFile& dex_file,
3269                                   Handle<mirror::DexCache> dex_cache) {
3270   WriterMutexLock mu(Thread::Current(), dex_lock_);
3271   RegisterDexFileLocked(dex_file, dex_cache);
3272 }
3273 
FindDexCache(Thread * self,const DexFile & dex_file,bool allow_failure)3274 mirror::DexCache* ClassLinker::FindDexCache(Thread* self,
3275                                             const DexFile& dex_file,
3276                                             bool allow_failure) {
3277   ReaderMutexLock mu(self, dex_lock_);
3278   return FindDexCacheLocked(self, dex_file, allow_failure);
3279 }
3280 
FindDexCacheLocked(Thread * self,const DexFile & dex_file,bool allow_failure)3281 mirror::DexCache* ClassLinker::FindDexCacheLocked(Thread* self,
3282                                                   const DexFile& dex_file,
3283                                                   bool allow_failure) {
3284   // Search assuming unique-ness of dex file.
3285   for (const DexCacheData& data : dex_caches_) {
3286     // Avoid decoding (and read barriers) other unrelated dex caches.
3287     if (data.dex_file == &dex_file) {
3288       mirror::DexCache* dex_cache =
3289           down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
3290       if (dex_cache != nullptr) {
3291         return dex_cache;
3292       } else {
3293         break;
3294       }
3295     }
3296   }
3297   if (allow_failure) {
3298     return nullptr;
3299   }
3300   std::string location(dex_file.GetLocation());
3301   // Failure, dump diagnostic and abort.
3302   for (const DexCacheData& data : dex_caches_) {
3303     mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
3304     if (dex_cache != nullptr) {
3305       LOG(ERROR) << "Registered dex file " << dex_cache->GetDexFile()->GetLocation();
3306     }
3307   }
3308   LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
3309   UNREACHABLE();
3310 }
3311 
FixupDexCaches(ArtMethod * resolution_method)3312 void ClassLinker::FixupDexCaches(ArtMethod* resolution_method) {
3313   Thread* const self = Thread::Current();
3314   ReaderMutexLock mu(self, dex_lock_);
3315   for (const DexCacheData& data : dex_caches_) {
3316     if (!self->IsJWeakCleared(data.weak_root)) {
3317       mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(
3318           self->DecodeJObject(data.weak_root));
3319       if (dex_cache != nullptr) {
3320         dex_cache->Fixup(resolution_method, image_pointer_size_);
3321       }
3322     }
3323   }
3324 }
3325 
CreatePrimitiveClass(Thread * self,Primitive::Type type)3326 mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
3327   mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize(image_pointer_size_));
3328   if (UNLIKELY(klass == nullptr)) {
3329     self->AssertPendingOOMException();
3330     return nullptr;
3331   }
3332   return InitializePrimitiveClass(klass, type);
3333 }
3334 
InitializePrimitiveClass(mirror::Class * primitive_class,Primitive::Type type)3335 mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3336                                                      Primitive::Type type) {
3337   CHECK(primitive_class != nullptr);
3338   // Must hold lock on object when initializing.
3339   Thread* self = Thread::Current();
3340   StackHandleScope<1> hs(self);
3341   Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
3342   ObjectLock<mirror::Class> lock(self, h_class);
3343   h_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3344   h_class->SetPrimitiveType(type);
3345   mirror::Class::SetStatus(h_class, mirror::Class::kStatusInitialized, self);
3346   const char* descriptor = Primitive::Descriptor(type);
3347   mirror::Class* existing = InsertClass(descriptor, h_class.Get(),
3348                                         ComputeModifiedUtf8Hash(descriptor));
3349   CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
3350   return h_class.Get();
3351 }
3352 
3353 // Create an array class (i.e. the class object for the array, not the
3354 // array itself).  "descriptor" looks like "[C" or "[[[[B" or
3355 // "[Ljava/lang/String;".
3356 //
3357 // If "descriptor" refers to an array of primitives, look up the
3358 // primitive type's internally-generated class object.
3359 //
3360 // "class_loader" is the class loader of the class that's referring to
3361 // us.  It's used to ensure that we're looking for the element type in
3362 // the right context.  It does NOT become the class loader for the
3363 // array class; that always comes from the base element class.
3364 //
3365 // Returns null with an exception raised on failure.
CreateArrayClass(Thread * self,const char * descriptor,size_t hash,Handle<mirror::ClassLoader> class_loader)3366 mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
3367                                              Handle<mirror::ClassLoader> class_loader) {
3368   // Identify the underlying component type
3369   CHECK_EQ('[', descriptor[0]);
3370   StackHandleScope<2> hs(self);
3371   MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3372                                                                      class_loader)));
3373   if (component_type.Get() == nullptr) {
3374     DCHECK(self->IsExceptionPending());
3375     // We need to accept erroneous classes as component types.
3376     const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3377     component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
3378     if (component_type.Get() == nullptr) {
3379       DCHECK(self->IsExceptionPending());
3380       return nullptr;
3381     } else {
3382       self->ClearException();
3383     }
3384   }
3385   if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3386     ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3387     return nullptr;
3388   }
3389   // See if the component type is already loaded.  Array classes are
3390   // always associated with the class loader of their underlying
3391   // element type -- an array of Strings goes with the loader for
3392   // java/lang/String -- so we need to look for it there.  (The
3393   // caller should have checked for the existence of the class
3394   // before calling here, but they did so with *their* class loader,
3395   // not the component type's loader.)
3396   //
3397   // If we find it, the caller adds "loader" to the class' initiating
3398   // loader list, which should prevent us from going through this again.
3399   //
3400   // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
3401   // are the same, because our caller (FindClass) just did the
3402   // lookup.  (Even if we get this wrong we still have correct behavior,
3403   // because we effectively do this lookup again when we add the new
3404   // class to the hash table --- necessary because of possible races with
3405   // other threads.)
3406   if (class_loader.Get() != component_type->GetClassLoader()) {
3407     mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
3408     if (new_class != nullptr) {
3409       return new_class;
3410     }
3411   }
3412 
3413   // Fill out the fields in the Class.
3414   //
3415   // It is possible to execute some methods against arrays, because
3416   // all arrays are subclasses of java_lang_Object_, so we need to set
3417   // up a vtable.  We can just point at the one in java_lang_Object_.
3418   //
3419   // Array classes are simple enough that we don't need to do a full
3420   // link step.
3421   auto new_class = hs.NewHandle<mirror::Class>(nullptr);
3422   if (UNLIKELY(!init_done_)) {
3423     // Classes that were hand created, ie not by FindSystemClass
3424     if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
3425       new_class.Assign(GetClassRoot(kClassArrayClass));
3426     } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
3427       new_class.Assign(GetClassRoot(kObjectArrayClass));
3428     } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
3429       new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
3430     } else if (strcmp(descriptor, "[C") == 0) {
3431       new_class.Assign(GetClassRoot(kCharArrayClass));
3432     } else if (strcmp(descriptor, "[I") == 0) {
3433       new_class.Assign(GetClassRoot(kIntArrayClass));
3434     } else if (strcmp(descriptor, "[J") == 0) {
3435       new_class.Assign(GetClassRoot(kLongArrayClass));
3436     }
3437   }
3438   if (new_class.Get() == nullptr) {
3439     new_class.Assign(AllocClass(self, mirror::Array::ClassSize(image_pointer_size_)));
3440     if (new_class.Get() == nullptr) {
3441       self->AssertPendingOOMException();
3442       return nullptr;
3443     }
3444     new_class->SetComponentType(component_type.Get());
3445   }
3446   ObjectLock<mirror::Class> lock(self, new_class);  // Must hold lock on object when initializing.
3447   DCHECK(new_class->GetComponentType() != nullptr);
3448   mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
3449   new_class->SetSuperClass(java_lang_Object);
3450   new_class->SetVTable(java_lang_Object->GetVTable());
3451   new_class->SetPrimitiveType(Primitive::kPrimNot);
3452   new_class->SetClassLoader(component_type->GetClassLoader());
3453   if (component_type->IsPrimitive()) {
3454     new_class->SetClassFlags(mirror::kClassFlagNoReferenceFields);
3455   } else {
3456     new_class->SetClassFlags(mirror::kClassFlagObjectArray);
3457   }
3458   mirror::Class::SetStatus(new_class, mirror::Class::kStatusLoaded, self);
3459   {
3460     ArtMethod* imt[mirror::Class::kImtSize];
3461     std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod());
3462     new_class->PopulateEmbeddedImtAndVTable(imt, image_pointer_size_);
3463   }
3464   mirror::Class::SetStatus(new_class, mirror::Class::kStatusInitialized, self);
3465   // don't need to set new_class->SetObjectSize(..)
3466   // because Object::SizeOf delegates to Array::SizeOf
3467 
3468 
3469   // All arrays have java/lang/Cloneable and java/io/Serializable as
3470   // interfaces.  We need to set that up here, so that stuff like
3471   // "instanceof" works right.
3472   //
3473   // Note: The GC could run during the call to FindSystemClass,
3474   // so we need to make sure the class object is GC-valid while we're in
3475   // there.  Do this by clearing the interface list so the GC will just
3476   // think that the entries are null.
3477 
3478 
3479   // Use the single, global copies of "interfaces" and "iftable"
3480   // (remember not to free them for arrays).
3481   {
3482     mirror::IfTable* array_iftable = array_iftable_.Read();
3483     CHECK(array_iftable != nullptr);
3484     new_class->SetIfTable(array_iftable);
3485   }
3486 
3487   // Inherit access flags from the component type.
3488   int access_flags = new_class->GetComponentType()->GetAccessFlags();
3489   // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3490   access_flags &= kAccJavaFlagsMask;
3491   // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
3492   // and remove "interface".
3493   access_flags |= kAccAbstract | kAccFinal;
3494   access_flags &= ~kAccInterface;
3495 
3496   new_class->SetAccessFlags(access_flags);
3497 
3498   mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
3499   if (existing == nullptr) {
3500     jit::Jit::NewTypeLoadedIfUsingJit(new_class.Get());
3501     return new_class.Get();
3502   }
3503   // Another thread must have loaded the class after we
3504   // started but before we finished.  Abandon what we've
3505   // done.
3506   //
3507   // (Yes, this happens.)
3508 
3509   return existing;
3510 }
3511 
FindPrimitiveClass(char type)3512 mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
3513   switch (type) {
3514     case 'B':
3515       return GetClassRoot(kPrimitiveByte);
3516     case 'C':
3517       return GetClassRoot(kPrimitiveChar);
3518     case 'D':
3519       return GetClassRoot(kPrimitiveDouble);
3520     case 'F':
3521       return GetClassRoot(kPrimitiveFloat);
3522     case 'I':
3523       return GetClassRoot(kPrimitiveInt);
3524     case 'J':
3525       return GetClassRoot(kPrimitiveLong);
3526     case 'S':
3527       return GetClassRoot(kPrimitiveShort);
3528     case 'Z':
3529       return GetClassRoot(kPrimitiveBoolean);
3530     case 'V':
3531       return GetClassRoot(kPrimitiveVoid);
3532     default:
3533       break;
3534   }
3535   std::string printable_type(PrintableChar(type));
3536   ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
3537   return nullptr;
3538 }
3539 
InsertClass(const char * descriptor,mirror::Class * klass,size_t hash)3540 mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass, size_t hash) {
3541   if (VLOG_IS_ON(class_linker)) {
3542     mirror::DexCache* dex_cache = klass->GetDexCache();
3543     std::string source;
3544     if (dex_cache != nullptr) {
3545       source += " from ";
3546       source += dex_cache->GetLocation()->ToModifiedUtf8();
3547     }
3548     LOG(INFO) << "Loaded class " << descriptor << source;
3549   }
3550   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3551   mirror::ClassLoader* const class_loader = klass->GetClassLoader();
3552   ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
3553   mirror::Class* existing = class_table->Lookup(descriptor, hash);
3554   if (existing != nullptr) {
3555     return existing;
3556   }
3557   if (kIsDebugBuild &&
3558       !klass->IsTemp() &&
3559       class_loader == nullptr &&
3560       dex_cache_boot_image_class_lookup_required_) {
3561     // Check a class loaded with the system class loader matches one in the image if the class
3562     // is in the image.
3563     existing = LookupClassFromBootImage(descriptor);
3564     if (existing != nullptr) {
3565       CHECK_EQ(klass, existing);
3566     }
3567   }
3568   VerifyObject(klass);
3569   class_table->InsertWithHash(klass, hash);
3570   if (class_loader != nullptr) {
3571     // This is necessary because we need to have the card dirtied for remembered sets.
3572     Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
3573   }
3574   if (log_new_class_table_roots_) {
3575     new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
3576   }
3577   return nullptr;
3578 }
3579 
3580 // TODO This should really be in mirror::Class.
UpdateClassMethods(mirror::Class * klass,LengthPrefixedArray<ArtMethod> * new_methods)3581 void ClassLinker::UpdateClassMethods(mirror::Class* klass,
3582                                      LengthPrefixedArray<ArtMethod>* new_methods) {
3583   klass->SetMethodsPtrUnchecked(new_methods,
3584                                 klass->NumDirectMethods(),
3585                                 klass->NumDeclaredVirtualMethods());
3586   // Need to mark the card so that the remembered sets and mod union tables get updated.
3587   Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(klass);
3588 }
3589 
RemoveClass(const char * descriptor,mirror::ClassLoader * class_loader)3590 bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
3591   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3592   ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3593   return class_table != nullptr && class_table->Remove(descriptor);
3594 }
3595 
LookupClass(Thread * self,const char * descriptor,size_t hash,mirror::ClassLoader * class_loader)3596 mirror::Class* ClassLinker::LookupClass(Thread* self,
3597                                         const char* descriptor,
3598                                         size_t hash,
3599                                         mirror::ClassLoader* class_loader) {
3600   {
3601     ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3602     ClassTable* const class_table = ClassTableForClassLoader(class_loader);
3603     if (class_table != nullptr) {
3604       mirror::Class* result = class_table->Lookup(descriptor, hash);
3605       if (result != nullptr) {
3606         return result;
3607       }
3608     }
3609   }
3610   if (class_loader != nullptr || !dex_cache_boot_image_class_lookup_required_) {
3611     return nullptr;
3612   }
3613   // Lookup failed but need to search dex_caches_.
3614   mirror::Class* result = LookupClassFromBootImage(descriptor);
3615   if (result != nullptr) {
3616     result = InsertClass(descriptor, result, hash);
3617   } else {
3618     // Searching the image dex files/caches failed, we don't want to get into this situation
3619     // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3620     // classes into the class table.
3621     constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
3622     if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3623       AddBootImageClassesToClassTable();
3624     }
3625   }
3626   return result;
3627 }
3628 
GetImageDexCaches(std::vector<gc::space::ImageSpace * > image_spaces)3629 static std::vector<mirror::ObjectArray<mirror::DexCache>*> GetImageDexCaches(
3630     std::vector<gc::space::ImageSpace*> image_spaces) SHARED_REQUIRES(Locks::mutator_lock_) {
3631   CHECK(!image_spaces.empty());
3632   std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector;
3633   for (gc::space::ImageSpace* image_space : image_spaces) {
3634     mirror::Object* root = image_space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3635     DCHECK(root != nullptr);
3636     dex_caches_vector.push_back(root->AsObjectArray<mirror::DexCache>());
3637   }
3638   return dex_caches_vector;
3639 }
3640 
AddBootImageClassesToClassTable()3641 void ClassLinker::AddBootImageClassesToClassTable() {
3642   if (dex_cache_boot_image_class_lookup_required_) {
3643     AddImageClassesToClassTable(Runtime::Current()->GetHeap()->GetBootImageSpaces(),
3644                                 /*class_loader*/nullptr);
3645     dex_cache_boot_image_class_lookup_required_ = false;
3646   }
3647 }
3648 
AddImageClassesToClassTable(std::vector<gc::space::ImageSpace * > image_spaces,mirror::ClassLoader * class_loader)3649 void ClassLinker::AddImageClassesToClassTable(std::vector<gc::space::ImageSpace*> image_spaces,
3650                                               mirror::ClassLoader* class_loader) {
3651   Thread* self = Thread::Current();
3652   WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3653   ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
3654 
3655   ClassTable* const class_table = InsertClassTableForClassLoader(class_loader);
3656 
3657   std::string temp;
3658   std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector =
3659       GetImageDexCaches(image_spaces);
3660   for (mirror::ObjectArray<mirror::DexCache>* dex_caches : dex_caches_vector) {
3661     for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3662       mirror::DexCache* dex_cache = dex_caches->Get(i);
3663       GcRoot<mirror::Class>* types = dex_cache->GetResolvedTypes();
3664       for (int32_t j = 0, num_types = dex_cache->NumResolvedTypes(); j < num_types; j++) {
3665         mirror::Class* klass = types[j].Read();
3666         if (klass != nullptr) {
3667           DCHECK_EQ(klass->GetClassLoader(), class_loader);
3668           const char* descriptor = klass->GetDescriptor(&temp);
3669           size_t hash = ComputeModifiedUtf8Hash(descriptor);
3670           mirror::Class* existing = class_table->Lookup(descriptor, hash);
3671           if (existing != nullptr) {
3672             CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
3673                 << PrettyClassAndClassLoader(klass);
3674           } else {
3675             class_table->Insert(klass);
3676             if (log_new_class_table_roots_) {
3677               new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
3678             }
3679           }
3680         }
3681       }
3682     }
3683   }
3684 }
3685 
3686 class MoveClassTableToPreZygoteVisitor : public ClassLoaderVisitor {
3687  public:
MoveClassTableToPreZygoteVisitor()3688   explicit MoveClassTableToPreZygoteVisitor() {}
3689 
Visit(mirror::ClassLoader * class_loader)3690   void Visit(mirror::ClassLoader* class_loader)
3691       REQUIRES(Locks::classlinker_classes_lock_)
3692       SHARED_REQUIRES(Locks::mutator_lock_) OVERRIDE {
3693     ClassTable* const class_table = class_loader->GetClassTable();
3694     if (class_table != nullptr) {
3695       class_table->FreezeSnapshot();
3696     }
3697   }
3698 };
3699 
MoveClassTableToPreZygote()3700 void ClassLinker::MoveClassTableToPreZygote() {
3701   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3702   boot_class_table_.FreezeSnapshot();
3703   MoveClassTableToPreZygoteVisitor visitor;
3704   VisitClassLoaders(&visitor);
3705 }
3706 
LookupClassFromBootImage(const char * descriptor)3707 mirror::Class* ClassLinker::LookupClassFromBootImage(const char* descriptor) {
3708   ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
3709   std::vector<mirror::ObjectArray<mirror::DexCache>*> dex_caches_vector =
3710       GetImageDexCaches(Runtime::Current()->GetHeap()->GetBootImageSpaces());
3711   for (mirror::ObjectArray<mirror::DexCache>* dex_caches : dex_caches_vector) {
3712     for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3713       mirror::DexCache* dex_cache = dex_caches->Get(i);
3714       const DexFile* dex_file = dex_cache->GetDexFile();
3715       // Try binary searching the type index by descriptor.
3716       const DexFile::TypeId* type_id = dex_file->FindTypeId(descriptor);
3717       if (type_id != nullptr) {
3718         uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3719         mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3720         if (klass != nullptr) {
3721           return klass;
3722         }
3723       }
3724     }
3725   }
3726   return nullptr;
3727 }
3728 
3729 // Look up classes by hash and descriptor and put all matching ones in the result array.
3730 class LookupClassesVisitor : public ClassLoaderVisitor {
3731  public:
LookupClassesVisitor(const char * descriptor,size_t hash,std::vector<mirror::Class * > * result)3732   LookupClassesVisitor(const char* descriptor, size_t hash, std::vector<mirror::Class*>* result)
3733      : descriptor_(descriptor),
3734        hash_(hash),
3735        result_(result) {}
3736 
Visit(mirror::ClassLoader * class_loader)3737   void Visit(mirror::ClassLoader* class_loader)
3738       SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
3739     ClassTable* const class_table = class_loader->GetClassTable();
3740     mirror::Class* klass = class_table->Lookup(descriptor_, hash_);
3741     if (klass != nullptr) {
3742       result_->push_back(klass);
3743     }
3744   }
3745 
3746  private:
3747   const char* const descriptor_;
3748   const size_t hash_;
3749   std::vector<mirror::Class*>* const result_;
3750 };
3751 
LookupClasses(const char * descriptor,std::vector<mirror::Class * > & result)3752 void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3753   result.clear();
3754   if (dex_cache_boot_image_class_lookup_required_) {
3755     AddBootImageClassesToClassTable();
3756   }
3757   Thread* const self = Thread::Current();
3758   ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3759   const size_t hash = ComputeModifiedUtf8Hash(descriptor);
3760   mirror::Class* klass = boot_class_table_.Lookup(descriptor, hash);
3761   if (klass != nullptr) {
3762     result.push_back(klass);
3763   }
3764   LookupClassesVisitor visitor(descriptor, hash, &result);
3765   VisitClassLoaders(&visitor);
3766 }
3767 
AttemptSupertypeVerification(Thread * self,Handle<mirror::Class> klass,Handle<mirror::Class> supertype)3768 bool ClassLinker::AttemptSupertypeVerification(Thread* self,
3769                                                Handle<mirror::Class> klass,
3770                                                Handle<mirror::Class> supertype) {
3771   DCHECK(self != nullptr);
3772   DCHECK(klass.Get() != nullptr);
3773   DCHECK(supertype.Get() != nullptr);
3774 
3775   if (!supertype->IsVerified() && !supertype->IsErroneous()) {
3776     VerifyClass(self, supertype);
3777   }
3778   if (supertype->IsCompileTimeVerified()) {
3779     // Either we are verified or we soft failed and need to retry at runtime.
3780     return true;
3781   }
3782   // If we got this far then we have a hard failure.
3783   std::string error_msg =
3784       StringPrintf("Rejecting class %s that attempts to sub-type erroneous class %s",
3785                    PrettyDescriptor(klass.Get()).c_str(),
3786                    PrettyDescriptor(supertype.Get()).c_str());
3787   LOG(WARNING) << error_msg  << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
3788   StackHandleScope<1> hs(self);
3789   Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
3790   if (cause.Get() != nullptr) {
3791     // Set during VerifyClass call (if at all).
3792     self->ClearException();
3793   }
3794   // Change into a verify error.
3795   ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3796   if (cause.Get() != nullptr) {
3797     self->GetException()->SetCause(cause.Get());
3798   }
3799   ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3800   if (Runtime::Current()->IsAotCompiler()) {
3801     Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3802   }
3803   // Need to grab the lock to change status.
3804   ObjectLock<mirror::Class> super_lock(self, klass);
3805   mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
3806   return false;
3807 }
3808 
VerifyClass(Thread * self,Handle<mirror::Class> klass,LogSeverity log_level)3809 void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass, LogSeverity log_level) {
3810   {
3811     // TODO: assert that the monitor on the Class is held
3812     ObjectLock<mirror::Class> lock(self, klass);
3813 
3814     // Is somebody verifying this now?
3815     mirror::Class::Status old_status = klass->GetStatus();
3816     while (old_status == mirror::Class::kStatusVerifying ||
3817         old_status == mirror::Class::kStatusVerifyingAtRuntime) {
3818       lock.WaitIgnoringInterrupts();
3819       CHECK(klass->IsErroneous() || (klass->GetStatus() > old_status))
3820           << "Class '" << PrettyClass(klass.Get()) << "' performed an illegal verification state "
3821           << "transition from " << old_status << " to " << klass->GetStatus();
3822       old_status = klass->GetStatus();
3823     }
3824 
3825     // The class might already be erroneous, for example at compile time if we attempted to verify
3826     // this class as a parent to another.
3827     if (klass->IsErroneous()) {
3828       ThrowEarlierClassFailure(klass.Get());
3829       return;
3830     }
3831 
3832     // Don't attempt to re-verify if already sufficiently verified.
3833     if (klass->IsVerified()) {
3834       EnsureSkipAccessChecksMethods(klass);
3835       return;
3836     }
3837     if (klass->IsCompileTimeVerified() && Runtime::Current()->IsAotCompiler()) {
3838       return;
3839     }
3840 
3841     if (klass->GetStatus() == mirror::Class::kStatusResolved) {
3842       mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifying, self);
3843     } else {
3844       CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
3845             << PrettyClass(klass.Get());
3846       CHECK(!Runtime::Current()->IsAotCompiler());
3847       mirror::Class::SetStatus(klass, mirror::Class::kStatusVerifyingAtRuntime, self);
3848     }
3849 
3850     // Skip verification if disabled.
3851     if (!Runtime::Current()->IsVerificationEnabled()) {
3852       mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
3853       EnsureSkipAccessChecksMethods(klass);
3854       return;
3855     }
3856   }
3857 
3858   // Verify super class.
3859   StackHandleScope<2> hs(self);
3860   MutableHandle<mirror::Class> supertype(hs.NewHandle(klass->GetSuperClass()));
3861   // If we have a superclass and we get a hard verification failure we can return immediately.
3862   if (supertype.Get() != nullptr && !AttemptSupertypeVerification(self, klass, supertype)) {
3863     CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
3864     return;
3865   }
3866 
3867   // Verify all default super-interfaces.
3868   //
3869   // (1) Don't bother if the superclass has already had a soft verification failure.
3870   //
3871   // (2) Interfaces shouldn't bother to do this recursive verification because they cannot cause
3872   //     recursive initialization by themselves. This is because when an interface is initialized
3873   //     directly it must not initialize its superinterfaces. We are allowed to verify regardless
3874   //     but choose not to for an optimization. If the interfaces is being verified due to a class
3875   //     initialization (which would need all the default interfaces to be verified) the class code
3876   //     will trigger the recursive verification anyway.
3877   if ((supertype.Get() == nullptr || supertype->IsVerified())  // See (1)
3878       && !klass->IsInterface()) {                              // See (2)
3879     int32_t iftable_count = klass->GetIfTableCount();
3880     MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
3881     // Loop through all interfaces this class has defined. It doesn't matter the order.
3882     for (int32_t i = 0; i < iftable_count; i++) {
3883       iface.Assign(klass->GetIfTable()->GetInterface(i));
3884       DCHECK(iface.Get() != nullptr);
3885       // We only care if we have default interfaces and can skip if we are already verified...
3886       if (LIKELY(!iface->HasDefaultMethods() || iface->IsVerified())) {
3887         continue;
3888       } else if (UNLIKELY(!AttemptSupertypeVerification(self, klass, iface))) {
3889         // We had a hard failure while verifying this interface. Just return immediately.
3890         CHECK(self->IsExceptionPending()) << "Verification error should be pending.";
3891         return;
3892       } else if (UNLIKELY(!iface->IsVerified())) {
3893         // We softly failed to verify the iface. Stop checking and clean up.
3894         // Put the iface into the supertype handle so we know what caused us to fail.
3895         supertype.Assign(iface.Get());
3896         break;
3897       }
3898     }
3899   }
3900 
3901   // At this point if verification failed, then supertype is the "first" supertype that failed
3902   // verification (without a specific order). If verification succeeded, then supertype is either
3903   // null or the original superclass of klass and is verified.
3904   DCHECK(supertype.Get() == nullptr ||
3905          supertype.Get() == klass->GetSuperClass() ||
3906          !supertype->IsVerified());
3907 
3908   // Try to use verification information from the oat file, otherwise do runtime verification.
3909   const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
3910   mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
3911   bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
3912   // If the oat file says the class had an error, re-run the verifier. That way we will get a
3913   // precise error message. To ensure a rerun, test:
3914   //     oat_file_class_status == mirror::Class::kStatusError => !preverified
3915   DCHECK(!(oat_file_class_status == mirror::Class::kStatusError) || !preverified);
3916 
3917   verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
3918   std::string error_msg;
3919   if (!preverified) {
3920     Runtime* runtime = Runtime::Current();
3921     verifier_failure = verifier::MethodVerifier::VerifyClass(self,
3922                                                              klass.Get(),
3923                                                              runtime->GetCompilerCallbacks(),
3924                                                              runtime->IsAotCompiler(),
3925                                                              log_level,
3926                                                              &error_msg);
3927   }
3928 
3929   // Verification is done, grab the lock again.
3930   ObjectLock<mirror::Class> lock(self, klass);
3931 
3932   if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
3933     if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
3934       VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
3935           << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3936           << " because: " << error_msg;
3937     }
3938     self->AssertNoPendingException();
3939     // Make sure all classes referenced by catch blocks are resolved.
3940     ResolveClassExceptionHandlerTypes(klass);
3941     if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
3942       // Even though there were no verifier failures we need to respect whether the super-class and
3943       // super-default-interfaces were verified or requiring runtime reverification.
3944       if (supertype.Get() == nullptr || supertype->IsVerified()) {
3945         mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
3946       } else {
3947         CHECK_EQ(supertype->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
3948         mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
3949         // Pretend a soft failure occurred so that we don't consider the class verified below.
3950         verifier_failure = verifier::MethodVerifier::kSoftFailure;
3951       }
3952     } else {
3953       CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3954       // Soft failures at compile time should be retried at runtime. Soft
3955       // failures at runtime will be handled by slow paths in the generated
3956       // code. Set status accordingly.
3957       if (Runtime::Current()->IsAotCompiler()) {
3958         mirror::Class::SetStatus(klass, mirror::Class::kStatusRetryVerificationAtRuntime, self);
3959       } else {
3960         mirror::Class::SetStatus(klass, mirror::Class::kStatusVerified, self);
3961         // As this is a fake verified status, make sure the methods are _not_ marked
3962         // kAccSkipAccessChecks later.
3963         klass->SetVerificationAttempted();
3964       }
3965     }
3966   } else {
3967     VLOG(verifier) << "Verification failed on class " << PrettyDescriptor(klass.Get())
3968                   << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3969                   << " because: " << error_msg;
3970     self->AssertNoPendingException();
3971     ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3972     mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
3973   }
3974   if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
3975     // Class is verified so we don't need to do any access check on its methods.
3976     // Let the interpreter know it by setting the kAccSkipAccessChecks flag onto each
3977     // method.
3978     // Note: we're going here during compilation and at runtime. When we set the
3979     // kAccSkipAccessChecks flag when compiling image classes, the flag is recorded
3980     // in the image and is set when loading the image.
3981 
3982     if (UNLIKELY(Runtime::Current()->IsVerificationSoftFail())) {
3983       // Never skip access checks if the verification soft fail is forced.
3984       // Mark the class as having a verification attempt to avoid re-running the verifier.
3985       klass->SetVerificationAttempted();
3986     } else {
3987       EnsureSkipAccessChecksMethods(klass);
3988     }
3989   }
3990 }
3991 
EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass)3992 void ClassLinker::EnsureSkipAccessChecksMethods(Handle<mirror::Class> klass) {
3993   if (!klass->WasVerificationAttempted()) {
3994     klass->SetSkipAccessChecksFlagOnAllMethods(image_pointer_size_);
3995     klass->SetVerificationAttempted();
3996   }
3997 }
3998 
VerifyClassUsingOatFile(const DexFile & dex_file,mirror::Class * klass,mirror::Class::Status & oat_file_class_status)3999 bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file,
4000                                           mirror::Class* klass,
4001                                           mirror::Class::Status& oat_file_class_status) {
4002   // If we're compiling, we can only verify the class using the oat file if
4003   // we are not compiling the image or if the class we're verifying is not part of
4004   // the app.  In other words, we will only check for preverification of bootclasspath
4005   // classes.
4006   if (Runtime::Current()->IsAotCompiler()) {
4007     // Are we compiling the bootclasspath?
4008     if (Runtime::Current()->GetCompilerCallbacks()->IsBootImage()) {
4009       return false;
4010     }
4011     // We are compiling an app (not the image).
4012 
4013     // Is this an app class? (I.e. not a bootclasspath class)
4014     if (klass->GetClassLoader() != nullptr) {
4015       return false;
4016     }
4017   }
4018 
4019   const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
4020   // In case we run without an image there won't be a backing oat file.
4021   if (oat_dex_file == nullptr) {
4022     return false;
4023   }
4024 
4025   // We may be running with a preopted oat file but without image. In this case,
4026   // we don't skip verification of skip_access_checks classes to ensure we initialize
4027   // dex caches with all types resolved during verification.
4028   // We need to trust image classes, as these might be coming out of a pre-opted, quickened boot
4029   // image (that we just failed loading), and the verifier can't be run on quickened opcodes when
4030   // the runtime isn't started. On the other hand, app classes can be re-verified even if they are
4031   // already pre-opted, as then the runtime is started.
4032   if (!Runtime::Current()->IsAotCompiler() &&
4033       !Runtime::Current()->GetHeap()->HasBootImageSpace() &&
4034       klass->GetClassLoader() != nullptr) {
4035     return false;
4036   }
4037 
4038   uint16_t class_def_index = klass->GetDexClassDefIndex();
4039   oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
4040   if (oat_file_class_status == mirror::Class::kStatusVerified ||
4041       oat_file_class_status == mirror::Class::kStatusInitialized) {
4042     return true;
4043   }
4044   // If we only verified a subset of the classes at compile time, we can end up with classes that
4045   // were resolved by the verifier.
4046   if (oat_file_class_status == mirror::Class::kStatusResolved) {
4047     return false;
4048   }
4049   if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
4050     // Compile time verification failed with a soft error. Compile time verification can fail
4051     // because we have incomplete type information. Consider the following:
4052     // class ... {
4053     //   Foo x;
4054     //   .... () {
4055     //     if (...) {
4056     //       v1 gets assigned a type of resolved class Foo
4057     //     } else {
4058     //       v1 gets assigned a type of unresolved class Bar
4059     //     }
4060     //     iput x = v1
4061     // } }
4062     // when we merge v1 following the if-the-else it results in Conflict
4063     // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
4064     // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
4065     // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
4066     // at compile time).
4067     return false;
4068   }
4069   if (oat_file_class_status == mirror::Class::kStatusError) {
4070     // Compile time verification failed with a hard error. This is caused by invalid instructions
4071     // in the class. These errors are unrecoverable.
4072     return false;
4073   }
4074   if (oat_file_class_status == mirror::Class::kStatusNotReady) {
4075     // Status is uninitialized if we couldn't determine the status at compile time, for example,
4076     // not loading the class.
4077     // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
4078     // isn't a problem and this case shouldn't occur
4079     return false;
4080   }
4081   std::string temp;
4082   LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
4083              << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
4084              << klass->GetDescriptor(&temp);
4085   UNREACHABLE();
4086 }
4087 
ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass)4088 void ClassLinker::ResolveClassExceptionHandlerTypes(Handle<mirror::Class> klass) {
4089   for (ArtMethod& method : klass->GetMethods(image_pointer_size_)) {
4090     ResolveMethodExceptionHandlerTypes(&method);
4091   }
4092 }
4093 
ResolveMethodExceptionHandlerTypes(ArtMethod * method)4094 void ClassLinker::ResolveMethodExceptionHandlerTypes(ArtMethod* method) {
4095   // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
4096   const DexFile::CodeItem* code_item =
4097       method->GetDexFile()->GetCodeItem(method->GetCodeItemOffset());
4098   if (code_item == nullptr) {
4099     return;  // native or abstract method
4100   }
4101   if (code_item->tries_size_ == 0) {
4102     return;  // nothing to process
4103   }
4104   const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
4105   uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
4106   for (uint32_t idx = 0; idx < handlers_size; idx++) {
4107     CatchHandlerIterator iterator(handlers_ptr);
4108     for (; iterator.HasNext(); iterator.Next()) {
4109       // Ensure exception types are resolved so that they don't need resolution to be delivered,
4110       // unresolved exception types will be ignored by exception delivery
4111       if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
4112         mirror::Class* exception_type = ResolveType(iterator.GetHandlerTypeIndex(), method);
4113         if (exception_type == nullptr) {
4114           DCHECK(Thread::Current()->IsExceptionPending());
4115           Thread::Current()->ClearException();
4116         }
4117       }
4118     }
4119     handlers_ptr = iterator.EndDataPointer();
4120   }
4121 }
4122 
CreateProxyClass(ScopedObjectAccessAlreadyRunnable & soa,jstring name,jobjectArray interfaces,jobject loader,jobjectArray methods,jobjectArray throws)4123 mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa,
4124                                              jstring name,
4125                                              jobjectArray interfaces,
4126                                              jobject loader,
4127                                              jobjectArray methods,
4128                                              jobjectArray throws) {
4129   Thread* self = soa.Self();
4130   StackHandleScope<10> hs(self);
4131   MutableHandle<mirror::Class> klass(hs.NewHandle(
4132       AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
4133   if (klass.Get() == nullptr) {
4134     CHECK(self->IsExceptionPending());  // OOME.
4135     return nullptr;
4136   }
4137   DCHECK(klass->GetClass() != nullptr);
4138   klass->SetObjectSize(sizeof(mirror::Proxy));
4139   // Set the class access flags incl. VerificationAttempted, so we do not try to set the flag on
4140   // the methods.
4141   klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccVerificationAttempted);
4142   klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
4143   DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
4144   klass->SetName(soa.Decode<mirror::String*>(name));
4145   klass->SetDexCache(GetClassRoot(kJavaLangReflectProxy)->GetDexCache());
4146   mirror::Class::SetStatus(klass, mirror::Class::kStatusIdx, self);
4147   std::string descriptor(GetDescriptorForProxy(klass.Get()));
4148   const size_t hash = ComputeModifiedUtf8Hash(descriptor.c_str());
4149 
4150   // Needs to be before we insert the class so that the allocator field is set.
4151   LinearAlloc* const allocator = GetOrCreateAllocatorForClassLoader(klass->GetClassLoader());
4152 
4153   // Insert the class before loading the fields as the field roots
4154   // (ArtField::declaring_class_) are only visited from the class
4155   // table. There can't be any suspend points between inserting the
4156   // class and setting the field arrays below.
4157   mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), hash);
4158   CHECK(existing == nullptr);
4159 
4160   // Instance fields are inherited, but we add a couple of static fields...
4161   const size_t num_fields = 2;
4162   LengthPrefixedArray<ArtField>* sfields = AllocArtFieldArray(self, allocator, num_fields);
4163   klass->SetSFieldsPtr(sfields);
4164 
4165   // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
4166   // our proxy, so Class.getInterfaces doesn't return the flattened set.
4167   ArtField& interfaces_sfield = sfields->At(0);
4168   interfaces_sfield.SetDexFieldIndex(0);
4169   interfaces_sfield.SetDeclaringClass(klass.Get());
4170   interfaces_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
4171 
4172   // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
4173   ArtField& throws_sfield = sfields->At(1);
4174   throws_sfield.SetDexFieldIndex(1);
4175   throws_sfield.SetDeclaringClass(klass.Get());
4176   throws_sfield.SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
4177 
4178   // Proxies have 1 direct method, the constructor
4179   const size_t num_direct_methods = 1;
4180 
4181   // They have as many virtual methods as the array
4182   auto h_methods = hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Method>*>(methods));
4183   DCHECK_EQ(h_methods->GetClass(), mirror::Method::ArrayClass())
4184       << PrettyClass(h_methods->GetClass());
4185   const size_t num_virtual_methods = h_methods->GetLength();
4186 
4187   // Create the methods array.
4188   LengthPrefixedArray<ArtMethod>* proxy_class_methods = AllocArtMethodArray(
4189         self, allocator, num_direct_methods + num_virtual_methods);
4190   // Currently AllocArtMethodArray cannot return null, but the OOM logic is left there in case we
4191   // want to throw OOM in the future.
4192   if (UNLIKELY(proxy_class_methods == nullptr)) {
4193     self->AssertPendingOOMException();
4194     return nullptr;
4195   }
4196   klass->SetMethodsPtr(proxy_class_methods, num_direct_methods, num_virtual_methods);
4197 
4198   // Create the single direct method.
4199   CreateProxyConstructor(klass, klass->GetDirectMethodUnchecked(0, image_pointer_size_));
4200 
4201   // Create virtual method using specified prototypes.
4202   // TODO These should really use the iterators.
4203   for (size_t i = 0; i < num_virtual_methods; ++i) {
4204     auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4205     auto* prototype = h_methods->Get(i)->GetArtMethod();
4206     CreateProxyMethod(klass, prototype, virtual_method);
4207     DCHECK(virtual_method->GetDeclaringClass() != nullptr);
4208     DCHECK(prototype->GetDeclaringClass() != nullptr);
4209   }
4210 
4211   // The super class is java.lang.reflect.Proxy
4212   klass->SetSuperClass(GetClassRoot(kJavaLangReflectProxy));
4213   // Now effectively in the loaded state.
4214   mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, self);
4215   self->AssertNoPendingException();
4216 
4217   MutableHandle<mirror::Class> new_class = hs.NewHandle<mirror::Class>(nullptr);
4218   {
4219     // Must hold lock on object when resolved.
4220     ObjectLock<mirror::Class> resolution_lock(self, klass);
4221     // Link the fields and virtual methods, creating vtable and iftables.
4222     // The new class will replace the old one in the class table.
4223     Handle<mirror::ObjectArray<mirror::Class>> h_interfaces(
4224         hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
4225     if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
4226       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4227       return nullptr;
4228     }
4229   }
4230   CHECK(klass->IsRetired());
4231   CHECK_NE(klass.Get(), new_class.Get());
4232   klass.Assign(new_class.Get());
4233 
4234   CHECK_EQ(interfaces_sfield.GetDeclaringClass(), klass.Get());
4235   interfaces_sfield.SetObject<false>(klass.Get(),
4236                                      soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
4237   CHECK_EQ(throws_sfield.GetDeclaringClass(), klass.Get());
4238   throws_sfield.SetObject<false>(
4239       klass.Get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
4240 
4241   {
4242     // Lock on klass is released. Lock new class object.
4243     ObjectLock<mirror::Class> initialization_lock(self, klass);
4244     mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
4245   }
4246 
4247   // sanity checks
4248   if (kIsDebugBuild) {
4249     CHECK(klass->GetIFieldsPtr() == nullptr);
4250     CheckProxyConstructor(klass->GetDirectMethod(0, image_pointer_size_));
4251 
4252     for (size_t i = 0; i < num_virtual_methods; ++i) {
4253       auto* virtual_method = klass->GetVirtualMethodUnchecked(i, image_pointer_size_);
4254       auto* prototype = h_methods->Get(i++)->GetArtMethod();
4255       CheckProxyMethod(virtual_method, prototype);
4256     }
4257 
4258     StackHandleScope<1> hs2(self);
4259     Handle<mirror::String> decoded_name = hs2.NewHandle(soa.Decode<mirror::String*>(name));
4260     std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
4261                                                    decoded_name->ToModifiedUtf8().c_str()));
4262     CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
4263 
4264     std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
4265                                                decoded_name->ToModifiedUtf8().c_str()));
4266     CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
4267 
4268     CHECK_EQ(klass.Get()->GetInterfaces(),
4269              soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
4270     CHECK_EQ(klass.Get()->GetThrows(),
4271              soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
4272   }
4273   return klass.Get();
4274 }
4275 
GetDescriptorForProxy(mirror::Class * proxy_class)4276 std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
4277   DCHECK(proxy_class->IsProxyClass());
4278   mirror::String* name = proxy_class->GetName();
4279   DCHECK(name != nullptr);
4280   return DotToDescriptor(name->ToModifiedUtf8().c_str());
4281 }
4282 
FindMethodForProxy(mirror::Class * proxy_class,ArtMethod * proxy_method)4283 ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class, ArtMethod* proxy_method) {
4284   DCHECK(proxy_class->IsProxyClass());
4285   DCHECK(proxy_method->IsProxyMethod());
4286   {
4287     Thread* const self = Thread::Current();
4288     ReaderMutexLock mu(self, dex_lock_);
4289     // Locate the dex cache of the original interface/Object
4290     for (const DexCacheData& data : dex_caches_) {
4291       if (!self->IsJWeakCleared(data.weak_root) &&
4292           proxy_method->HasSameDexCacheResolvedTypes(data.resolved_types,
4293                                                      image_pointer_size_)) {
4294         mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(
4295             self->DecodeJObject(data.weak_root));
4296         if (dex_cache != nullptr) {
4297           ArtMethod* resolved_method = dex_cache->GetResolvedMethod(
4298               proxy_method->GetDexMethodIndex(), image_pointer_size_);
4299           CHECK(resolved_method != nullptr);
4300           return resolved_method;
4301         }
4302       }
4303     }
4304   }
4305   LOG(FATAL) << "Didn't find dex cache for " << PrettyClass(proxy_class) << " "
4306       << PrettyMethod(proxy_method);
4307   UNREACHABLE();
4308 }
4309 
CreateProxyConstructor(Handle<mirror::Class> klass,ArtMethod * out)4310 void ClassLinker::CreateProxyConstructor(Handle<mirror::Class> klass, ArtMethod* out) {
4311   // Create constructor for Proxy that must initialize the method.
4312   CHECK_EQ(GetClassRoot(kJavaLangReflectProxy)->NumDirectMethods(), 18u);
4313   ArtMethod* proxy_constructor = GetClassRoot(kJavaLangReflectProxy)->GetDirectMethodUnchecked(
4314       2, image_pointer_size_);
4315   DCHECK_EQ(std::string(proxy_constructor->GetName()), "<init>");
4316   // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
4317   // constructor method.
4318   GetClassRoot(kJavaLangReflectProxy)->GetDexCache()->SetResolvedMethod(
4319       proxy_constructor->GetDexMethodIndex(), proxy_constructor, image_pointer_size_);
4320   // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4321   // code_ too)
4322   DCHECK(out != nullptr);
4323   out->CopyFrom(proxy_constructor, image_pointer_size_);
4324   // Make this constructor public and fix the class to be our Proxy version
4325   out->SetAccessFlags((out->GetAccessFlags() & ~kAccProtected) | kAccPublic);
4326   out->SetDeclaringClass(klass.Get());
4327 }
4328 
CheckProxyConstructor(ArtMethod * constructor) const4329 void ClassLinker::CheckProxyConstructor(ArtMethod* constructor) const {
4330   CHECK(constructor->IsConstructor());
4331   auto* np = constructor->GetInterfaceMethodIfProxy(image_pointer_size_);
4332   CHECK_STREQ(np->GetName(), "<init>");
4333   CHECK_STREQ(np->GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
4334   DCHECK(constructor->IsPublic());
4335 }
4336 
CreateProxyMethod(Handle<mirror::Class> klass,ArtMethod * prototype,ArtMethod * out)4337 void ClassLinker::CreateProxyMethod(Handle<mirror::Class> klass, ArtMethod* prototype,
4338                                     ArtMethod* out) {
4339   // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4340   // prototype method
4341   auto* dex_cache = prototype->GetDeclaringClass()->GetDexCache();
4342   // Avoid dirtying the dex cache unless we need to.
4343   if (dex_cache->GetResolvedMethod(prototype->GetDexMethodIndex(), image_pointer_size_) !=
4344       prototype) {
4345     dex_cache->SetResolvedMethod(
4346         prototype->GetDexMethodIndex(), prototype, image_pointer_size_);
4347   }
4348   // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
4349   // as necessary
4350   DCHECK(out != nullptr);
4351   out->CopyFrom(prototype, image_pointer_size_);
4352 
4353   // Set class to be the concrete proxy class.
4354   out->SetDeclaringClass(klass.Get());
4355   // Clear the abstract, default and conflict flags to ensure that defaults aren't picked in
4356   // preference to the invocation handler.
4357   const uint32_t kRemoveFlags = kAccAbstract | kAccDefault | kAccDefaultConflict;
4358   // Make the method final.
4359   const uint32_t kAddFlags = kAccFinal;
4360   out->SetAccessFlags((out->GetAccessFlags() & ~kRemoveFlags) | kAddFlags);
4361 
4362   // Clear the dex_code_item_offset_. It needs to be 0 since proxy methods have no CodeItems but the
4363   // method they copy might (if it's a default method).
4364   out->SetCodeItemOffset(0);
4365 
4366   // At runtime the method looks like a reference and argument saving method, clone the code
4367   // related parameters from this method.
4368   out->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4369 }
4370 
CheckProxyMethod(ArtMethod * method,ArtMethod * prototype) const4371 void ClassLinker::CheckProxyMethod(ArtMethod* method, ArtMethod* prototype) const {
4372   // Basic sanity
4373   CHECK(!prototype->IsFinal());
4374   CHECK(method->IsFinal());
4375   CHECK(method->IsInvokable());
4376 
4377   // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4378   // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4379   CHECK(prototype->HasSameDexCacheResolvedMethods(method, image_pointer_size_));
4380   CHECK(prototype->HasSameDexCacheResolvedTypes(method, image_pointer_size_));
4381   auto* np = method->GetInterfaceMethodIfProxy(image_pointer_size_);
4382   CHECK_EQ(prototype->GetDeclaringClass()->GetDexCache(), np->GetDexCache());
4383   CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4384 
4385   CHECK_STREQ(np->GetName(), prototype->GetName());
4386   CHECK_STREQ(np->GetShorty(), prototype->GetShorty());
4387   // More complex sanity - via dex cache
4388   CHECK_EQ(np->GetReturnType(true /* resolve */, image_pointer_size_),
4389            prototype->GetReturnType(true /* resolve */, image_pointer_size_));
4390 }
4391 
CanWeInitializeClass(mirror::Class * klass,bool can_init_statics,bool can_init_parents)4392 bool ClassLinker::CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4393                                        bool can_init_parents) {
4394   if (can_init_statics && can_init_parents) {
4395     return true;
4396   }
4397   if (!can_init_statics) {
4398     // Check if there's a class initializer.
4399     ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4400     if (clinit != nullptr) {
4401       return false;
4402     }
4403     // Check if there are encoded static values needing initialization.
4404     if (klass->NumStaticFields() != 0) {
4405       const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
4406       DCHECK(dex_class_def != nullptr);
4407       if (dex_class_def->static_values_off_ != 0) {
4408         return false;
4409       }
4410     }
4411     // If we are a class we need to initialize all interfaces with default methods when we are
4412     // initialized. Check all of them.
4413     if (!klass->IsInterface()) {
4414       size_t num_interfaces = klass->GetIfTableCount();
4415       for (size_t i = 0; i < num_interfaces; i++) {
4416         mirror::Class* iface = klass->GetIfTable()->GetInterface(i);
4417         if (iface->HasDefaultMethods() &&
4418             !CanWeInitializeClass(iface, can_init_statics, can_init_parents)) {
4419           return false;
4420         }
4421       }
4422     }
4423   }
4424   if (klass->IsInterface() || !klass->HasSuperClass()) {
4425     return true;
4426   }
4427   mirror::Class* super_class = klass->GetSuperClass();
4428   if (!can_init_parents && !super_class->IsInitialized()) {
4429     return false;
4430   }
4431   return CanWeInitializeClass(super_class, can_init_statics, can_init_parents);
4432 }
4433 
InitializeClass(Thread * self,Handle<mirror::Class> klass,bool can_init_statics,bool can_init_parents)4434 bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4435                                   bool can_init_statics, bool can_init_parents) {
4436   // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4437 
4438   // Are we already initialized and therefore done?
4439   // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4440   // an initialized class will never change its state.
4441   if (klass->IsInitialized()) {
4442     return true;
4443   }
4444 
4445   // Fast fail if initialization requires a full runtime. Not part of the JLS.
4446   if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
4447     return false;
4448   }
4449 
4450   self->AllowThreadSuspension();
4451   uint64_t t0;
4452   {
4453     ObjectLock<mirror::Class> lock(self, klass);
4454 
4455     // Re-check under the lock in case another thread initialized ahead of us.
4456     if (klass->IsInitialized()) {
4457       return true;
4458     }
4459 
4460     // Was the class already found to be erroneous? Done under the lock to match the JLS.
4461     if (klass->IsErroneous()) {
4462       ThrowEarlierClassFailure(klass.Get(), true);
4463       VlogClassInitializationFailure(klass);
4464       return false;
4465     }
4466 
4467     CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
4468 
4469     if (!klass->IsVerified()) {
4470       VerifyClass(self, klass);
4471       if (!klass->IsVerified()) {
4472         // We failed to verify, expect either the klass to be erroneous or verification failed at
4473         // compile time.
4474         if (klass->IsErroneous()) {
4475           // The class is erroneous. This may be a verifier error, or another thread attempted
4476           // verification and/or initialization and failed. We can distinguish those cases by
4477           // whether an exception is already pending.
4478           if (self->IsExceptionPending()) {
4479             // Check that it's a VerifyError.
4480             DCHECK_EQ("java.lang.Class<java.lang.VerifyError>",
4481                       PrettyClass(self->GetException()->GetClass()));
4482           } else {
4483             // Check that another thread attempted initialization.
4484             DCHECK_NE(0, klass->GetClinitThreadId());
4485             DCHECK_NE(self->GetTid(), klass->GetClinitThreadId());
4486             // Need to rethrow the previous failure now.
4487             ThrowEarlierClassFailure(klass.Get(), true);
4488           }
4489           VlogClassInitializationFailure(klass);
4490         } else {
4491           CHECK(Runtime::Current()->IsAotCompiler());
4492           CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
4493         }
4494         return false;
4495       } else {
4496         self->AssertNoPendingException();
4497       }
4498 
4499       // A separate thread could have moved us all the way to initialized. A "simple" example
4500       // involves a subclass of the current class being initialized at the same time (which
4501       // will implicitly initialize the superclass, if scheduled that way). b/28254258
4502       DCHECK_NE(mirror::Class::kStatusError, klass->GetStatus());
4503       if (klass->IsInitialized()) {
4504         return true;
4505       }
4506     }
4507 
4508     // If the class is kStatusInitializing, either this thread is
4509     // initializing higher up the stack or another thread has beat us
4510     // to initializing and we need to wait. Either way, this
4511     // invocation of InitializeClass will not be responsible for
4512     // running <clinit> and will return.
4513     if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
4514       // Could have got an exception during verification.
4515       if (self->IsExceptionPending()) {
4516         VlogClassInitializationFailure(klass);
4517         return false;
4518       }
4519       // We caught somebody else in the act; was it us?
4520       if (klass->GetClinitThreadId() == self->GetTid()) {
4521         // Yes. That's fine. Return so we can continue initializing.
4522         return true;
4523       }
4524       // No. That's fine. Wait for another thread to finish initializing.
4525       return WaitForInitializeClass(klass, self, lock);
4526     }
4527 
4528     if (!ValidateSuperClassDescriptors(klass)) {
4529       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4530       return false;
4531     }
4532     self->AllowThreadSuspension();
4533 
4534     CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get())
4535         << " self.tid=" << self->GetTid() << " clinit.tid=" << klass->GetClinitThreadId();
4536 
4537     // From here out other threads may observe that we're initializing and so changes of state
4538     // require the a notification.
4539     klass->SetClinitThreadId(self->GetTid());
4540     mirror::Class::SetStatus(klass, mirror::Class::kStatusInitializing, self);
4541 
4542     t0 = NanoTime();
4543   }
4544 
4545   // Initialize super classes, must be done while initializing for the JLS.
4546   if (!klass->IsInterface() && klass->HasSuperClass()) {
4547     mirror::Class* super_class = klass->GetSuperClass();
4548     if (!super_class->IsInitialized()) {
4549       CHECK(!super_class->IsInterface());
4550       CHECK(can_init_parents);
4551       StackHandleScope<1> hs(self);
4552       Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
4553       bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
4554       if (!super_initialized) {
4555         // The super class was verified ahead of entering initializing, we should only be here if
4556         // the super class became erroneous due to initialization.
4557         CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
4558             << "Super class initialization failed for "
4559             << PrettyDescriptor(handle_scope_super.Get())
4560             << " that has unexpected status " << handle_scope_super->GetStatus()
4561             << "\nPending exception:\n"
4562             << (self->GetException() != nullptr ? self->GetException()->Dump() : "");
4563         ObjectLock<mirror::Class> lock(self, klass);
4564         // Initialization failed because the super-class is erroneous.
4565         mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4566         return false;
4567       }
4568     }
4569   }
4570 
4571   if (!klass->IsInterface()) {
4572     // Initialize interfaces with default methods for the JLS.
4573     size_t num_direct_interfaces = klass->NumDirectInterfaces();
4574     // Only setup the (expensive) handle scope if we actually need to.
4575     if (UNLIKELY(num_direct_interfaces > 0)) {
4576       StackHandleScope<1> hs_iface(self);
4577       MutableHandle<mirror::Class> handle_scope_iface(hs_iface.NewHandle<mirror::Class>(nullptr));
4578       for (size_t i = 0; i < num_direct_interfaces; i++) {
4579         handle_scope_iface.Assign(mirror::Class::GetDirectInterface(self, klass, i));
4580         CHECK(handle_scope_iface.Get() != nullptr);
4581         CHECK(handle_scope_iface->IsInterface());
4582         if (handle_scope_iface->HasBeenRecursivelyInitialized()) {
4583           // We have already done this for this interface. Skip it.
4584           continue;
4585         }
4586         // We cannot just call initialize class directly because we need to ensure that ALL
4587         // interfaces with default methods are initialized. Non-default interface initialization
4588         // will not affect other non-default super-interfaces.
4589         bool iface_initialized = InitializeDefaultInterfaceRecursive(self,
4590                                                                      handle_scope_iface,
4591                                                                      can_init_statics,
4592                                                                      can_init_parents);
4593         if (!iface_initialized) {
4594           ObjectLock<mirror::Class> lock(self, klass);
4595           // Initialization failed because one of our interfaces with default methods is erroneous.
4596           mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4597           return false;
4598         }
4599       }
4600     }
4601   }
4602 
4603   const size_t num_static_fields = klass->NumStaticFields();
4604   if (num_static_fields > 0) {
4605     const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
4606     CHECK(dex_class_def != nullptr);
4607     const DexFile& dex_file = klass->GetDexFile();
4608     StackHandleScope<3> hs(self);
4609     Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
4610     Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4611 
4612     // Eagerly fill in static fields so that the we don't have to do as many expensive
4613     // Class::FindStaticField in ResolveField.
4614     for (size_t i = 0; i < num_static_fields; ++i) {
4615       ArtField* field = klass->GetStaticField(i);
4616       const uint32_t field_idx = field->GetDexFieldIndex();
4617       ArtField* resolved_field = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
4618       if (resolved_field == nullptr) {
4619         dex_cache->SetResolvedField(field_idx, field, image_pointer_size_);
4620       } else {
4621         DCHECK_EQ(field, resolved_field);
4622       }
4623     }
4624 
4625     EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4626                                              this, *dex_class_def);
4627     const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
4628     ClassDataItemIterator field_it(dex_file, class_data);
4629     if (value_it.HasNext()) {
4630       DCHECK(field_it.HasNextStaticField());
4631       CHECK(can_init_statics);
4632       for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
4633         ArtField* field = ResolveField(
4634             dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true);
4635         if (Runtime::Current()->IsActiveTransaction()) {
4636           value_it.ReadValueToField<true>(field);
4637         } else {
4638           value_it.ReadValueToField<false>(field);
4639         }
4640         DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
4641       }
4642     }
4643   }
4644 
4645   ArtMethod* clinit = klass->FindClassInitializer(image_pointer_size_);
4646   if (clinit != nullptr) {
4647     CHECK(can_init_statics);
4648     JValue result;
4649     clinit->Invoke(self, nullptr, 0, &result, "V");
4650   }
4651 
4652   self->AllowThreadSuspension();
4653   uint64_t t1 = NanoTime();
4654 
4655   bool success = true;
4656   {
4657     ObjectLock<mirror::Class> lock(self, klass);
4658 
4659     if (self->IsExceptionPending()) {
4660       WrapExceptionInInitializer(klass);
4661       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4662       success = false;
4663     } else if (Runtime::Current()->IsTransactionAborted()) {
4664       // The exception thrown when the transaction aborted has been caught and cleared
4665       // so we need to throw it again now.
4666       VLOG(compiler) << "Return from class initializer of " << PrettyDescriptor(klass.Get())
4667                      << " without exception while transaction was aborted: re-throw it now.";
4668       Runtime::Current()->ThrowTransactionAbortError(self);
4669       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4670       success = false;
4671     } else {
4672       RuntimeStats* global_stats = Runtime::Current()->GetStats();
4673       RuntimeStats* thread_stats = self->GetStats();
4674       ++global_stats->class_init_count;
4675       ++thread_stats->class_init_count;
4676       global_stats->class_init_time_ns += (t1 - t0);
4677       thread_stats->class_init_time_ns += (t1 - t0);
4678       // Set the class as initialized except if failed to initialize static fields.
4679       mirror::Class::SetStatus(klass, mirror::Class::kStatusInitialized, self);
4680       if (VLOG_IS_ON(class_linker)) {
4681         std::string temp;
4682         LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
4683             klass->GetLocation();
4684       }
4685       // Opportunistically set static method trampolines to their destination.
4686       FixupStaticTrampolines(klass.Get());
4687     }
4688   }
4689   return success;
4690 }
4691 
4692 // We recursively run down the tree of interfaces. We need to do this in the order they are declared
4693 // and perform the initialization only on those interfaces that contain default methods.
InitializeDefaultInterfaceRecursive(Thread * self,Handle<mirror::Class> iface,bool can_init_statics,bool can_init_parents)4694 bool ClassLinker::InitializeDefaultInterfaceRecursive(Thread* self,
4695                                                       Handle<mirror::Class> iface,
4696                                                       bool can_init_statics,
4697                                                       bool can_init_parents) {
4698   CHECK(iface->IsInterface());
4699   size_t num_direct_ifaces = iface->NumDirectInterfaces();
4700   // Only create the (expensive) handle scope if we need it.
4701   if (UNLIKELY(num_direct_ifaces > 0)) {
4702     StackHandleScope<1> hs(self);
4703     MutableHandle<mirror::Class> handle_super_iface(hs.NewHandle<mirror::Class>(nullptr));
4704     // First we initialize all of iface's super-interfaces recursively.
4705     for (size_t i = 0; i < num_direct_ifaces; i++) {
4706       mirror::Class* super_iface = mirror::Class::GetDirectInterface(self, iface, i);
4707       if (!super_iface->HasBeenRecursivelyInitialized()) {
4708         // Recursive step
4709         handle_super_iface.Assign(super_iface);
4710         if (!InitializeDefaultInterfaceRecursive(self,
4711                                                  handle_super_iface,
4712                                                  can_init_statics,
4713                                                  can_init_parents)) {
4714           return false;
4715         }
4716       }
4717     }
4718   }
4719 
4720   bool result = true;
4721   // Then we initialize 'iface' if it has default methods. We do not need to (and in fact must not)
4722   // initialize if we don't have default methods.
4723   if (iface->HasDefaultMethods()) {
4724     result = EnsureInitialized(self, iface, can_init_statics, can_init_parents);
4725   }
4726 
4727   // Mark that this interface has undergone recursive default interface initialization so we know we
4728   // can skip it on any later class initializations. We do this even if we are not a default
4729   // interface since we can still avoid the traversal. This is purely a performance optimization.
4730   if (result) {
4731     // TODO This should be done in a better way
4732     ObjectLock<mirror::Class> lock(self, iface);
4733     iface->SetRecursivelyInitialized();
4734   }
4735   return result;
4736 }
4737 
WaitForInitializeClass(Handle<mirror::Class> klass,Thread * self,ObjectLock<mirror::Class> & lock)4738 bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass,
4739                                          Thread* self,
4740                                          ObjectLock<mirror::Class>& lock)
4741     SHARED_REQUIRES(Locks::mutator_lock_) {
4742   while (true) {
4743     self->AssertNoPendingException();
4744     CHECK(!klass->IsInitialized());
4745     lock.WaitIgnoringInterrupts();
4746 
4747     // When we wake up, repeat the test for init-in-progress.  If
4748     // there's an exception pending (only possible if
4749     // we were not using WaitIgnoringInterrupts), bail out.
4750     if (self->IsExceptionPending()) {
4751       WrapExceptionInInitializer(klass);
4752       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
4753       return false;
4754     }
4755     // Spurious wakeup? Go back to waiting.
4756     if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
4757       continue;
4758     }
4759     if (klass->GetStatus() == mirror::Class::kStatusVerified &&
4760         Runtime::Current()->IsAotCompiler()) {
4761       // Compile time initialization failed.
4762       return false;
4763     }
4764     if (klass->IsErroneous()) {
4765       // The caller wants an exception, but it was thrown in a
4766       // different thread.  Synthesize one here.
4767       ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
4768                                 PrettyDescriptor(klass.Get()).c_str());
4769       VlogClassInitializationFailure(klass);
4770       return false;
4771     }
4772     if (klass->IsInitialized()) {
4773       return true;
4774     }
4775     LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
4776         << klass->GetStatus();
4777   }
4778   UNREACHABLE();
4779 }
4780 
ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,Handle<mirror::Class> super_klass,ArtMethod * method,ArtMethod * m)4781 static void ThrowSignatureCheckResolveReturnTypeException(Handle<mirror::Class> klass,
4782                                                           Handle<mirror::Class> super_klass,
4783                                                           ArtMethod* method,
4784                                                           ArtMethod* m)
4785     SHARED_REQUIRES(Locks::mutator_lock_) {
4786   DCHECK(Thread::Current()->IsExceptionPending());
4787   DCHECK(!m->IsProxyMethod());
4788   const DexFile* dex_file = m->GetDexFile();
4789   const DexFile::MethodId& method_id = dex_file->GetMethodId(m->GetDexMethodIndex());
4790   const DexFile::ProtoId& proto_id = dex_file->GetMethodPrototype(method_id);
4791   uint16_t return_type_idx = proto_id.return_type_idx_;
4792   std::string return_type = PrettyType(return_type_idx, *dex_file);
4793   std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
4794   ThrowWrappedLinkageError(klass.Get(),
4795                            "While checking class %s method %s signature against %s %s: "
4796                            "Failed to resolve return type %s with %s",
4797                            PrettyDescriptor(klass.Get()).c_str(),
4798                            PrettyMethod(method).c_str(),
4799                            super_klass->IsInterface() ? "interface" : "superclass",
4800                            PrettyDescriptor(super_klass.Get()).c_str(),
4801                            return_type.c_str(), class_loader.c_str());
4802 }
4803 
ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,Handle<mirror::Class> super_klass,ArtMethod * method,ArtMethod * m,uint32_t index,uint32_t arg_type_idx)4804 static void ThrowSignatureCheckResolveArgException(Handle<mirror::Class> klass,
4805                                                    Handle<mirror::Class> super_klass,
4806                                                    ArtMethod* method,
4807                                                    ArtMethod* m,
4808                                                    uint32_t index,
4809                                                    uint32_t arg_type_idx)
4810     SHARED_REQUIRES(Locks::mutator_lock_) {
4811   DCHECK(Thread::Current()->IsExceptionPending());
4812   DCHECK(!m->IsProxyMethod());
4813   const DexFile* dex_file = m->GetDexFile();
4814   std::string arg_type = PrettyType(arg_type_idx, *dex_file);
4815   std::string class_loader = PrettyTypeOf(m->GetDeclaringClass()->GetClassLoader());
4816   ThrowWrappedLinkageError(klass.Get(),
4817                            "While checking class %s method %s signature against %s %s: "
4818                            "Failed to resolve arg %u type %s with %s",
4819                            PrettyDescriptor(klass.Get()).c_str(),
4820                            PrettyMethod(method).c_str(),
4821                            super_klass->IsInterface() ? "interface" : "superclass",
4822                            PrettyDescriptor(super_klass.Get()).c_str(),
4823                            index, arg_type.c_str(), class_loader.c_str());
4824 }
4825 
ThrowSignatureMismatch(Handle<mirror::Class> klass,Handle<mirror::Class> super_klass,ArtMethod * method,const std::string & error_msg)4826 static void ThrowSignatureMismatch(Handle<mirror::Class> klass,
4827                                    Handle<mirror::Class> super_klass,
4828                                    ArtMethod* method,
4829                                    const std::string& error_msg)
4830     SHARED_REQUIRES(Locks::mutator_lock_) {
4831   ThrowLinkageError(klass.Get(),
4832                     "Class %s method %s resolves differently in %s %s: %s",
4833                     PrettyDescriptor(klass.Get()).c_str(),
4834                     PrettyMethod(method).c_str(),
4835                     super_klass->IsInterface() ? "interface" : "superclass",
4836                     PrettyDescriptor(super_klass.Get()).c_str(),
4837                     error_msg.c_str());
4838 }
4839 
HasSameSignatureWithDifferentClassLoaders(Thread * self,size_t pointer_size,Handle<mirror::Class> klass,Handle<mirror::Class> super_klass,ArtMethod * method1,ArtMethod * method2)4840 static bool HasSameSignatureWithDifferentClassLoaders(Thread* self,
4841                                                       size_t pointer_size,
4842                                                       Handle<mirror::Class> klass,
4843                                                       Handle<mirror::Class> super_klass,
4844                                                       ArtMethod* method1,
4845                                                       ArtMethod* method2)
4846     SHARED_REQUIRES(Locks::mutator_lock_) {
4847   {
4848     StackHandleScope<1> hs(self);
4849     Handle<mirror::Class> return_type(hs.NewHandle(method1->GetReturnType(true /* resolve */,
4850                                                                           pointer_size)));
4851     if (UNLIKELY(return_type.Get() == nullptr)) {
4852       ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method1);
4853       return false;
4854     }
4855     mirror::Class* other_return_type = method2->GetReturnType(true /* resolve */,
4856                                                               pointer_size);
4857     if (UNLIKELY(other_return_type == nullptr)) {
4858       ThrowSignatureCheckResolveReturnTypeException(klass, super_klass, method1, method2);
4859       return false;
4860     }
4861     if (UNLIKELY(other_return_type != return_type.Get())) {
4862       ThrowSignatureMismatch(klass, super_klass, method1,
4863                              StringPrintf("Return types mismatch: %s(%p) vs %s(%p)",
4864                                           PrettyClassAndClassLoader(return_type.Get()).c_str(),
4865                                           return_type.Get(),
4866                                           PrettyClassAndClassLoader(other_return_type).c_str(),
4867                                           other_return_type));
4868       return false;
4869     }
4870   }
4871   const DexFile::TypeList* types1 = method1->GetParameterTypeList();
4872   const DexFile::TypeList* types2 = method2->GetParameterTypeList();
4873   if (types1 == nullptr) {
4874     if (types2 != nullptr && types2->Size() != 0) {
4875       ThrowSignatureMismatch(klass, super_klass, method1,
4876                              StringPrintf("Type list mismatch with %s",
4877                                           PrettyMethod(method2, true).c_str()));
4878       return false;
4879     }
4880     return true;
4881   } else if (UNLIKELY(types2 == nullptr)) {
4882     if (types1->Size() != 0) {
4883       ThrowSignatureMismatch(klass, super_klass, method1,
4884                              StringPrintf("Type list mismatch with %s",
4885                                           PrettyMethod(method2, true).c_str()));
4886       return false;
4887     }
4888     return true;
4889   }
4890   uint32_t num_types = types1->Size();
4891   if (UNLIKELY(num_types != types2->Size())) {
4892     ThrowSignatureMismatch(klass, super_klass, method1,
4893                            StringPrintf("Type list mismatch with %s",
4894                                         PrettyMethod(method2, true).c_str()));
4895     return false;
4896   }
4897   for (uint32_t i = 0; i < num_types; ++i) {
4898     StackHandleScope<1> hs(self);
4899     uint32_t param_type_idx = types1->GetTypeItem(i).type_idx_;
4900     Handle<mirror::Class> param_type(hs.NewHandle(
4901         method1->GetClassFromTypeIndex(param_type_idx, true /* resolve */, pointer_size)));
4902     if (UNLIKELY(param_type.Get() == nullptr)) {
4903       ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
4904                                              method1, i, param_type_idx);
4905       return false;
4906     }
4907     uint32_t other_param_type_idx = types2->GetTypeItem(i).type_idx_;
4908     mirror::Class* other_param_type =
4909         method2->GetClassFromTypeIndex(other_param_type_idx, true /* resolve */, pointer_size);
4910     if (UNLIKELY(other_param_type == nullptr)) {
4911       ThrowSignatureCheckResolveArgException(klass, super_klass, method1,
4912                                              method2, i, other_param_type_idx);
4913       return false;
4914     }
4915     if (UNLIKELY(param_type.Get() != other_param_type)) {
4916       ThrowSignatureMismatch(klass, super_klass, method1,
4917                              StringPrintf("Parameter %u type mismatch: %s(%p) vs %s(%p)",
4918                                           i,
4919                                           PrettyClassAndClassLoader(param_type.Get()).c_str(),
4920                                           param_type.Get(),
4921                                           PrettyClassAndClassLoader(other_param_type).c_str(),
4922                                           other_param_type));
4923       return false;
4924     }
4925   }
4926   return true;
4927 }
4928 
4929 
ValidateSuperClassDescriptors(Handle<mirror::Class> klass)4930 bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
4931   if (klass->IsInterface()) {
4932     return true;
4933   }
4934   // Begin with the methods local to the superclass.
4935   Thread* self = Thread::Current();
4936   StackHandleScope<1> hs(self);
4937   MutableHandle<mirror::Class> super_klass(hs.NewHandle<mirror::Class>(nullptr));
4938   if (klass->HasSuperClass() &&
4939       klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
4940     super_klass.Assign(klass->GetSuperClass());
4941     for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4942       auto* m = klass->GetVTableEntry(i, image_pointer_size_);
4943       auto* super_m = klass->GetSuperClass()->GetVTableEntry(i, image_pointer_size_);
4944       if (m != super_m) {
4945         if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
4946                                                                 klass, super_klass,
4947                                                                 m, super_m))) {
4948           self->AssertPendingException();
4949           return false;
4950         }
4951       }
4952     }
4953   }
4954   for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
4955     super_klass.Assign(klass->GetIfTable()->GetInterface(i));
4956     if (klass->GetClassLoader() != super_klass->GetClassLoader()) {
4957       uint32_t num_methods = super_klass->NumVirtualMethods();
4958       for (uint32_t j = 0; j < num_methods; ++j) {
4959         auto* m = klass->GetIfTable()->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
4960             j, image_pointer_size_);
4961         auto* super_m = super_klass->GetVirtualMethod(j, image_pointer_size_);
4962         if (m != super_m) {
4963           if (UNLIKELY(!HasSameSignatureWithDifferentClassLoaders(self, image_pointer_size_,
4964                                                                   klass, super_klass,
4965                                                                   m, super_m))) {
4966             self->AssertPendingException();
4967             return false;
4968           }
4969         }
4970       }
4971     }
4972   }
4973   return true;
4974 }
4975 
EnsureInitialized(Thread * self,Handle<mirror::Class> c,bool can_init_fields,bool can_init_parents)4976 bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4977                                     bool can_init_parents) {
4978   DCHECK(c.Get() != nullptr);
4979   if (c->IsInitialized()) {
4980     EnsureSkipAccessChecksMethods(c);
4981     return true;
4982   }
4983   const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
4984   if (!success) {
4985     if (can_init_fields && can_init_parents) {
4986       CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4987     }
4988   } else {
4989     self->AssertNoPendingException();
4990   }
4991   return success;
4992 }
4993 
FixupTemporaryDeclaringClass(mirror::Class * temp_class,mirror::Class * new_class)4994 void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class,
4995                                                mirror::Class* new_class) {
4996   DCHECK_EQ(temp_class->NumInstanceFields(), 0u);
4997   for (ArtField& field : new_class->GetIFields()) {
4998     if (field.GetDeclaringClass() == temp_class) {
4999       field.SetDeclaringClass(new_class);
5000     }
5001   }
5002 
5003   DCHECK_EQ(temp_class->NumStaticFields(), 0u);
5004   for (ArtField& field : new_class->GetSFields()) {
5005     if (field.GetDeclaringClass() == temp_class) {
5006       field.SetDeclaringClass(new_class);
5007     }
5008   }
5009 
5010   DCHECK_EQ(temp_class->NumDirectMethods(), 0u);
5011   DCHECK_EQ(temp_class->NumVirtualMethods(), 0u);
5012   for (auto& method : new_class->GetMethods(image_pointer_size_)) {
5013     if (method.GetDeclaringClass() == temp_class) {
5014       method.SetDeclaringClass(new_class);
5015     }
5016   }
5017 
5018   // Make sure the remembered set and mod-union tables know that we updated some of the native
5019   // roots.
5020   Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(new_class);
5021 }
5022 
RegisterClassLoader(mirror::ClassLoader * class_loader)5023 void ClassLinker::RegisterClassLoader(mirror::ClassLoader* class_loader) {
5024   CHECK(class_loader->GetAllocator() == nullptr);
5025   CHECK(class_loader->GetClassTable() == nullptr);
5026   Thread* const self = Thread::Current();
5027   ClassLoaderData data;
5028   data.weak_root = self->GetJniEnv()->vm->AddWeakGlobalRef(self, class_loader);
5029   // Create and set the class table.
5030   data.class_table = new ClassTable;
5031   class_loader->SetClassTable(data.class_table);
5032   // Create and set the linear allocator.
5033   data.allocator = Runtime::Current()->CreateLinearAlloc();
5034   class_loader->SetAllocator(data.allocator);
5035   // Add to the list so that we know to free the data later.
5036   class_loaders_.push_back(data);
5037 }
5038 
InsertClassTableForClassLoader(mirror::ClassLoader * class_loader)5039 ClassTable* ClassLinker::InsertClassTableForClassLoader(mirror::ClassLoader* class_loader) {
5040   if (class_loader == nullptr) {
5041     return &boot_class_table_;
5042   }
5043   ClassTable* class_table = class_loader->GetClassTable();
5044   if (class_table == nullptr) {
5045     RegisterClassLoader(class_loader);
5046     class_table = class_loader->GetClassTable();
5047     DCHECK(class_table != nullptr);
5048   }
5049   return class_table;
5050 }
5051 
ClassTableForClassLoader(mirror::ClassLoader * class_loader)5052 ClassTable* ClassLinker::ClassTableForClassLoader(mirror::ClassLoader* class_loader) {
5053   return class_loader == nullptr ? &boot_class_table_ : class_loader->GetClassTable();
5054 }
5055 
LinkClass(Thread * self,const char * descriptor,Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces,MutableHandle<mirror::Class> * h_new_class_out)5056 bool ClassLinker::LinkClass(Thread* self,
5057                             const char* descriptor,
5058                             Handle<mirror::Class> klass,
5059                             Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5060                             MutableHandle<mirror::Class>* h_new_class_out) {
5061   CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
5062 
5063   if (!LinkSuperClass(klass)) {
5064     return false;
5065   }
5066   ArtMethod* imt[mirror::Class::kImtSize];
5067   std::fill_n(imt, arraysize(imt), Runtime::Current()->GetImtUnimplementedMethod());
5068   if (!LinkMethods(self, klass, interfaces, imt)) {
5069     return false;
5070   }
5071   if (!LinkInstanceFields(self, klass)) {
5072     return false;
5073   }
5074   size_t class_size;
5075   if (!LinkStaticFields(self, klass, &class_size)) {
5076     return false;
5077   }
5078   CreateReferenceInstanceOffsets(klass);
5079   CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
5080 
5081   if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
5082     // We don't need to retire this class as it has no embedded tables or it was created the
5083     // correct size during class linker initialization.
5084     CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
5085 
5086     if (klass->ShouldHaveEmbeddedImtAndVTable()) {
5087       klass->PopulateEmbeddedImtAndVTable(imt, image_pointer_size_);
5088     }
5089 
5090     // This will notify waiters on klass that saw the not yet resolved
5091     // class in the class_table_ during EnsureResolved.
5092     mirror::Class::SetStatus(klass, mirror::Class::kStatusResolved, self);
5093     h_new_class_out->Assign(klass.Get());
5094   } else {
5095     CHECK(!klass->IsResolved());
5096     // Retire the temporary class and create the correctly sized resolved class.
5097     StackHandleScope<1> hs(self);
5098     auto h_new_class = hs.NewHandle(klass->CopyOf(self, class_size, imt, image_pointer_size_));
5099     // Set arrays to null since we don't want to have multiple classes with the same ArtField or
5100     // ArtMethod array pointers. If this occurs, it causes bugs in remembered sets since the GC
5101     // may not see any references to the target space and clean the card for a class if another
5102     // class had the same array pointer.
5103     klass->SetMethodsPtrUnchecked(nullptr, 0, 0);
5104     klass->SetSFieldsPtrUnchecked(nullptr);
5105     klass->SetIFieldsPtrUnchecked(nullptr);
5106     if (UNLIKELY(h_new_class.Get() == nullptr)) {
5107       self->AssertPendingOOMException();
5108       mirror::Class::SetStatus(klass, mirror::Class::kStatusError, self);
5109       return false;
5110     }
5111 
5112     CHECK_EQ(h_new_class->GetClassSize(), class_size);
5113     ObjectLock<mirror::Class> lock(self, h_new_class);
5114     FixupTemporaryDeclaringClass(klass.Get(), h_new_class.Get());
5115 
5116     {
5117       WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
5118       mirror::ClassLoader* const class_loader = h_new_class.Get()->GetClassLoader();
5119       ClassTable* const table = InsertClassTableForClassLoader(class_loader);
5120       mirror::Class* existing = table->UpdateClass(descriptor, h_new_class.Get(),
5121                                                    ComputeModifiedUtf8Hash(descriptor));
5122       if (class_loader != nullptr) {
5123         // We updated the class in the class table, perform the write barrier so that the GC knows
5124         // about the change.
5125         Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
5126       }
5127       CHECK_EQ(existing, klass.Get());
5128       if (kIsDebugBuild && class_loader == nullptr && dex_cache_boot_image_class_lookup_required_) {
5129         // Check a class loaded with the system class loader matches one in the image if the class
5130         // is in the image.
5131         mirror::Class* const image_class = LookupClassFromBootImage(descriptor);
5132         if (image_class != nullptr) {
5133           CHECK_EQ(klass.Get(), existing) << descriptor;
5134         }
5135       }
5136       if (log_new_class_table_roots_) {
5137         new_class_roots_.push_back(GcRoot<mirror::Class>(h_new_class.Get()));
5138       }
5139     }
5140 
5141     // This will notify waiters on temp class that saw the not yet resolved class in the
5142     // class_table_ during EnsureResolved.
5143     mirror::Class::SetStatus(klass, mirror::Class::kStatusRetired, self);
5144 
5145     CHECK_EQ(h_new_class->GetStatus(), mirror::Class::kStatusResolving);
5146     // This will notify waiters on new_class that saw the not yet resolved
5147     // class in the class_table_ during EnsureResolved.
5148     mirror::Class::SetStatus(h_new_class, mirror::Class::kStatusResolved, self);
5149     // Return the new class.
5150     h_new_class_out->Assign(h_new_class.Get());
5151   }
5152   return true;
5153 }
5154 
CountMethodsAndFields(ClassDataItemIterator & dex_data,size_t * virtual_methods,size_t * direct_methods,size_t * static_fields,size_t * instance_fields)5155 static void CountMethodsAndFields(ClassDataItemIterator& dex_data,
5156                                   size_t* virtual_methods,
5157                                   size_t* direct_methods,
5158                                   size_t* static_fields,
5159                                   size_t* instance_fields) {
5160   *virtual_methods = *direct_methods = *static_fields = *instance_fields = 0;
5161 
5162   while (dex_data.HasNextStaticField()) {
5163     dex_data.Next();
5164     (*static_fields)++;
5165   }
5166   while (dex_data.HasNextInstanceField()) {
5167     dex_data.Next();
5168     (*instance_fields)++;
5169   }
5170   while (dex_data.HasNextDirectMethod()) {
5171     (*direct_methods)++;
5172     dex_data.Next();
5173   }
5174   while (dex_data.HasNextVirtualMethod()) {
5175     (*virtual_methods)++;
5176     dex_data.Next();
5177   }
5178   DCHECK(!dex_data.HasNext());
5179 }
5180 
DumpClass(std::ostream & os,const DexFile & dex_file,const DexFile::ClassDef & dex_class_def,const char * suffix)5181 static void DumpClass(std::ostream& os,
5182                       const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
5183                       const char* suffix) {
5184   ClassDataItemIterator dex_data(dex_file, dex_file.GetClassData(dex_class_def));
5185   os << dex_file.GetClassDescriptor(dex_class_def) << suffix << ":\n";
5186   os << " Static fields:\n";
5187   while (dex_data.HasNextStaticField()) {
5188     const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5189     os << "  " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5190     dex_data.Next();
5191   }
5192   os << " Instance fields:\n";
5193   while (dex_data.HasNextInstanceField()) {
5194     const DexFile::FieldId& id = dex_file.GetFieldId(dex_data.GetMemberIndex());
5195     os << "  " << dex_file.GetFieldTypeDescriptor(id) << " " << dex_file.GetFieldName(id) << "\n";
5196     dex_data.Next();
5197   }
5198   os << " Direct methods:\n";
5199   while (dex_data.HasNextDirectMethod()) {
5200     const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5201     os << "  " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5202     dex_data.Next();
5203   }
5204   os << " Virtual methods:\n";
5205   while (dex_data.HasNextVirtualMethod()) {
5206     const DexFile::MethodId& id = dex_file.GetMethodId(dex_data.GetMemberIndex());
5207     os << "  " << dex_file.GetMethodName(id) << dex_file.GetMethodSignature(id).ToString() << "\n";
5208     dex_data.Next();
5209   }
5210 }
5211 
DumpClasses(const DexFile & dex_file1,const DexFile::ClassDef & dex_class_def1,const DexFile & dex_file2,const DexFile::ClassDef & dex_class_def2)5212 static std::string DumpClasses(const DexFile& dex_file1,
5213                                const DexFile::ClassDef& dex_class_def1,
5214                                const DexFile& dex_file2,
5215                                const DexFile::ClassDef& dex_class_def2) {
5216   std::ostringstream os;
5217   DumpClass(os, dex_file1, dex_class_def1, " (Compile time)");
5218   DumpClass(os, dex_file2, dex_class_def2, " (Runtime)");
5219   return os.str();
5220 }
5221 
5222 
5223 // Very simple structural check on whether the classes match. Only compares the number of
5224 // methods and fields.
SimpleStructuralCheck(const DexFile & dex_file1,const DexFile::ClassDef & dex_class_def1,const DexFile & dex_file2,const DexFile::ClassDef & dex_class_def2,std::string * error_msg)5225 static bool SimpleStructuralCheck(const DexFile& dex_file1,
5226                                   const DexFile::ClassDef& dex_class_def1,
5227                                   const DexFile& dex_file2,
5228                                   const DexFile::ClassDef& dex_class_def2,
5229                                   std::string* error_msg) {
5230   ClassDataItemIterator dex_data1(dex_file1, dex_file1.GetClassData(dex_class_def1));
5231   ClassDataItemIterator dex_data2(dex_file2, dex_file2.GetClassData(dex_class_def2));
5232 
5233   // Counters for current dex file.
5234   size_t dex_virtual_methods1, dex_direct_methods1, dex_static_fields1, dex_instance_fields1;
5235   CountMethodsAndFields(dex_data1,
5236                         &dex_virtual_methods1,
5237                         &dex_direct_methods1,
5238                         &dex_static_fields1,
5239                         &dex_instance_fields1);
5240   // Counters for compile-time dex file.
5241   size_t dex_virtual_methods2, dex_direct_methods2, dex_static_fields2, dex_instance_fields2;
5242   CountMethodsAndFields(dex_data2,
5243                         &dex_virtual_methods2,
5244                         &dex_direct_methods2,
5245                         &dex_static_fields2,
5246                         &dex_instance_fields2);
5247 
5248   if (dex_virtual_methods1 != dex_virtual_methods2) {
5249     std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
5250     *error_msg = StringPrintf("Virtual method count off: %zu vs %zu\n%s",
5251                               dex_virtual_methods1,
5252                               dex_virtual_methods2,
5253                               class_dump.c_str());
5254     return false;
5255   }
5256   if (dex_direct_methods1 != dex_direct_methods2) {
5257     std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
5258     *error_msg = StringPrintf("Direct method count off: %zu vs %zu\n%s",
5259                               dex_direct_methods1,
5260                               dex_direct_methods2,
5261                               class_dump.c_str());
5262     return false;
5263   }
5264   if (dex_static_fields1 != dex_static_fields2) {
5265     std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
5266     *error_msg = StringPrintf("Static field count off: %zu vs %zu\n%s",
5267                               dex_static_fields1,
5268                               dex_static_fields2,
5269                               class_dump.c_str());
5270     return false;
5271   }
5272   if (dex_instance_fields1 != dex_instance_fields2) {
5273     std::string class_dump = DumpClasses(dex_file1, dex_class_def1, dex_file2, dex_class_def2);
5274     *error_msg = StringPrintf("Instance field count off: %zu vs %zu\n%s",
5275                               dex_instance_fields1,
5276                               dex_instance_fields2,
5277                               class_dump.c_str());
5278     return false;
5279   }
5280 
5281   return true;
5282 }
5283 
5284 // Checks whether a the super-class changed from what we had at compile-time. This would
5285 // invalidate quickening.
CheckSuperClassChange(Handle<mirror::Class> klass,const DexFile & dex_file,const DexFile::ClassDef & class_def,mirror::Class * super_class)5286 static bool CheckSuperClassChange(Handle<mirror::Class> klass,
5287                                   const DexFile& dex_file,
5288                                   const DexFile::ClassDef& class_def,
5289                                   mirror::Class* super_class)
5290     SHARED_REQUIRES(Locks::mutator_lock_) {
5291   // Check for unexpected changes in the superclass.
5292   // Quick check 1) is the super_class class-loader the boot class loader? This always has
5293   // precedence.
5294   if (super_class->GetClassLoader() != nullptr &&
5295       // Quick check 2) different dex cache? Breaks can only occur for different dex files,
5296       // which is implied by different dex cache.
5297       klass->GetDexCache() != super_class->GetDexCache()) {
5298     // Now comes the expensive part: things can be broken if (a) the klass' dex file has a
5299     // definition for the super-class, and (b) the files are in separate oat files. The oat files
5300     // are referenced from the dex file, so do (b) first. Only relevant if we have oat files.
5301     const OatDexFile* class_oat_dex_file = dex_file.GetOatDexFile();
5302     const OatFile* class_oat_file = nullptr;
5303     if (class_oat_dex_file != nullptr) {
5304       class_oat_file = class_oat_dex_file->GetOatFile();
5305     }
5306 
5307     if (class_oat_file != nullptr) {
5308       const OatDexFile* loaded_super_oat_dex_file = super_class->GetDexFile().GetOatDexFile();
5309       const OatFile* loaded_super_oat_file = nullptr;
5310       if (loaded_super_oat_dex_file != nullptr) {
5311         loaded_super_oat_file = loaded_super_oat_dex_file->GetOatFile();
5312       }
5313 
5314       if (loaded_super_oat_file != nullptr && class_oat_file != loaded_super_oat_file) {
5315         // Now check (a).
5316         const DexFile::ClassDef* super_class_def = dex_file.FindClassDef(class_def.superclass_idx_);
5317         if (super_class_def != nullptr) {
5318           // Uh-oh, we found something. Do our check.
5319           std::string error_msg;
5320           if (!SimpleStructuralCheck(dex_file, *super_class_def,
5321                                      super_class->GetDexFile(), *super_class->GetClassDef(),
5322                                      &error_msg)) {
5323             // Print a warning to the log. This exception might be caught, e.g., as common in test
5324             // drivers. When the class is later tried to be used, we re-throw a new instance, as we
5325             // only save the type of the exception.
5326             LOG(WARNING) << "Incompatible structural change detected: " <<
5327                 StringPrintf(
5328                     "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
5329                     PrettyType(super_class_def->class_idx_, dex_file).c_str(),
5330                     class_oat_file->GetLocation().c_str(),
5331                     loaded_super_oat_file->GetLocation().c_str(),
5332                     error_msg.c_str());
5333             ThrowIncompatibleClassChangeError(klass.Get(),
5334                 "Structural change of %s is hazardous (%s at compile time, %s at runtime): %s",
5335                 PrettyType(super_class_def->class_idx_, dex_file).c_str(),
5336                 class_oat_file->GetLocation().c_str(),
5337                 loaded_super_oat_file->GetLocation().c_str(),
5338                 error_msg.c_str());
5339             return false;
5340           }
5341         }
5342       }
5343     }
5344   }
5345   return true;
5346 }
5347 
LoadSuperAndInterfaces(Handle<mirror::Class> klass,const DexFile & dex_file)5348 bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
5349   CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
5350   const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
5351   uint16_t super_class_idx = class_def.superclass_idx_;
5352   if (super_class_idx != DexFile::kDexNoIndex16) {
5353     // Check that a class does not inherit from itself directly.
5354     //
5355     // TODO: This is a cheap check to detect the straightforward case
5356     // of a class extending itself (b/28685551), but we should do a
5357     // proper cycle detection on loaded classes, to detect all cases
5358     // of class circularity errors (b/28830038).
5359     if (super_class_idx == class_def.class_idx_) {
5360       ThrowClassCircularityError(klass.Get(),
5361                                  "Class %s extends itself",
5362                                  PrettyDescriptor(klass.Get()).c_str());
5363       return false;
5364     }
5365 
5366     mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
5367     if (super_class == nullptr) {
5368       DCHECK(Thread::Current()->IsExceptionPending());
5369       return false;
5370     }
5371     // Verify
5372     if (!klass->CanAccess(super_class)) {
5373       ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
5374                               PrettyDescriptor(super_class).c_str(),
5375                               PrettyDescriptor(klass.Get()).c_str());
5376       return false;
5377     }
5378     CHECK(super_class->IsResolved());
5379     klass->SetSuperClass(super_class);
5380 
5381     if (!CheckSuperClassChange(klass, dex_file, class_def, super_class)) {
5382       DCHECK(Thread::Current()->IsExceptionPending());
5383       return false;
5384     }
5385   }
5386   const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
5387   if (interfaces != nullptr) {
5388     for (size_t i = 0; i < interfaces->Size(); i++) {
5389       uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
5390       mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
5391       if (interface == nullptr) {
5392         DCHECK(Thread::Current()->IsExceptionPending());
5393         return false;
5394       }
5395       // Verify
5396       if (!klass->CanAccess(interface)) {
5397         // TODO: the RI seemed to ignore this in my testing.
5398         ThrowIllegalAccessError(klass.Get(),
5399                                 "Interface %s implemented by class %s is inaccessible",
5400                                 PrettyDescriptor(interface).c_str(),
5401                                 PrettyDescriptor(klass.Get()).c_str());
5402         return false;
5403       }
5404     }
5405   }
5406   // Mark the class as loaded.
5407   mirror::Class::SetStatus(klass, mirror::Class::kStatusLoaded, nullptr);
5408   return true;
5409 }
5410 
LinkSuperClass(Handle<mirror::Class> klass)5411 bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
5412   CHECK(!klass->IsPrimitive());
5413   mirror::Class* super = klass->GetSuperClass();
5414   if (klass.Get() == GetClassRoot(kJavaLangObject)) {
5415     if (super != nullptr) {
5416       ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
5417       return false;
5418     }
5419     return true;
5420   }
5421   if (super == nullptr) {
5422     ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
5423                       PrettyDescriptor(klass.Get()).c_str());
5424     return false;
5425   }
5426   // Verify
5427   if (super->IsFinal() || super->IsInterface()) {
5428     ThrowIncompatibleClassChangeError(klass.Get(),
5429                                       "Superclass %s of %s is %s",
5430                                       PrettyDescriptor(super).c_str(),
5431                                       PrettyDescriptor(klass.Get()).c_str(),
5432                                       super->IsFinal() ? "declared final" : "an interface");
5433     return false;
5434   }
5435   if (!klass->CanAccess(super)) {
5436     ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
5437                             PrettyDescriptor(super).c_str(),
5438                             PrettyDescriptor(klass.Get()).c_str());
5439     return false;
5440   }
5441 
5442   // Inherit kAccClassIsFinalizable from the superclass in case this
5443   // class doesn't override finalize.
5444   if (super->IsFinalizable()) {
5445     klass->SetFinalizable();
5446   }
5447 
5448   // Inherit class loader flag form super class.
5449   if (super->IsClassLoaderClass()) {
5450     klass->SetClassLoaderClass();
5451   }
5452 
5453   // Inherit reference flags (if any) from the superclass.
5454   uint32_t reference_flags = (super->GetClassFlags() & mirror::kClassFlagReference);
5455   if (reference_flags != 0) {
5456     CHECK_EQ(klass->GetClassFlags(), 0u);
5457     klass->SetClassFlags(klass->GetClassFlags() | reference_flags);
5458   }
5459   // Disallow custom direct subclasses of java.lang.ref.Reference.
5460   if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
5461     ThrowLinkageError(klass.Get(),
5462                       "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
5463                       PrettyDescriptor(klass.Get()).c_str());
5464     return false;
5465   }
5466 
5467   if (kIsDebugBuild) {
5468     // Ensure super classes are fully resolved prior to resolving fields..
5469     while (super != nullptr) {
5470       CHECK(super->IsResolved());
5471       super = super->GetSuperClass();
5472     }
5473   }
5474   return true;
5475 }
5476 
5477 // Populate the class vtable and itable. Compute return type indices.
LinkMethods(Thread * self,Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces,ArtMethod ** out_imt)5478 bool ClassLinker::LinkMethods(Thread* self,
5479                               Handle<mirror::Class> klass,
5480                               Handle<mirror::ObjectArray<mirror::Class>> interfaces,
5481                               ArtMethod** out_imt) {
5482   self->AllowThreadSuspension();
5483   // A map from vtable indexes to the method they need to be updated to point to. Used because we
5484   // need to have default methods be in the virtuals array of each class but we don't set that up
5485   // until LinkInterfaceMethods.
5486   std::unordered_map<size_t, ClassLinker::MethodTranslation> default_translations;
5487   // Link virtual methods then interface methods.
5488   // We set up the interface lookup table first because we need it to determine if we need to update
5489   // any vtable entries with new default method implementations.
5490   return SetupInterfaceLookupTable(self, klass, interfaces)
5491           && LinkVirtualMethods(self, klass, /*out*/ &default_translations)
5492           && LinkInterfaceMethods(self, klass, default_translations, out_imt);
5493 }
5494 
5495 // Comparator for name and signature of a method, used in finding overriding methods. Implementation
5496 // avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
5497 // caches in the implementation below.
5498 class MethodNameAndSignatureComparator FINAL : public ValueObject {
5499  public:
5500   explicit MethodNameAndSignatureComparator(ArtMethod* method)
SHARED_REQUIRES(Locks::mutator_lock_)5501       SHARED_REQUIRES(Locks::mutator_lock_) :
5502       dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
5503       name_(nullptr), name_len_(0) {
5504     DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
5505   }
5506 
GetName()5507   const char* GetName() {
5508     if (name_ == nullptr) {
5509       name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
5510     }
5511     return name_;
5512   }
5513 
HasSameNameAndSignature(ArtMethod * other)5514   bool HasSameNameAndSignature(ArtMethod* other)
5515       SHARED_REQUIRES(Locks::mutator_lock_) {
5516     DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
5517     const DexFile* other_dex_file = other->GetDexFile();
5518     const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
5519     if (dex_file_ == other_dex_file) {
5520       return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
5521     }
5522     GetName();  // Only used to make sure its calculated.
5523     uint32_t other_name_len;
5524     const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
5525                                                                            &other_name_len);
5526     if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
5527       return false;
5528     }
5529     return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
5530   }
5531 
5532  private:
5533   // Dex file for the method to compare against.
5534   const DexFile* const dex_file_;
5535   // MethodId for the method to compare against.
5536   const DexFile::MethodId* const mid_;
5537   // Lazily computed name from the dex file's strings.
5538   const char* name_;
5539   // Lazily computed name length.
5540   uint32_t name_len_;
5541 };
5542 
5543 class LinkVirtualHashTable {
5544  public:
LinkVirtualHashTable(Handle<mirror::Class> klass,size_t hash_size,uint32_t * hash_table,size_t image_pointer_size)5545   LinkVirtualHashTable(Handle<mirror::Class> klass,
5546                        size_t hash_size,
5547                        uint32_t* hash_table,
5548                        size_t image_pointer_size)
5549      : klass_(klass),
5550        hash_size_(hash_size),
5551        hash_table_(hash_table),
5552        image_pointer_size_(image_pointer_size) {
5553     std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
5554   }
5555 
Add(uint32_t virtual_method_index)5556   void Add(uint32_t virtual_method_index) SHARED_REQUIRES(Locks::mutator_lock_) {
5557     ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(
5558         virtual_method_index, image_pointer_size_);
5559     const char* name = local_method->GetInterfaceMethodIfProxy(image_pointer_size_)->GetName();
5560     uint32_t hash = ComputeModifiedUtf8Hash(name);
5561     uint32_t index = hash % hash_size_;
5562     // Linear probe until we have an empty slot.
5563     while (hash_table_[index] != invalid_index_) {
5564       if (++index == hash_size_) {
5565         index = 0;
5566       }
5567     }
5568     hash_table_[index] = virtual_method_index;
5569   }
5570 
FindAndRemove(MethodNameAndSignatureComparator * comparator)5571   uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
5572       SHARED_REQUIRES(Locks::mutator_lock_) {
5573     const char* name = comparator->GetName();
5574     uint32_t hash = ComputeModifiedUtf8Hash(name);
5575     size_t index = hash % hash_size_;
5576     while (true) {
5577       const uint32_t value = hash_table_[index];
5578       // Since linear probe makes continuous blocks, hitting an invalid index means we are done
5579       // the block and can safely assume not found.
5580       if (value == invalid_index_) {
5581         break;
5582       }
5583       if (value != removed_index_) {  // This signifies not already overriden.
5584         ArtMethod* virtual_method =
5585             klass_->GetVirtualMethodDuringLinking(value, image_pointer_size_);
5586         if (comparator->HasSameNameAndSignature(
5587             virtual_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
5588           hash_table_[index] = removed_index_;
5589           return value;
5590         }
5591       }
5592       if (++index == hash_size_) {
5593         index = 0;
5594       }
5595     }
5596     return GetNotFoundIndex();
5597   }
5598 
GetNotFoundIndex()5599   static uint32_t GetNotFoundIndex() {
5600     return invalid_index_;
5601   }
5602 
5603  private:
5604   static const uint32_t invalid_index_;
5605   static const uint32_t removed_index_;
5606 
5607   Handle<mirror::Class> klass_;
5608   const size_t hash_size_;
5609   uint32_t* const hash_table_;
5610   const size_t image_pointer_size_;
5611 };
5612 
5613 const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
5614 const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
5615 
LinkVirtualMethods(Thread * self,Handle<mirror::Class> klass,std::unordered_map<size_t,ClassLinker::MethodTranslation> * default_translations)5616 bool ClassLinker::LinkVirtualMethods(
5617     Thread* self,
5618     Handle<mirror::Class> klass,
5619     /*out*/std::unordered_map<size_t, ClassLinker::MethodTranslation>* default_translations) {
5620   const size_t num_virtual_methods = klass->NumVirtualMethods();
5621   if (klass->IsInterface()) {
5622     // No vtable.
5623     if (!IsUint<16>(num_virtual_methods)) {
5624       ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zu", num_virtual_methods);
5625       return false;
5626     }
5627     bool has_defaults = false;
5628     // Assign each method an IMT index and set the default flag.
5629     for (size_t i = 0; i < num_virtual_methods; ++i) {
5630       ArtMethod* m = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5631       m->SetMethodIndex(i);
5632       if (!m->IsAbstract()) {
5633         m->SetAccessFlags(m->GetAccessFlags() | kAccDefault);
5634         has_defaults = true;
5635       }
5636     }
5637     // Mark that we have default methods so that we won't need to scan the virtual_methods_ array
5638     // during initialization. This is a performance optimization. We could simply traverse the
5639     // virtual_methods_ array again during initialization.
5640     if (has_defaults) {
5641       klass->SetHasDefaultMethods();
5642     }
5643     return true;
5644   } else if (klass->HasSuperClass()) {
5645     const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
5646     const size_t max_count = num_virtual_methods + super_vtable_length;
5647     StackHandleScope<2> hs(self);
5648     Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
5649     MutableHandle<mirror::PointerArray> vtable;
5650     if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5651       vtable = hs.NewHandle(AllocPointerArray(self, max_count));
5652       if (UNLIKELY(vtable.Get() == nullptr)) {
5653         self->AssertPendingOOMException();
5654         return false;
5655       }
5656       for (size_t i = 0; i < super_vtable_length; i++) {
5657         vtable->SetElementPtrSize(
5658             i, super_class->GetEmbeddedVTableEntry(i, image_pointer_size_), image_pointer_size_);
5659       }
5660       // We might need to change vtable if we have new virtual methods or new interfaces (since that
5661       // might give us new default methods). If no new interfaces then we can skip the rest since
5662       // the class cannot override any of the super-class's methods. This is required for
5663       // correctness since without it we might not update overridden default method vtable entries
5664       // correctly.
5665       if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
5666         klass->SetVTable(vtable.Get());
5667         return true;
5668       }
5669     } else {
5670       DCHECK(super_class->IsAbstract() && !super_class->IsArrayClass());
5671       auto* super_vtable = super_class->GetVTable();
5672       CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
5673       // We might need to change vtable if we have new virtual methods or new interfaces (since that
5674       // might give us new default methods). See comment above.
5675       if (num_virtual_methods == 0 && super_class->GetIfTableCount() == klass->GetIfTableCount()) {
5676         klass->SetVTable(super_vtable);
5677         return true;
5678       }
5679       vtable = hs.NewHandle(down_cast<mirror::PointerArray*>(
5680           super_vtable->CopyOf(self, max_count)));
5681       if (UNLIKELY(vtable.Get() == nullptr)) {
5682         self->AssertPendingOOMException();
5683         return false;
5684       }
5685     }
5686     // How the algorithm works:
5687     // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
5688     // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
5689     // method which has not been matched to a vtable method, and j if the virtual method at the
5690     // index overrode the super virtual method at index j.
5691     // 2. Loop through super virtual methods, if they overwrite, update hash table to j
5692     // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
5693     // the need for the initial vtable which we later shrink back down).
5694     // 3. Add non overridden methods to the end of the vtable.
5695     static constexpr size_t kMaxStackHash = 250;
5696     // + 1 so that even if we only have new default methods we will still be able to use this hash
5697     // table (i.e. it will never have 0 size).
5698     const size_t hash_table_size = num_virtual_methods * 3 + 1;
5699     uint32_t* hash_table_ptr;
5700     std::unique_ptr<uint32_t[]> hash_heap_storage;
5701     if (hash_table_size <= kMaxStackHash) {
5702       hash_table_ptr = reinterpret_cast<uint32_t*>(
5703           alloca(hash_table_size * sizeof(*hash_table_ptr)));
5704     } else {
5705       hash_heap_storage.reset(new uint32_t[hash_table_size]);
5706       hash_table_ptr = hash_heap_storage.get();
5707     }
5708     LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr, image_pointer_size_);
5709     // Add virtual methods to the hash table.
5710     for (size_t i = 0; i < num_virtual_methods; ++i) {
5711       DCHECK(klass->GetVirtualMethodDuringLinking(
5712           i, image_pointer_size_)->GetDeclaringClass() != nullptr);
5713       hash_table.Add(i);
5714     }
5715     // Loop through each super vtable method and see if they are overridden by a method we added to
5716     // the hash table.
5717     for (size_t j = 0; j < super_vtable_length; ++j) {
5718       // Search the hash table to see if we are overridden by any method.
5719       ArtMethod* super_method = vtable->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
5720       MethodNameAndSignatureComparator super_method_name_comparator(
5721           super_method->GetInterfaceMethodIfProxy(image_pointer_size_));
5722       uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
5723       if (hash_index != hash_table.GetNotFoundIndex()) {
5724         ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(
5725             hash_index, image_pointer_size_);
5726         if (klass->CanAccessMember(super_method->GetDeclaringClass(),
5727                                    super_method->GetAccessFlags())) {
5728           if (super_method->IsFinal()) {
5729             ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
5730                               PrettyMethod(virtual_method).c_str(),
5731                               super_method->GetDeclaringClassDescriptor());
5732             return false;
5733           }
5734           vtable->SetElementPtrSize(j, virtual_method, image_pointer_size_);
5735           virtual_method->SetMethodIndex(j);
5736         } else {
5737           LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
5738                        << " would have incorrectly overridden the package-private method in "
5739                        << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
5740         }
5741       } else if (super_method->IsOverridableByDefaultMethod()) {
5742         // We didn't directly override this method but we might through default methods...
5743         // Check for default method update.
5744         ArtMethod* default_method = nullptr;
5745         switch (FindDefaultMethodImplementation(self,
5746                                                 super_method,
5747                                                 klass,
5748                                                 /*out*/&default_method)) {
5749           case DefaultMethodSearchResult::kDefaultConflict: {
5750             // A conflict was found looking for default methods. Note this (assuming it wasn't
5751             // pre-existing) in the translations map.
5752             if (UNLIKELY(!super_method->IsDefaultConflicting())) {
5753               // Don't generate another conflict method to reduce memory use as an optimization.
5754               default_translations->insert(
5755                   {j, ClassLinker::MethodTranslation::CreateConflictingMethod()});
5756             }
5757             break;
5758           }
5759           case DefaultMethodSearchResult::kAbstractFound: {
5760             // No conflict but method is abstract.
5761             // We note that this vtable entry must be made abstract.
5762             if (UNLIKELY(!super_method->IsAbstract())) {
5763               default_translations->insert(
5764                   {j, ClassLinker::MethodTranslation::CreateAbstractMethod()});
5765             }
5766             break;
5767           }
5768           case DefaultMethodSearchResult::kDefaultFound: {
5769             if (UNLIKELY(super_method->IsDefaultConflicting() ||
5770                         default_method->GetDeclaringClass() != super_method->GetDeclaringClass())) {
5771               // Found a default method implementation that is new.
5772               // TODO Refactor this add default methods to virtuals here and not in
5773               //      LinkInterfaceMethods maybe.
5774               //      The problem is default methods might override previously present
5775               //      default-method or miranda-method vtable entries from the superclass.
5776               //      Unfortunately we need these to be entries in this class's virtuals. We do not
5777               //      give these entries there until LinkInterfaceMethods so we pass this map around
5778               //      to let it know which vtable entries need to be updated.
5779               // Make a note that vtable entry j must be updated, store what it needs to be updated
5780               // to. We will allocate a virtual method slot in LinkInterfaceMethods and fix it up
5781               // then.
5782               default_translations->insert(
5783                   {j, ClassLinker::MethodTranslation::CreateTranslatedMethod(default_method)});
5784               VLOG(class_linker) << "Method " << PrettyMethod(super_method)
5785                                  << " overridden by default " << PrettyMethod(default_method)
5786                                  << " in " << PrettyClass(klass.Get());
5787             }
5788             break;
5789           }
5790         }
5791       }
5792     }
5793     size_t actual_count = super_vtable_length;
5794     // Add the non-overridden methods at the end.
5795     for (size_t i = 0; i < num_virtual_methods; ++i) {
5796       ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5797       size_t method_idx = local_method->GetMethodIndexDuringLinking();
5798       if (method_idx < super_vtable_length &&
5799           local_method == vtable->GetElementPtrSize<ArtMethod*>(method_idx, image_pointer_size_)) {
5800         continue;
5801       }
5802       vtable->SetElementPtrSize(actual_count, local_method, image_pointer_size_);
5803       local_method->SetMethodIndex(actual_count);
5804       ++actual_count;
5805     }
5806     if (!IsUint<16>(actual_count)) {
5807       ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
5808       return false;
5809     }
5810     // Shrink vtable if possible
5811     CHECK_LE(actual_count, max_count);
5812     if (actual_count < max_count) {
5813       vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, actual_count)));
5814       if (UNLIKELY(vtable.Get() == nullptr)) {
5815         self->AssertPendingOOMException();
5816         return false;
5817       }
5818     }
5819     klass->SetVTable(vtable.Get());
5820   } else {
5821     CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
5822     if (!IsUint<16>(num_virtual_methods)) {
5823       ThrowClassFormatError(klass.Get(), "Too many methods: %d",
5824                             static_cast<int>(num_virtual_methods));
5825       return false;
5826     }
5827     auto* vtable = AllocPointerArray(self, num_virtual_methods);
5828     if (UNLIKELY(vtable == nullptr)) {
5829       self->AssertPendingOOMException();
5830       return false;
5831     }
5832     for (size_t i = 0; i < num_virtual_methods; ++i) {
5833       ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i, image_pointer_size_);
5834       vtable->SetElementPtrSize(i, virtual_method, image_pointer_size_);
5835       virtual_method->SetMethodIndex(i & 0xFFFF);
5836     }
5837     klass->SetVTable(vtable);
5838   }
5839   return true;
5840 }
5841 
5842 // Determine if the given iface has any subinterface in the given list that declares the method
5843 // specified by 'target'.
5844 //
5845 // Arguments
5846 // - self:    The thread we are running on
5847 // - target:  A comparator that will match any method that overrides the method we are checking for
5848 // - iftable: The iftable we are searching for an overriding method on.
5849 // - ifstart: The index of the interface we are checking to see if anything overrides
5850 // - iface:   The interface we are checking to see if anything overrides.
5851 // - image_pointer_size:
5852 //            The image pointer size.
5853 //
5854 // Returns
5855 // - True:  There is some method that matches the target comparator defined in an interface that
5856 //          is a subtype of iface.
5857 // - False: There is no method that matches the target comparator in any interface that is a subtype
5858 //          of iface.
ContainsOverridingMethodOf(Thread * self,MethodNameAndSignatureComparator & target,Handle<mirror::IfTable> iftable,size_t ifstart,Handle<mirror::Class> iface,size_t image_pointer_size)5859 static bool ContainsOverridingMethodOf(Thread* self,
5860                                        MethodNameAndSignatureComparator& target,
5861                                        Handle<mirror::IfTable> iftable,
5862                                        size_t ifstart,
5863                                        Handle<mirror::Class> iface,
5864                                        size_t image_pointer_size)
5865     SHARED_REQUIRES(Locks::mutator_lock_) {
5866   DCHECK(self != nullptr);
5867   DCHECK(iface.Get() != nullptr);
5868   DCHECK(iftable.Get() != nullptr);
5869   DCHECK_GE(ifstart, 0u);
5870   DCHECK_LT(ifstart, iftable->Count());
5871   DCHECK_EQ(iface.Get(), iftable->GetInterface(ifstart));
5872   DCHECK(iface->IsInterface());
5873 
5874   size_t iftable_count = iftable->Count();
5875   StackHandleScope<1> hs(self);
5876   MutableHandle<mirror::Class> current_iface(hs.NewHandle<mirror::Class>(nullptr));
5877   for (size_t k = ifstart + 1; k < iftable_count; k++) {
5878     // Skip ifstart since our current interface obviously cannot override itself.
5879     current_iface.Assign(iftable->GetInterface(k));
5880     // Iterate through every method on this interface. The order does not matter.
5881     for (ArtMethod& current_method : current_iface->GetDeclaredVirtualMethods(image_pointer_size)) {
5882       if (UNLIKELY(target.HasSameNameAndSignature(
5883                       current_method.GetInterfaceMethodIfProxy(image_pointer_size)))) {
5884         // Check if the i'th interface is a subtype of this one.
5885         if (iface->IsAssignableFrom(current_iface.Get())) {
5886           return true;
5887         }
5888         break;
5889       }
5890     }
5891   }
5892   return false;
5893 }
5894 
5895 // Find the default method implementation for 'interface_method' in 'klass'. Stores it into
5896 // out_default_method and returns kDefaultFound on success. If no default method was found return
5897 // kAbstractFound and store nullptr into out_default_method. If an error occurs (such as a
5898 // default_method conflict) it will return kDefaultConflict.
FindDefaultMethodImplementation(Thread * self,ArtMethod * target_method,Handle<mirror::Class> klass,ArtMethod ** out_default_method) const5899 ClassLinker::DefaultMethodSearchResult ClassLinker::FindDefaultMethodImplementation(
5900     Thread* self,
5901     ArtMethod* target_method,
5902     Handle<mirror::Class> klass,
5903     /*out*/ArtMethod** out_default_method) const {
5904   DCHECK(self != nullptr);
5905   DCHECK(target_method != nullptr);
5906   DCHECK(out_default_method != nullptr);
5907 
5908   *out_default_method = nullptr;
5909 
5910   // We organize the interface table so that, for interface I any subinterfaces J follow it in the
5911   // table. This lets us walk the table backwards when searching for default methods.  The first one
5912   // we encounter is the best candidate since it is the most specific. Once we have found it we keep
5913   // track of it and then continue checking all other interfaces, since we need to throw an error if
5914   // we encounter conflicting default method implementations (one is not a subtype of the other).
5915   //
5916   // The order of unrelated interfaces does not matter and is not defined.
5917   size_t iftable_count = klass->GetIfTableCount();
5918   if (iftable_count == 0) {
5919     // No interfaces. We have already reset out to null so just return kAbstractFound.
5920     return DefaultMethodSearchResult::kAbstractFound;
5921   }
5922 
5923   StackHandleScope<3> hs(self);
5924   MutableHandle<mirror::Class> chosen_iface(hs.NewHandle<mirror::Class>(nullptr));
5925   MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
5926   MutableHandle<mirror::Class> iface(hs.NewHandle<mirror::Class>(nullptr));
5927   MethodNameAndSignatureComparator target_name_comparator(
5928       target_method->GetInterfaceMethodIfProxy(image_pointer_size_));
5929   // Iterates over the klass's iftable in reverse
5930   for (size_t k = iftable_count; k != 0; ) {
5931     --k;
5932 
5933     DCHECK_LT(k, iftable->Count());
5934 
5935     iface.Assign(iftable->GetInterface(k));
5936     // Iterate through every declared method on this interface. The order does not matter.
5937     for (auto& method_iter : iface->GetDeclaredVirtualMethods(image_pointer_size_)) {
5938       ArtMethod* current_method = &method_iter;
5939       // Skip abstract methods and methods with different names.
5940       if (current_method->IsAbstract() ||
5941           !target_name_comparator.HasSameNameAndSignature(
5942               current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
5943         continue;
5944       } else if (!current_method->IsPublic()) {
5945         // The verifier should have caught the non-public method for dex version 37. Just warn and
5946         // skip it since this is from before default-methods so we don't really need to care that it
5947         // has code.
5948         LOG(WARNING) << "Interface method " << PrettyMethod(current_method) << " is not public! "
5949                      << "This will be a fatal error in subsequent versions of android. "
5950                      << "Continuing anyway.";
5951       }
5952       if (UNLIKELY(chosen_iface.Get() != nullptr)) {
5953         // We have multiple default impls of the same method. This is a potential default conflict.
5954         // We need to check if this possibly conflicting method is either a superclass of the chosen
5955         // default implementation or is overridden by a non-default interface method. In either case
5956         // there is no conflict.
5957         if (!iface->IsAssignableFrom(chosen_iface.Get()) &&
5958             !ContainsOverridingMethodOf(self,
5959                                         target_name_comparator,
5960                                         iftable,
5961                                         k,
5962                                         iface,
5963                                         image_pointer_size_)) {
5964           VLOG(class_linker) << "Conflicting default method implementations found: "
5965                              << PrettyMethod(current_method) << " and "
5966                              << PrettyMethod(*out_default_method) << " in class "
5967                              << PrettyClass(klass.Get()) << " conflict.";
5968           *out_default_method = nullptr;
5969           return DefaultMethodSearchResult::kDefaultConflict;
5970         } else {
5971           break;  // Continue checking at the next interface.
5972         }
5973       } else {
5974         // chosen_iface == null
5975         if (!ContainsOverridingMethodOf(self,
5976                                         target_name_comparator,
5977                                         iftable,
5978                                         k,
5979                                         iface,
5980                                         image_pointer_size_)) {
5981           // Don't set this as the chosen interface if something else is overriding it (because that
5982           // other interface would be potentially chosen instead if it was default). If the other
5983           // interface was abstract then we wouldn't select this interface as chosen anyway since
5984           // the abstract method masks it.
5985           *out_default_method = current_method;
5986           chosen_iface.Assign(iface.Get());
5987           // We should now finish traversing the graph to find if we have default methods that
5988           // conflict.
5989         } else {
5990           VLOG(class_linker) << "A default method '" << PrettyMethod(current_method) << "' was "
5991                             << "skipped because it was overridden by an abstract method in a "
5992                             << "subinterface on class '" << PrettyClass(klass.Get()) << "'";
5993         }
5994       }
5995       break;
5996     }
5997   }
5998   if (*out_default_method != nullptr) {
5999     VLOG(class_linker) << "Default method '" << PrettyMethod(*out_default_method) << "' selected "
6000                        << "as the implementation for '" << PrettyMethod(target_method) << "' "
6001                        << "in '" << PrettyClass(klass.Get()) << "'";
6002     return DefaultMethodSearchResult::kDefaultFound;
6003   } else {
6004     return DefaultMethodSearchResult::kAbstractFound;
6005   }
6006 }
6007 
AddMethodToConflictTable(mirror::Class * klass,ArtMethod * conflict_method,ArtMethod * interface_method,ArtMethod * method,bool force_new_conflict_method)6008 ArtMethod* ClassLinker::AddMethodToConflictTable(mirror::Class* klass,
6009                                                  ArtMethod* conflict_method,
6010                                                  ArtMethod* interface_method,
6011                                                  ArtMethod* method,
6012                                                  bool force_new_conflict_method) {
6013   ImtConflictTable* current_table = conflict_method->GetImtConflictTable(sizeof(void*));
6014   Runtime* const runtime = Runtime::Current();
6015   LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6016   bool new_entry = conflict_method == runtime->GetImtConflictMethod() || force_new_conflict_method;
6017 
6018   // Create a new entry if the existing one is the shared conflict method.
6019   ArtMethod* new_conflict_method = new_entry
6020       ? runtime->CreateImtConflictMethod(linear_alloc)
6021       : conflict_method;
6022 
6023   // Allocate a new table. Note that we will leak this table at the next conflict,
6024   // but that's a tradeoff compared to making the table fixed size.
6025   void* data = linear_alloc->Alloc(
6026       Thread::Current(), ImtConflictTable::ComputeSizeWithOneMoreEntry(current_table,
6027                                                                        image_pointer_size_));
6028   if (data == nullptr) {
6029     LOG(ERROR) << "Failed to allocate conflict table";
6030     return conflict_method;
6031   }
6032   ImtConflictTable* new_table = new (data) ImtConflictTable(current_table,
6033                                                             interface_method,
6034                                                             method,
6035                                                             image_pointer_size_);
6036 
6037   // Do a fence to ensure threads see the data in the table before it is assigned
6038   // to the conflict method.
6039   // Note that there is a race in the presence of multiple threads and we may leak
6040   // memory from the LinearAlloc, but that's a tradeoff compared to using
6041   // atomic operations.
6042   QuasiAtomic::ThreadFenceRelease();
6043   new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6044   return new_conflict_method;
6045 }
6046 
SetIMTRef(ArtMethod * unimplemented_method,ArtMethod * imt_conflict_method,ArtMethod * current_method,ArtMethod ** imt_ref)6047 void ClassLinker::SetIMTRef(ArtMethod* unimplemented_method,
6048                             ArtMethod* imt_conflict_method,
6049                             ArtMethod* current_method,
6050                             /*out*/ArtMethod** imt_ref) {
6051   // Place method in imt if entry is empty, place conflict otherwise.
6052   if (*imt_ref == unimplemented_method) {
6053     *imt_ref = current_method;
6054   } else if (!(*imt_ref)->IsRuntimeMethod()) {
6055     // If we are not a conflict and we have the same signature and name as the imt
6056     // entry, it must be that we overwrote a superclass vtable entry.
6057     // Note that we have checked IsRuntimeMethod, as there may be multiple different
6058     // conflict methods.
6059     MethodNameAndSignatureComparator imt_comparator(
6060         (*imt_ref)->GetInterfaceMethodIfProxy(image_pointer_size_));
6061     if (imt_comparator.HasSameNameAndSignature(
6062           current_method->GetInterfaceMethodIfProxy(image_pointer_size_))) {
6063       *imt_ref = current_method;
6064     } else {
6065       *imt_ref = imt_conflict_method;
6066     }
6067   } else {
6068     // Place the default conflict method. Note that there may be an existing conflict
6069     // method in the IMT, but it could be one tailored to the super class, with a
6070     // specific ImtConflictTable.
6071     *imt_ref = imt_conflict_method;
6072   }
6073 }
6074 
FillIMTAndConflictTables(mirror::Class * klass)6075 void ClassLinker::FillIMTAndConflictTables(mirror::Class* klass) {
6076   DCHECK(klass->ShouldHaveEmbeddedImtAndVTable()) << PrettyClass(klass);
6077   DCHECK(!klass->IsTemp()) << PrettyClass(klass);
6078   ArtMethod* imt[mirror::Class::kImtSize];
6079   Runtime* const runtime = Runtime::Current();
6080   ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6081   ArtMethod* const conflict_method = runtime->GetImtConflictMethod();
6082   std::fill_n(imt, arraysize(imt), unimplemented_method);
6083   if (klass->GetIfTable() != nullptr) {
6084     FillIMTFromIfTable(klass->GetIfTable(),
6085                        unimplemented_method,
6086                        conflict_method,
6087                        klass,
6088                        true,
6089                        false,
6090                        &imt[0]);
6091   }
6092   for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
6093     klass->SetEmbeddedImTableEntry(i, imt[i], image_pointer_size_);
6094   }
6095 }
6096 
GetIMTIndex(ArtMethod * interface_method)6097 static inline uint32_t GetIMTIndex(ArtMethod* interface_method)
6098     SHARED_REQUIRES(Locks::mutator_lock_) {
6099   return interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
6100 }
6101 
CreateImtConflictTable(size_t count,LinearAlloc * linear_alloc,size_t image_pointer_size)6102 ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count,
6103                                                       LinearAlloc* linear_alloc,
6104                                                       size_t image_pointer_size) {
6105   void* data = linear_alloc->Alloc(Thread::Current(),
6106                                    ImtConflictTable::ComputeSize(count,
6107                                                                  image_pointer_size));
6108   return (data != nullptr) ? new (data) ImtConflictTable(count, image_pointer_size) : nullptr;
6109 }
6110 
CreateImtConflictTable(size_t count,LinearAlloc * linear_alloc)6111 ImtConflictTable* ClassLinker::CreateImtConflictTable(size_t count, LinearAlloc* linear_alloc) {
6112   return CreateImtConflictTable(count, linear_alloc, image_pointer_size_);
6113 }
6114 
FillIMTFromIfTable(mirror::IfTable * if_table,ArtMethod * unimplemented_method,ArtMethod * imt_conflict_method,mirror::Class * klass,bool create_conflict_tables,bool ignore_copied_methods,ArtMethod ** imt)6115 void ClassLinker::FillIMTFromIfTable(mirror::IfTable* if_table,
6116                                      ArtMethod* unimplemented_method,
6117                                      ArtMethod* imt_conflict_method,
6118                                      mirror::Class* klass,
6119                                      bool create_conflict_tables,
6120                                      bool ignore_copied_methods,
6121                                      ArtMethod** imt) {
6122   uint32_t conflict_counts[mirror::Class::kImtSize] = {};
6123   for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
6124     mirror::Class* interface = if_table->GetInterface(i);
6125     const size_t num_virtuals = interface->NumVirtualMethods();
6126     const size_t method_array_count = if_table->GetMethodArrayCount(i);
6127     // Virtual methods can be larger than the if table methods if there are default methods.
6128     DCHECK_GE(num_virtuals, method_array_count);
6129     if (kIsDebugBuild) {
6130       if (klass->IsInterface()) {
6131         DCHECK_EQ(method_array_count, 0u);
6132       } else {
6133         DCHECK_EQ(interface->NumDeclaredVirtualMethods(), method_array_count);
6134       }
6135     }
6136     if (method_array_count == 0) {
6137       continue;
6138     }
6139     auto* method_array = if_table->GetMethodArray(i);
6140     for (size_t j = 0; j < method_array_count; ++j) {
6141       ArtMethod* implementation_method =
6142           method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6143       if (ignore_copied_methods && implementation_method->IsCopied()) {
6144         continue;
6145       }
6146       DCHECK(implementation_method != nullptr);
6147       // Miranda methods cannot be used to implement an interface method, but they are safe to put
6148       // in the IMT since their entrypoint is the interface trampoline. If we put any copied methods
6149       // or interface methods in the IMT here they will not create extra conflicts since we compare
6150       // names and signatures in SetIMTRef.
6151       ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
6152       const uint32_t imt_index = GetIMTIndex(interface_method);
6153 
6154       // There is only any conflicts if all of the interface methods for an IMT slot don't have
6155       // the same implementation method, keep track of this to avoid creating a conflict table in
6156       // this case.
6157 
6158       // Conflict table size for each IMT slot.
6159       ++conflict_counts[imt_index];
6160 
6161       SetIMTRef(unimplemented_method,
6162                 imt_conflict_method,
6163                 implementation_method,
6164                 /*out*/&imt[imt_index]);
6165     }
6166   }
6167 
6168   if (create_conflict_tables) {
6169     // Create the conflict tables.
6170     LinearAlloc* linear_alloc = GetAllocatorForClassLoader(klass->GetClassLoader());
6171     for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
6172       size_t conflicts = conflict_counts[i];
6173       if (imt[i] == imt_conflict_method) {
6174         ImtConflictTable* new_table = CreateImtConflictTable(conflicts, linear_alloc);
6175         if (new_table != nullptr) {
6176           ArtMethod* new_conflict_method =
6177               Runtime::Current()->CreateImtConflictMethod(linear_alloc);
6178           new_conflict_method->SetImtConflictTable(new_table, image_pointer_size_);
6179           imt[i] = new_conflict_method;
6180         } else {
6181           LOG(ERROR) << "Failed to allocate conflict table";
6182           imt[i] = imt_conflict_method;
6183         }
6184       } else {
6185         DCHECK_NE(imt[i], imt_conflict_method);
6186       }
6187     }
6188 
6189     for (size_t i = 0, length = if_table->Count(); i < length; ++i) {
6190       mirror::Class* interface = if_table->GetInterface(i);
6191       const size_t method_array_count = if_table->GetMethodArrayCount(i);
6192       // Virtual methods can be larger than the if table methods if there are default methods.
6193       if (method_array_count == 0) {
6194         continue;
6195       }
6196       auto* method_array = if_table->GetMethodArray(i);
6197       for (size_t j = 0; j < method_array_count; ++j) {
6198         ArtMethod* implementation_method =
6199             method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6200         if (ignore_copied_methods && implementation_method->IsCopied()) {
6201           continue;
6202         }
6203         DCHECK(implementation_method != nullptr);
6204         ArtMethod* interface_method = interface->GetVirtualMethod(j, image_pointer_size_);
6205         const uint32_t imt_index = GetIMTIndex(interface_method);
6206         if (!imt[imt_index]->IsRuntimeMethod() ||
6207             imt[imt_index] == unimplemented_method ||
6208             imt[imt_index] == imt_conflict_method) {
6209           continue;
6210         }
6211         ImtConflictTable* table = imt[imt_index]->GetImtConflictTable(image_pointer_size_);
6212         const size_t num_entries = table->NumEntries(image_pointer_size_);
6213         table->SetInterfaceMethod(num_entries, image_pointer_size_, interface_method);
6214         table->SetImplementationMethod(num_entries, image_pointer_size_, implementation_method);
6215       }
6216     }
6217   }
6218 }
6219 
6220 // Simple helper function that checks that no subtypes of 'val' are contained within the 'classes'
6221 // set.
NotSubinterfaceOfAny(const std::unordered_set<mirror::Class * > & classes,mirror::Class * val)6222 static bool NotSubinterfaceOfAny(const std::unordered_set<mirror::Class*>& classes,
6223                                  mirror::Class* val)
6224     REQUIRES(Roles::uninterruptible_)
6225     SHARED_REQUIRES(Locks::mutator_lock_) {
6226   DCHECK(val != nullptr);
6227   for (auto c : classes) {
6228     if (val->IsAssignableFrom(&*c)) {
6229       return false;
6230     }
6231   }
6232   return true;
6233 }
6234 
6235 // Fills in and flattens the interface inheritance hierarchy.
6236 //
6237 // By the end of this function all interfaces in the transitive closure of to_process are added to
6238 // the iftable and every interface precedes all of its sub-interfaces in this list.
6239 //
6240 // all I, J: Interface | I <: J implies J precedes I
6241 //
6242 // (note A <: B means that A is a subtype of B)
6243 //
6244 // This returns the total number of items in the iftable. The iftable might be resized down after
6245 // this call.
6246 //
6247 // We order this backwards so that we do not need to reorder superclass interfaces when new
6248 // interfaces are added in subclass's interface tables.
6249 //
6250 // Upon entry into this function iftable is a copy of the superclass's iftable with the first
6251 // super_ifcount entries filled in with the transitive closure of the interfaces of the superclass.
6252 // The other entries are uninitialized.  We will fill in the remaining entries in this function. The
6253 // iftable must be large enough to hold all interfaces without changing its size.
FillIfTable(mirror::IfTable * iftable,size_t super_ifcount,std::vector<mirror::Class * > to_process)6254 static size_t FillIfTable(mirror::IfTable* iftable,
6255                           size_t super_ifcount,
6256                           std::vector<mirror::Class*> to_process)
6257     REQUIRES(Roles::uninterruptible_)
6258     SHARED_REQUIRES(Locks::mutator_lock_) {
6259   // This is the set of all class's already in the iftable. Used to make checking if a class has
6260   // already been added quicker.
6261   std::unordered_set<mirror::Class*> classes_in_iftable;
6262   // The first super_ifcount elements are from the superclass. We note that they are already added.
6263   for (size_t i = 0; i < super_ifcount; i++) {
6264     mirror::Class* iface = iftable->GetInterface(i);
6265     DCHECK(NotSubinterfaceOfAny(classes_in_iftable, iface)) << "Bad ordering.";
6266     classes_in_iftable.insert(iface);
6267   }
6268   size_t filled_ifcount = super_ifcount;
6269   for (mirror::Class* interface : to_process) {
6270     // Let us call the first filled_ifcount elements of iftable the current-iface-list.
6271     // At this point in the loop current-iface-list has the invariant that:
6272     //    for every pair of interfaces I,J within it:
6273     //      if index_of(I) < index_of(J) then I is not a subtype of J
6274 
6275     // If we have already seen this element then all of its super-interfaces must already be in the
6276     // current-iface-list so we can skip adding it.
6277     if (!ContainsElement(classes_in_iftable, interface)) {
6278       // We haven't seen this interface so add all of its super-interfaces onto the
6279       // current-iface-list, skipping those already on it.
6280       int32_t ifcount = interface->GetIfTableCount();
6281       for (int32_t j = 0; j < ifcount; j++) {
6282         mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
6283         if (!ContainsElement(classes_in_iftable, super_interface)) {
6284           DCHECK(NotSubinterfaceOfAny(classes_in_iftable, super_interface)) << "Bad ordering.";
6285           classes_in_iftable.insert(super_interface);
6286           iftable->SetInterface(filled_ifcount, super_interface);
6287           filled_ifcount++;
6288         }
6289       }
6290       DCHECK(NotSubinterfaceOfAny(classes_in_iftable, interface)) << "Bad ordering";
6291       // Place this interface onto the current-iface-list after all of its super-interfaces.
6292       classes_in_iftable.insert(interface);
6293       iftable->SetInterface(filled_ifcount, interface);
6294       filled_ifcount++;
6295     } else if (kIsDebugBuild) {
6296       // Check all super-interfaces are already in the list.
6297       int32_t ifcount = interface->GetIfTableCount();
6298       for (int32_t j = 0; j < ifcount; j++) {
6299         mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
6300         DCHECK(ContainsElement(classes_in_iftable, super_interface))
6301             << "Iftable does not contain " << PrettyClass(super_interface)
6302             << ", a superinterface of " << PrettyClass(interface);
6303       }
6304     }
6305   }
6306   if (kIsDebugBuild) {
6307     // Check that the iftable is ordered correctly.
6308     for (size_t i = 0; i < filled_ifcount; i++) {
6309       mirror::Class* if_a = iftable->GetInterface(i);
6310       for (size_t j = i + 1; j < filled_ifcount; j++) {
6311         mirror::Class* if_b = iftable->GetInterface(j);
6312         // !(if_a <: if_b)
6313         CHECK(!if_b->IsAssignableFrom(if_a))
6314             << "Bad interface order: " << PrettyClass(if_a) << " (index " << i << ") extends "
6315             << PrettyClass(if_b) << " (index " << j << ") and so should be after it in the "
6316             << "interface list.";
6317       }
6318     }
6319   }
6320   return filled_ifcount;
6321 }
6322 
SetupInterfaceLookupTable(Thread * self,Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces)6323 bool ClassLinker::SetupInterfaceLookupTable(Thread* self, Handle<mirror::Class> klass,
6324                                             Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
6325   StackHandleScope<1> hs(self);
6326   const size_t super_ifcount =
6327       klass->HasSuperClass() ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6328   const bool have_interfaces = interfaces.Get() != nullptr;
6329   const size_t num_interfaces =
6330       have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
6331   if (num_interfaces == 0) {
6332     if (super_ifcount == 0) {
6333       // Class implements no interfaces.
6334       DCHECK_EQ(klass->GetIfTableCount(), 0);
6335       DCHECK(klass->GetIfTable() == nullptr);
6336       return true;
6337     }
6338     // Class implements same interfaces as parent, are any of these not marker interfaces?
6339     bool has_non_marker_interface = false;
6340     mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
6341     for (size_t i = 0; i < super_ifcount; ++i) {
6342       if (super_iftable->GetMethodArrayCount(i) > 0) {
6343         has_non_marker_interface = true;
6344         break;
6345       }
6346     }
6347     // Class just inherits marker interfaces from parent so recycle parent's iftable.
6348     if (!has_non_marker_interface) {
6349       klass->SetIfTable(super_iftable);
6350       return true;
6351     }
6352   }
6353   size_t ifcount = super_ifcount + num_interfaces;
6354   // Check that every class being implemented is an interface.
6355   for (size_t i = 0; i < num_interfaces; i++) {
6356     mirror::Class* interface = have_interfaces
6357         ? interfaces->GetWithoutChecks(i)
6358         : mirror::Class::GetDirectInterface(self, klass, i);
6359     DCHECK(interface != nullptr);
6360     if (UNLIKELY(!interface->IsInterface())) {
6361       std::string temp;
6362       ThrowIncompatibleClassChangeError(klass.Get(),
6363                                         "Class %s implements non-interface class %s",
6364                                         PrettyDescriptor(klass.Get()).c_str(),
6365                                         PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
6366       return false;
6367     }
6368     ifcount += interface->GetIfTableCount();
6369   }
6370   // Create the interface function table.
6371   MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
6372   if (UNLIKELY(iftable.Get() == nullptr)) {
6373     self->AssertPendingOOMException();
6374     return false;
6375   }
6376   // Fill in table with superclass's iftable.
6377   if (super_ifcount != 0) {
6378     mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
6379     for (size_t i = 0; i < super_ifcount; i++) {
6380       mirror::Class* super_interface = super_iftable->GetInterface(i);
6381       iftable->SetInterface(i, super_interface);
6382     }
6383   }
6384 
6385   // Note that AllowThreadSuspension is to thread suspension as pthread_testcancel is to pthread
6386   // cancellation. That is it will suspend if one has a pending suspend request but otherwise
6387   // doesn't really do anything.
6388   self->AllowThreadSuspension();
6389 
6390   size_t new_ifcount;
6391   {
6392     ScopedAssertNoThreadSuspension nts(self, "Copying mirror::Class*'s for FillIfTable");
6393     std::vector<mirror::Class*> to_add;
6394     for (size_t i = 0; i < num_interfaces; i++) {
6395       mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
6396           mirror::Class::GetDirectInterface(self, klass, i);
6397       to_add.push_back(interface);
6398     }
6399 
6400     new_ifcount = FillIfTable(iftable.Get(), super_ifcount, std::move(to_add));
6401   }
6402 
6403   self->AllowThreadSuspension();
6404 
6405   // Shrink iftable in case duplicates were found
6406   if (new_ifcount < ifcount) {
6407     DCHECK_NE(num_interfaces, 0U);
6408     iftable.Assign(down_cast<mirror::IfTable*>(
6409         iftable->CopyOf(self, new_ifcount * mirror::IfTable::kMax)));
6410     if (UNLIKELY(iftable.Get() == nullptr)) {
6411       self->AssertPendingOOMException();
6412       return false;
6413     }
6414     ifcount = new_ifcount;
6415   } else {
6416     DCHECK_EQ(new_ifcount, ifcount);
6417   }
6418   klass->SetIfTable(iftable.Get());
6419   return true;
6420 }
6421 
6422 // Finds the method with a name/signature that matches cmp in the given list of methods. The list of
6423 // methods must be unique.
FindSameNameAndSignature(MethodNameAndSignatureComparator & cmp,const ScopedArenaVector<ArtMethod * > & list)6424 static ArtMethod* FindSameNameAndSignature(MethodNameAndSignatureComparator& cmp,
6425                                            const ScopedArenaVector<ArtMethod*>& list)
6426     SHARED_REQUIRES(Locks::mutator_lock_) {
6427   for (ArtMethod* method : list) {
6428     if (cmp.HasSameNameAndSignature(method)) {
6429       return method;
6430     }
6431   }
6432   return nullptr;
6433 }
6434 
SanityCheckVTable(Handle<mirror::Class> klass,uint32_t pointer_size)6435 static void SanityCheckVTable(Handle<mirror::Class> klass, uint32_t pointer_size)
6436     SHARED_REQUIRES(Locks::mutator_lock_) {
6437   mirror::PointerArray* check_vtable = klass->GetVTableDuringLinking();
6438   mirror::Class* superclass = (klass->HasSuperClass()) ? klass->GetSuperClass() : nullptr;
6439   int32_t super_vtable_length = (superclass != nullptr) ? superclass->GetVTableLength() : 0;
6440   for (int32_t i = 0; i < check_vtable->GetLength(); ++i) {
6441     ArtMethod* m = check_vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
6442     CHECK(m != nullptr);
6443 
6444     ArraySlice<ArtMethod> virtuals = klass->GetVirtualMethodsSliceUnchecked(pointer_size);
6445     auto is_same_method = [m] (const ArtMethod& meth) {
6446       return &meth == m;
6447     };
6448     CHECK((super_vtable_length > i && superclass->GetVTableEntry(i, pointer_size) == m) ||
6449           std::find_if(virtuals.begin(), virtuals.end(), is_same_method) != virtuals.end())
6450         << "While linking class '" << PrettyClass(klass.Get()) << "' unable to find owning class "
6451         << "of '" << PrettyMethod(m) << "' (vtable index: " << i << ").";
6452   }
6453 }
6454 
FillImtFromSuperClass(Handle<mirror::Class> klass,ArtMethod * unimplemented_method,ArtMethod * imt_conflict_method,ArtMethod ** imt)6455 void ClassLinker::FillImtFromSuperClass(Handle<mirror::Class> klass,
6456                                         ArtMethod* unimplemented_method,
6457                                         ArtMethod* imt_conflict_method,
6458                                         ArtMethod** imt) {
6459   DCHECK(klass->HasSuperClass());
6460   mirror::Class* super_class = klass->GetSuperClass();
6461   if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
6462     for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
6463       imt[i] = super_class->GetEmbeddedImTableEntry(i, image_pointer_size_);
6464     }
6465   } else {
6466     // No imt in the super class, need to reconstruct from the iftable.
6467     mirror::IfTable* if_table = super_class->GetIfTable();
6468     if (if_table != nullptr) {
6469       // Ignore copied methods since we will handle these in LinkInterfaceMethods.
6470       FillIMTFromIfTable(if_table,
6471                          unimplemented_method,
6472                          imt_conflict_method,
6473                          klass.Get(),
6474                          /*create_conflict_table*/false,
6475                          /*ignore_copied_methods*/true,
6476                          /*out*/imt);
6477     }
6478   }
6479 }
6480 
6481 // TODO This method needs to be split up into several smaller methods.
LinkInterfaceMethods(Thread * self,Handle<mirror::Class> klass,const std::unordered_map<size_t,ClassLinker::MethodTranslation> & default_translations,ArtMethod ** out_imt)6482 bool ClassLinker::LinkInterfaceMethods(
6483     Thread* self,
6484     Handle<mirror::Class> klass,
6485     const std::unordered_map<size_t, ClassLinker::MethodTranslation>& default_translations,
6486     ArtMethod** out_imt) {
6487   StackHandleScope<3> hs(self);
6488   Runtime* const runtime = Runtime::Current();
6489 
6490   const bool is_interface = klass->IsInterface();
6491   const bool has_superclass = klass->HasSuperClass();
6492   const bool fill_tables = !is_interface;
6493   const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
6494   const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
6495   const size_t method_size = ArtMethod::Size(image_pointer_size_);
6496   const size_t ifcount = klass->GetIfTableCount();
6497 
6498   MutableHandle<mirror::IfTable> iftable(hs.NewHandle(klass->GetIfTable()));
6499 
6500   // These are allocated on the heap to begin, we then transfer to linear alloc when we re-create
6501   // the virtual methods array.
6502   // Need to use low 4GB arenas for compiler or else the pointers wont fit in 32 bit method array
6503   // during cross compilation.
6504   // Use the linear alloc pool since this one is in the low 4gb for the compiler.
6505   ArenaStack stack(runtime->GetLinearAlloc()->GetArenaPool());
6506   ScopedArenaAllocator allocator(&stack);
6507 
6508   ScopedArenaVector<ArtMethod*> default_conflict_methods(allocator.Adapter());
6509   ScopedArenaVector<ArtMethod*> miranda_methods(allocator.Adapter());
6510   ScopedArenaVector<ArtMethod*> default_methods(allocator.Adapter());
6511 
6512   MutableHandle<mirror::PointerArray> vtable(hs.NewHandle(klass->GetVTableDuringLinking()));
6513   ArtMethod* const unimplemented_method = runtime->GetImtUnimplementedMethod();
6514   ArtMethod* const imt_conflict_method = runtime->GetImtConflictMethod();
6515   // Copy the IMT from the super class if possible.
6516   const bool extend_super_iftable = has_superclass;
6517   if (has_superclass && fill_tables) {
6518     FillImtFromSuperClass(klass,
6519                           unimplemented_method,
6520                           imt_conflict_method,
6521                           out_imt);
6522   }
6523   // Allocate method arrays before since we don't want miss visiting miranda method roots due to
6524   // thread suspension.
6525   if (fill_tables) {
6526     for (size_t i = 0; i < ifcount; ++i) {
6527       size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6528       if (num_methods > 0) {
6529         const bool is_super = i < super_ifcount;
6530         // This is an interface implemented by a super-class. Therefore we can just copy the method
6531         // array from the superclass.
6532         const bool super_interface = is_super && extend_super_iftable;
6533         mirror::PointerArray* method_array;
6534         if (super_interface) {
6535           mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
6536           DCHECK(if_table != nullptr);
6537           DCHECK(if_table->GetMethodArray(i) != nullptr);
6538           // If we are working on a super interface, try extending the existing method array.
6539           method_array = down_cast<mirror::PointerArray*>(if_table->GetMethodArray(i)->Clone(self));
6540         } else {
6541           method_array = AllocPointerArray(self, num_methods);
6542         }
6543         if (UNLIKELY(method_array == nullptr)) {
6544           self->AssertPendingOOMException();
6545           return false;
6546         }
6547         iftable->SetMethodArray(i, method_array);
6548       }
6549     }
6550   }
6551 
6552   auto* old_cause = self->StartAssertNoThreadSuspension(
6553       "Copying ArtMethods for LinkInterfaceMethods");
6554   // Going in reverse to ensure that we will hit abstract methods that override defaults before the
6555   // defaults. This means we don't need to do any trickery when creating the Miranda methods, since
6556   // they will already be null. This has the additional benefit that the declarer of a miranda
6557   // method will actually declare an abstract method.
6558   for (size_t i = ifcount; i != 0; ) {
6559     --i;
6560 
6561     DCHECK_GE(i, 0u);
6562     DCHECK_LT(i, ifcount);
6563 
6564     size_t num_methods = iftable->GetInterface(i)->NumDeclaredVirtualMethods();
6565     if (num_methods > 0) {
6566       StackHandleScope<2> hs2(self);
6567       const bool is_super = i < super_ifcount;
6568       const bool super_interface = is_super && extend_super_iftable;
6569       // We don't actually create or fill these tables for interfaces, we just copy some methods for
6570       // conflict methods. Just set this as nullptr in those cases.
6571       Handle<mirror::PointerArray> method_array(fill_tables
6572                                                 ? hs2.NewHandle(iftable->GetMethodArray(i))
6573                                                 : hs2.NewHandle<mirror::PointerArray>(nullptr));
6574 
6575       ArraySlice<ArtMethod> input_virtual_methods;
6576       ScopedNullHandle<mirror::PointerArray> null_handle;
6577       Handle<mirror::PointerArray> input_vtable_array(null_handle);
6578       int32_t input_array_length = 0;
6579 
6580       // TODO Cleanup Needed: In the presence of default methods this optimization is rather dirty
6581       //      and confusing. Default methods should always look through all the superclasses
6582       //      because they are the last choice of an implementation. We get around this by looking
6583       //      at the super-classes iftable methods (copied into method_array previously) when we are
6584       //      looking for the implementation of a super-interface method but that is rather dirty.
6585       bool using_virtuals;
6586       if (super_interface || is_interface) {
6587         // If we are overwriting a super class interface, try to only virtual methods instead of the
6588         // whole vtable.
6589         using_virtuals = true;
6590         input_virtual_methods = klass->GetDeclaredMethodsSlice(image_pointer_size_);
6591         input_array_length = input_virtual_methods.size();
6592       } else {
6593         // For a new interface, however, we need the whole vtable in case a new
6594         // interface method is implemented in the whole superclass.
6595         using_virtuals = false;
6596         DCHECK(vtable.Get() != nullptr);
6597         input_vtable_array = vtable;
6598         input_array_length = input_vtable_array->GetLength();
6599       }
6600 
6601       // For each method in interface
6602       for (size_t j = 0; j < num_methods; ++j) {
6603         auto* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j, image_pointer_size_);
6604         MethodNameAndSignatureComparator interface_name_comparator(
6605             interface_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6606         uint32_t imt_index = GetIMTIndex(interface_method);
6607         ArtMethod** imt_ptr = &out_imt[imt_index];
6608         // For each method listed in the interface's method list, find the
6609         // matching method in our class's method list.  We want to favor the
6610         // subclass over the superclass, which just requires walking
6611         // back from the end of the vtable.  (This only matters if the
6612         // superclass defines a private method and this class redefines
6613         // it -- otherwise it would use the same vtable slot.  In .dex files
6614         // those don't end up in the virtual method table, so it shouldn't
6615         // matter which direction we go.  We walk it backward anyway.)
6616         //
6617         // To find defaults we need to do the same but also go over interfaces.
6618         bool found_impl = false;
6619         ArtMethod* vtable_impl = nullptr;
6620         for (int32_t k = input_array_length - 1; k >= 0; --k) {
6621           ArtMethod* vtable_method = using_virtuals ?
6622               &input_virtual_methods[k] :
6623               input_vtable_array->GetElementPtrSize<ArtMethod*>(k, image_pointer_size_);
6624           ArtMethod* vtable_method_for_name_comparison =
6625               vtable_method->GetInterfaceMethodIfProxy(image_pointer_size_);
6626           if (interface_name_comparator.HasSameNameAndSignature(
6627               vtable_method_for_name_comparison)) {
6628             if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
6629               // Must do EndAssertNoThreadSuspension before throw since the throw can cause
6630               // allocations.
6631               self->EndAssertNoThreadSuspension(old_cause);
6632               ThrowIllegalAccessError(klass.Get(),
6633                   "Method '%s' implementing interface method '%s' is not public",
6634                   PrettyMethod(vtable_method).c_str(), PrettyMethod(interface_method).c_str());
6635               return false;
6636             } else if (UNLIKELY(vtable_method->IsOverridableByDefaultMethod())) {
6637               // We might have a newer, better, default method for this, so we just skip it. If we
6638               // are still using this we will select it again when scanning for default methods. To
6639               // obviate the need to copy the method again we will make a note that we already found
6640               // a default here.
6641               // TODO This should be much cleaner.
6642               vtable_impl = vtable_method;
6643               break;
6644             } else {
6645               found_impl = true;
6646               if (LIKELY(fill_tables)) {
6647                 method_array->SetElementPtrSize(j, vtable_method, image_pointer_size_);
6648                 // Place method in imt if entry is empty, place conflict otherwise.
6649                 SetIMTRef(unimplemented_method,
6650                           imt_conflict_method,
6651                           vtable_method,
6652                           /*out*/imt_ptr);
6653               }
6654               break;
6655             }
6656           }
6657         }
6658         // Continue on to the next method if we are done.
6659         if (LIKELY(found_impl)) {
6660           continue;
6661         } else if (LIKELY(super_interface)) {
6662           // Don't look for a default implementation when the super-method is implemented directly
6663           // by the class.
6664           //
6665           // See if we can use the superclasses method and skip searching everything else.
6666           // Note: !found_impl && super_interface
6667           CHECK(extend_super_iftable);
6668           // If this is a super_interface method it is possible we shouldn't override it because a
6669           // superclass could have implemented it directly.  We get the method the superclass used
6670           // to implement this to know if we can override it with a default method. Doing this is
6671           // safe since we know that the super_iftable is filled in so we can simply pull it from
6672           // there. We don't bother if this is not a super-classes interface since in that case we
6673           // have scanned the entire vtable anyway and would have found it.
6674           // TODO This is rather dirty but it is faster than searching through the entire vtable
6675           //      every time.
6676           ArtMethod* supers_method =
6677               method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6678           DCHECK(supers_method != nullptr);
6679           DCHECK(interface_name_comparator.HasSameNameAndSignature(supers_method));
6680           if (LIKELY(!supers_method->IsOverridableByDefaultMethod())) {
6681             // The method is not overridable by a default method (i.e. it is directly implemented
6682             // in some class). Therefore move onto the next interface method.
6683             continue;
6684           } else {
6685             // If the super-classes method is override-able by a default method we need to keep
6686             // track of it since though it is override-able it is not guaranteed to be 'overridden'.
6687             // If it turns out not to be overridden and we did not keep track of it we might add it
6688             // to the vtable twice, causing corruption in this class and possibly any subclasses.
6689             DCHECK(vtable_impl == nullptr || vtable_impl == supers_method)
6690                 << "vtable_impl was " << PrettyMethod(vtable_impl) << " and not 'nullptr' or "
6691                 << PrettyMethod(supers_method) << " as expected. IFTable appears to be corrupt!";
6692             vtable_impl = supers_method;
6693           }
6694         }
6695         // If we haven't found it yet we should search through the interfaces for default methods.
6696         ArtMethod* current_method = nullptr;
6697         switch (FindDefaultMethodImplementation(self,
6698                                                 interface_method,
6699                                                 klass,
6700                                                 /*out*/&current_method)) {
6701           case DefaultMethodSearchResult::kDefaultConflict: {
6702             // Default method conflict.
6703             DCHECK(current_method == nullptr);
6704             ArtMethod* default_conflict_method = nullptr;
6705             if (vtable_impl != nullptr && vtable_impl->IsDefaultConflicting()) {
6706               // We can reuse the method from the superclass, don't bother adding it to virtuals.
6707               default_conflict_method = vtable_impl;
6708             } else {
6709               // See if we already have a conflict method for this method.
6710               ArtMethod* preexisting_conflict = FindSameNameAndSignature(interface_name_comparator,
6711                                                                          default_conflict_methods);
6712               if (LIKELY(preexisting_conflict != nullptr)) {
6713                 // We already have another conflict we can reuse.
6714                 default_conflict_method = preexisting_conflict;
6715               } else {
6716                 // Note that we do this even if we are an interface since we need to create this and
6717                 // cannot reuse another classes.
6718                 // Create a new conflict method for this to use.
6719                 default_conflict_method =
6720                     reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size));
6721                 new(default_conflict_method) ArtMethod(interface_method, image_pointer_size_);
6722                 default_conflict_methods.push_back(default_conflict_method);
6723               }
6724             }
6725             current_method = default_conflict_method;
6726             break;
6727           }  // case kDefaultConflict
6728           case DefaultMethodSearchResult::kDefaultFound: {
6729             DCHECK(current_method != nullptr);
6730             // Found a default method.
6731             if (vtable_impl != nullptr &&
6732                 current_method->GetDeclaringClass() == vtable_impl->GetDeclaringClass()) {
6733               // We found a default method but it was the same one we already have from our
6734               // superclass. Don't bother adding it to our vtable again.
6735               current_method = vtable_impl;
6736             } else if (LIKELY(fill_tables)) {
6737               // Interfaces don't need to copy default methods since they don't have vtables.
6738               // Only record this default method if it is new to save space.
6739               // TODO It might be worthwhile to copy default methods on interfaces anyway since it
6740               //      would make lookup for interface super much faster. (We would only need to scan
6741               //      the iftable to find if there is a NSME or AME.)
6742               ArtMethod* old = FindSameNameAndSignature(interface_name_comparator, default_methods);
6743               if (old == nullptr) {
6744                 // We found a default method implementation and there were no conflicts.
6745                 // Save the default method. We need to add it to the vtable.
6746                 default_methods.push_back(current_method);
6747               } else {
6748                 CHECK(old == current_method) << "Multiple default implementations selected!";
6749               }
6750             }
6751             break;
6752           }  // case kDefaultFound
6753           case DefaultMethodSearchResult::kAbstractFound: {
6754             DCHECK(current_method == nullptr);
6755             // Abstract method masks all defaults.
6756             if (vtable_impl != nullptr &&
6757                 vtable_impl->IsAbstract() &&
6758                 !vtable_impl->IsDefaultConflicting()) {
6759               // We need to make this an abstract method but the version in the vtable already is so
6760               // don't do anything.
6761               current_method = vtable_impl;
6762             }
6763             break;
6764           }  // case kAbstractFound
6765         }
6766         if (LIKELY(fill_tables)) {
6767           if (current_method == nullptr && !super_interface) {
6768             // We could not find an implementation for this method and since it is a brand new
6769             // interface we searched the entire vtable (and all default methods) for an
6770             // implementation but couldn't find one. We therefore need to make a miranda method.
6771             //
6772             // Find out if there is already a miranda method we can use.
6773             ArtMethod* miranda_method = FindSameNameAndSignature(interface_name_comparator,
6774                                                                  miranda_methods);
6775             if (miranda_method == nullptr) {
6776               DCHECK(interface_method->IsAbstract()) << PrettyMethod(interface_method);
6777               miranda_method = reinterpret_cast<ArtMethod*>(allocator.Alloc(method_size));
6778               CHECK(miranda_method != nullptr);
6779               // Point the interface table at a phantom slot.
6780               new(miranda_method) ArtMethod(interface_method, image_pointer_size_);
6781               miranda_methods.push_back(miranda_method);
6782             }
6783             current_method = miranda_method;
6784           }
6785 
6786           if (current_method != nullptr) {
6787             // We found a default method implementation. Record it in the iftable and IMT.
6788             method_array->SetElementPtrSize(j, current_method, image_pointer_size_);
6789             SetIMTRef(unimplemented_method,
6790                       imt_conflict_method,
6791                       current_method,
6792                       /*out*/imt_ptr);
6793           }
6794         }
6795       }  // For each method in interface end.
6796     }  // if (num_methods > 0)
6797   }  // For each interface.
6798   const bool has_new_virtuals = !(miranda_methods.empty() &&
6799                                   default_methods.empty() &&
6800                                   default_conflict_methods.empty());
6801   // TODO don't extend virtuals of interface unless necessary (when is it?).
6802   if (has_new_virtuals) {
6803     DCHECK(!is_interface || (default_methods.empty() && miranda_methods.empty()))
6804         << "Interfaces should only have default-conflict methods appended to them.";
6805     VLOG(class_linker) << PrettyClass(klass.Get()) << ": miranda_methods=" << miranda_methods.size()
6806                        << " default_methods=" << default_methods.size()
6807                        << " default_conflict_methods=" << default_conflict_methods.size();
6808     const size_t old_method_count = klass->NumMethods();
6809     const size_t new_method_count = old_method_count +
6810                                     miranda_methods.size() +
6811                                     default_methods.size() +
6812                                     default_conflict_methods.size();
6813     // Attempt to realloc to save RAM if possible.
6814     LengthPrefixedArray<ArtMethod>* old_methods = klass->GetMethodsPtr();
6815     // The Realloced virtual methods aren't visible from the class roots, so there is no issue
6816     // where GCs could attempt to mark stale pointers due to memcpy. And since we overwrite the
6817     // realloced memory with out->CopyFrom, we are guaranteed to have objects in the to space since
6818     // CopyFrom has internal read barriers.
6819     //
6820     // TODO We should maybe move some of this into mirror::Class or at least into another method.
6821     const size_t old_size = LengthPrefixedArray<ArtMethod>::ComputeSize(old_method_count,
6822                                                                         method_size,
6823                                                                         method_alignment);
6824     const size_t new_size = LengthPrefixedArray<ArtMethod>::ComputeSize(new_method_count,
6825                                                                         method_size,
6826                                                                         method_alignment);
6827     const size_t old_methods_ptr_size = (old_methods != nullptr) ? old_size : 0;
6828     auto* methods = reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
6829         runtime->GetLinearAlloc()->Realloc(self, old_methods, old_methods_ptr_size, new_size));
6830     if (UNLIKELY(methods == nullptr)) {
6831       self->AssertPendingOOMException();
6832       self->EndAssertNoThreadSuspension(old_cause);
6833       return false;
6834     }
6835     ScopedArenaUnorderedMap<ArtMethod*, ArtMethod*> move_table(allocator.Adapter());
6836     if (methods != old_methods) {
6837       // Maps from heap allocated miranda method to linear alloc miranda method.
6838       StrideIterator<ArtMethod> out = methods->begin(method_size, method_alignment);
6839       // Copy over the old methods.
6840       for (auto& m : klass->GetMethods(image_pointer_size_)) {
6841         move_table.emplace(&m, &*out);
6842         // The CopyFrom is only necessary to not miss read barriers since Realloc won't do read
6843         // barriers when it copies.
6844         out->CopyFrom(&m, image_pointer_size_);
6845         ++out;
6846       }
6847     }
6848     StrideIterator<ArtMethod> out(methods->begin(method_size, method_alignment) + old_method_count);
6849     // Copy over miranda methods before copying vtable since CopyOf may cause thread suspension and
6850     // we want the roots of the miranda methods to get visited.
6851     for (ArtMethod* mir_method : miranda_methods) {
6852       ArtMethod& new_method = *out;
6853       new_method.CopyFrom(mir_method, image_pointer_size_);
6854       new_method.SetAccessFlags(new_method.GetAccessFlags() | kAccMiranda | kAccCopied);
6855       DCHECK_NE(new_method.GetAccessFlags() & kAccAbstract, 0u)
6856           << "Miranda method should be abstract!";
6857       move_table.emplace(mir_method, &new_method);
6858       ++out;
6859     }
6860     // We need to copy the default methods into our own method table since the runtime requires that
6861     // every method on a class's vtable be in that respective class's virtual method table.
6862     // NOTE This means that two classes might have the same implementation of a method from the same
6863     // interface but will have different ArtMethod*s for them. This also means we cannot compare a
6864     // default method found on a class with one found on the declaring interface directly and must
6865     // look at the declaring class to determine if they are the same.
6866     for (ArtMethod* def_method : default_methods) {
6867       ArtMethod& new_method = *out;
6868       new_method.CopyFrom(def_method, image_pointer_size_);
6869       // Clear the kAccSkipAccessChecks flag if it is present. Since this class hasn't been verified
6870       // yet it shouldn't have methods that are skipping access checks.
6871       // TODO This is rather arbitrary. We should maybe support classes where only some of its
6872       // methods are skip_access_checks.
6873       constexpr uint32_t kSetFlags = kAccDefault | kAccCopied;
6874       constexpr uint32_t kMaskFlags = ~kAccSkipAccessChecks;
6875       new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
6876       move_table.emplace(def_method, &new_method);
6877       ++out;
6878     }
6879     for (ArtMethod* conf_method : default_conflict_methods) {
6880       ArtMethod& new_method = *out;
6881       new_method.CopyFrom(conf_method, image_pointer_size_);
6882       // This is a type of default method (there are default method impls, just a conflict) so mark
6883       // this as a default, non-abstract method, since thats what it is. Also clear the
6884       // kAccSkipAccessChecks bit since this class hasn't been verified yet it shouldn't have
6885       // methods that are skipping access checks.
6886       constexpr uint32_t kSetFlags = kAccDefault | kAccDefaultConflict | kAccCopied;
6887       constexpr uint32_t kMaskFlags = ~(kAccAbstract | kAccSkipAccessChecks);
6888       new_method.SetAccessFlags((new_method.GetAccessFlags() | kSetFlags) & kMaskFlags);
6889       DCHECK(new_method.IsDefaultConflicting());
6890       // The actual method might or might not be marked abstract since we just copied it from a
6891       // (possibly default) interface method. We need to set it entry point to be the bridge so that
6892       // the compiler will not invoke the implementation of whatever method we copied from.
6893       EnsureThrowsInvocationError(&new_method);
6894       move_table.emplace(conf_method, &new_method);
6895       ++out;
6896     }
6897     methods->SetSize(new_method_count);
6898     UpdateClassMethods(klass.Get(), methods);
6899     // Done copying methods, they are all roots in the class now, so we can end the no thread
6900     // suspension assert.
6901     self->EndAssertNoThreadSuspension(old_cause);
6902 
6903     if (fill_tables) {
6904       // Update the vtable to the new method structures. We can skip this for interfaces since they
6905       // do not have vtables.
6906       const size_t old_vtable_count = vtable->GetLength();
6907       const size_t new_vtable_count = old_vtable_count +
6908                                       miranda_methods.size() +
6909                                       default_methods.size() +
6910                                       default_conflict_methods.size();
6911       vtable.Assign(down_cast<mirror::PointerArray*>(vtable->CopyOf(self, new_vtable_count)));
6912       if (UNLIKELY(vtable.Get() == nullptr)) {
6913         self->AssertPendingOOMException();
6914         return false;
6915       }
6916       out = methods->begin(method_size, method_alignment) + old_method_count;
6917       size_t vtable_pos = old_vtable_count;
6918       // Update all the newly copied method's indexes so they denote their placement in the vtable.
6919       for (size_t i = old_method_count; i < new_method_count; ++i) {
6920         // Leave the declaring class alone the method's dex_code_item_offset_ and dex_method_index_
6921         // fields are references into the dex file the method was defined in. Since the ArtMethod
6922         // does not store that information it uses declaring_class_->dex_cache_.
6923         out->SetMethodIndex(0xFFFF & vtable_pos);
6924         vtable->SetElementPtrSize(vtable_pos, &*out, image_pointer_size_);
6925         ++out;
6926         ++vtable_pos;
6927       }
6928       CHECK_EQ(vtable_pos, new_vtable_count);
6929       // Update old vtable methods. We use the default_translations map to figure out what each
6930       // vtable entry should be updated to, if they need to be at all.
6931       for (size_t i = 0; i < old_vtable_count; ++i) {
6932         ArtMethod* translated_method = vtable->GetElementPtrSize<ArtMethod*>(
6933               i, image_pointer_size_);
6934         // Try and find what we need to change this method to.
6935         auto translation_it = default_translations.find(i);
6936         bool found_translation = false;
6937         if (translation_it != default_translations.end()) {
6938           if (translation_it->second.IsInConflict()) {
6939             // Find which conflict method we are to use for this method.
6940             MethodNameAndSignatureComparator old_method_comparator(
6941                 translated_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6942             ArtMethod* new_conflict_method = FindSameNameAndSignature(old_method_comparator,
6943                                                                       default_conflict_methods);
6944             CHECK(new_conflict_method != nullptr) << "Expected a conflict method!";
6945             translated_method = new_conflict_method;
6946           } else if (translation_it->second.IsAbstract()) {
6947             // Find which miranda method we are to use for this method.
6948             MethodNameAndSignatureComparator old_method_comparator(
6949                 translated_method->GetInterfaceMethodIfProxy(image_pointer_size_));
6950             ArtMethod* miranda_method = FindSameNameAndSignature(old_method_comparator,
6951                                                                 miranda_methods);
6952             DCHECK(miranda_method != nullptr);
6953             translated_method = miranda_method;
6954           } else {
6955             // Normal default method (changed from an older default or abstract interface method).
6956             DCHECK(translation_it->second.IsTranslation());
6957             translated_method = translation_it->second.GetTranslation();
6958           }
6959           found_translation = true;
6960         }
6961         DCHECK(translated_method != nullptr);
6962         auto it = move_table.find(translated_method);
6963         if (it != move_table.end()) {
6964           auto* new_method = it->second;
6965           DCHECK(new_method != nullptr);
6966           vtable->SetElementPtrSize(i, new_method, image_pointer_size_);
6967         } else {
6968           // If it was not going to be updated we wouldn't have put it into the default_translations
6969           // map.
6970           CHECK(!found_translation) << "We were asked to update this vtable entry. Must not fail.";
6971         }
6972       }
6973       klass->SetVTable(vtable.Get());
6974 
6975       // Go fix up all the stale iftable pointers.
6976       for (size_t i = 0; i < ifcount; ++i) {
6977         for (size_t j = 0, count = iftable->GetMethodArrayCount(i); j < count; ++j) {
6978           auto* method_array = iftable->GetMethodArray(i);
6979           auto* m = method_array->GetElementPtrSize<ArtMethod*>(j, image_pointer_size_);
6980           DCHECK(m != nullptr) << PrettyClass(klass.Get());
6981           auto it = move_table.find(m);
6982           if (it != move_table.end()) {
6983             auto* new_m = it->second;
6984             DCHECK(new_m != nullptr) << PrettyClass(klass.Get());
6985             method_array->SetElementPtrSize(j, new_m, image_pointer_size_);
6986           }
6987         }
6988       }
6989 
6990       // Fix up IMT next
6991       for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
6992         auto it = move_table.find(out_imt[i]);
6993         if (it != move_table.end()) {
6994           out_imt[i] = it->second;
6995         }
6996       }
6997     }
6998 
6999     // Check that there are no stale methods are in the dex cache array.
7000     if (kIsDebugBuild) {
7001       auto* resolved_methods = klass->GetDexCache()->GetResolvedMethods();
7002       for (size_t i = 0, count = klass->GetDexCache()->NumResolvedMethods(); i < count; ++i) {
7003         auto* m = mirror::DexCache::GetElementPtrSize(resolved_methods, i, image_pointer_size_);
7004         CHECK(move_table.find(m) == move_table.end() ||
7005               // The original versions of copied methods will still be present so allow those too.
7006               // Note that if the first check passes this might fail to GetDeclaringClass().
7007               std::find_if(m->GetDeclaringClass()->GetMethods(image_pointer_size_).begin(),
7008                            m->GetDeclaringClass()->GetMethods(image_pointer_size_).end(),
7009                            [m] (ArtMethod& meth) {
7010                              return &meth == m;
7011                            }) != m->GetDeclaringClass()->GetMethods(image_pointer_size_).end())
7012             << "Obsolete methods " << PrettyMethod(m) << " is in dex cache!";
7013       }
7014     }
7015     // Put some random garbage in old methods to help find stale pointers.
7016     if (methods != old_methods && old_methods != nullptr && kIsDebugBuild) {
7017       // Need to make sure the GC is not running since it could be scanning the methods we are
7018       // about to overwrite.
7019       ScopedThreadStateChange tsc(self, kSuspended);
7020       gc::ScopedGCCriticalSection gcs(self,
7021                                       gc::kGcCauseClassLinker,
7022                                       gc::kCollectorTypeClassLinker);
7023       memset(old_methods, 0xFEu, old_size);
7024     }
7025   } else {
7026     self->EndAssertNoThreadSuspension(old_cause);
7027   }
7028   if (kIsDebugBuild && !is_interface) {
7029     SanityCheckVTable(klass, image_pointer_size_);
7030   }
7031   return true;
7032 }
7033 
LinkInstanceFields(Thread * self,Handle<mirror::Class> klass)7034 bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
7035   CHECK(klass.Get() != nullptr);
7036   return LinkFields(self, klass, false, nullptr);
7037 }
7038 
LinkStaticFields(Thread * self,Handle<mirror::Class> klass,size_t * class_size)7039 bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
7040   CHECK(klass.Get() != nullptr);
7041   return LinkFields(self, klass, true, class_size);
7042 }
7043 
7044 struct LinkFieldsComparator {
SHARED_REQUIRESart::LinkFieldsComparator7045   explicit LinkFieldsComparator() SHARED_REQUIRES(Locks::mutator_lock_) {
7046   }
7047   // No thread safety analysis as will be called from STL. Checked lock held in constructor.
operator ()art::LinkFieldsComparator7048   bool operator()(ArtField* field1, ArtField* field2)
7049       NO_THREAD_SAFETY_ANALYSIS {
7050     // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit.
7051     Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
7052     Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
7053     if (type1 != type2) {
7054       if (type1 == Primitive::kPrimNot) {
7055         // Reference always goes first.
7056         return true;
7057       }
7058       if (type2 == Primitive::kPrimNot) {
7059         // Reference always goes first.
7060         return false;
7061       }
7062       size_t size1 = Primitive::ComponentSize(type1);
7063       size_t size2 = Primitive::ComponentSize(type2);
7064       if (size1 != size2) {
7065         // Larger primitive types go first.
7066         return size1 > size2;
7067       }
7068       // Primitive types differ but sizes match. Arbitrarily order by primitive type.
7069       return type1 < type2;
7070     }
7071     // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
7072     // by name and for equal names by type id index.
7073     // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
7074     return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
7075   }
7076 };
7077 
LinkFields(Thread * self,Handle<mirror::Class> klass,bool is_static,size_t * class_size)7078 bool ClassLinker::LinkFields(Thread* self,
7079                              Handle<mirror::Class> klass,
7080                              bool is_static,
7081                              size_t* class_size) {
7082   self->AllowThreadSuspension();
7083   const size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
7084   LengthPrefixedArray<ArtField>* const fields = is_static ? klass->GetSFieldsPtr() :
7085       klass->GetIFieldsPtr();
7086 
7087   // Initialize field_offset
7088   MemberOffset field_offset(0);
7089   if (is_static) {
7090     field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_);
7091   } else {
7092     mirror::Class* super_class = klass->GetSuperClass();
7093     if (super_class != nullptr) {
7094       CHECK(super_class->IsResolved())
7095           << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
7096       field_offset = MemberOffset(super_class->GetObjectSize());
7097     }
7098   }
7099 
7100   CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
7101 
7102   // we want a relatively stable order so that adding new fields
7103   // minimizes disruption of C++ version such as Class and Method.
7104   //
7105   // The overall sort order order is:
7106   // 1) All object reference fields, sorted alphabetically.
7107   // 2) All java long (64-bit) integer fields, sorted alphabetically.
7108   // 3) All java double (64-bit) floating point fields, sorted alphabetically.
7109   // 4) All java int (32-bit) integer fields, sorted alphabetically.
7110   // 5) All java float (32-bit) floating point fields, sorted alphabetically.
7111   // 6) All java char (16-bit) integer fields, sorted alphabetically.
7112   // 7) All java short (16-bit) integer fields, sorted alphabetically.
7113   // 8) All java boolean (8-bit) integer fields, sorted alphabetically.
7114   // 9) All java byte (8-bit) integer fields, sorted alphabetically.
7115   //
7116   // Once the fields are sorted in this order we will attempt to fill any gaps that might be present
7117   // in the memory layout of the structure. See ShuffleForward for how this is done.
7118   std::deque<ArtField*> grouped_and_sorted_fields;
7119   const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
7120       "Naked ArtField references in deque");
7121   for (size_t i = 0; i < num_fields; i++) {
7122     grouped_and_sorted_fields.push_back(&fields->At(i));
7123   }
7124   std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
7125             LinkFieldsComparator());
7126 
7127   // References should be at the front.
7128   size_t current_field = 0;
7129   size_t num_reference_fields = 0;
7130   FieldGaps gaps;
7131 
7132   for (; current_field < num_fields; current_field++) {
7133     ArtField* field = grouped_and_sorted_fields.front();
7134     Primitive::Type type = field->GetTypeAsPrimitiveType();
7135     bool isPrimitive = type != Primitive::kPrimNot;
7136     if (isPrimitive) {
7137       break;  // past last reference, move on to the next phase
7138     }
7139     if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
7140         field_offset.Uint32Value()))) {
7141       MemberOffset old_offset = field_offset;
7142       field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
7143       AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
7144     }
7145     DCHECK_ALIGNED(field_offset.Uint32Value(), sizeof(mirror::HeapReference<mirror::Object>));
7146     grouped_and_sorted_fields.pop_front();
7147     num_reference_fields++;
7148     field->SetOffset(field_offset);
7149     field_offset = MemberOffset(field_offset.Uint32Value() +
7150                                 sizeof(mirror::HeapReference<mirror::Object>));
7151   }
7152   // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
7153   // otherwise we could end up with suboptimal gap fills.
7154   ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7155   ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7156   ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7157   ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
7158   CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
7159       " fields.";
7160   self->EndAssertNoThreadSuspension(old_no_suspend_cause);
7161 
7162   // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
7163   if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
7164     // We know there are no non-reference fields in the Reference classes, and we know
7165     // that 'referent' is alphabetically last, so this is easy...
7166     CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
7167     CHECK_STREQ(fields->At(num_fields - 1).GetName(), "referent")
7168         << PrettyClass(klass.Get());
7169     --num_reference_fields;
7170   }
7171 
7172   size_t size = field_offset.Uint32Value();
7173   // Update klass
7174   if (is_static) {
7175     klass->SetNumReferenceStaticFields(num_reference_fields);
7176     *class_size = size;
7177   } else {
7178     klass->SetNumReferenceInstanceFields(num_reference_fields);
7179     mirror::Class* super_class = klass->GetSuperClass();
7180     if (num_reference_fields == 0 || super_class == nullptr) {
7181       // object has one reference field, klass, but we ignore it since we always visit the class.
7182       // super_class is null iff the class is java.lang.Object.
7183       if (super_class == nullptr ||
7184           (super_class->GetClassFlags() & mirror::kClassFlagNoReferenceFields) != 0) {
7185         klass->SetClassFlags(klass->GetClassFlags() | mirror::kClassFlagNoReferenceFields);
7186       }
7187     }
7188     if (kIsDebugBuild) {
7189       DCHECK_EQ(super_class == nullptr, klass->DescriptorEquals("Ljava/lang/Object;"));
7190       size_t total_reference_instance_fields = 0;
7191       mirror::Class* cur_super = klass.Get();
7192       while (cur_super != nullptr) {
7193         total_reference_instance_fields += cur_super->NumReferenceInstanceFieldsDuringLinking();
7194         cur_super = cur_super->GetSuperClass();
7195       }
7196       if (super_class == nullptr) {
7197         CHECK_EQ(total_reference_instance_fields, 1u) << PrettyDescriptor(klass.Get());
7198       } else {
7199         // Check that there is at least num_reference_fields other than Object.class.
7200         CHECK_GE(total_reference_instance_fields, 1u + num_reference_fields)
7201             << PrettyClass(klass.Get());
7202       }
7203     }
7204     if (!klass->IsVariableSize()) {
7205       std::string temp;
7206       DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
7207       size_t previous_size = klass->GetObjectSize();
7208       if (previous_size != 0) {
7209         // Make sure that we didn't originally have an incorrect size.
7210         CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
7211       }
7212       klass->SetObjectSize(size);
7213     }
7214   }
7215 
7216   if (kIsDebugBuild) {
7217     // Make sure that the fields array is ordered by name but all reference
7218     // offsets are at the beginning as far as alignment allows.
7219     MemberOffset start_ref_offset = is_static
7220         ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking(image_pointer_size_)
7221         : klass->GetFirstReferenceInstanceFieldOffset();
7222     MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
7223                                 num_reference_fields *
7224                                     sizeof(mirror::HeapReference<mirror::Object>));
7225     MemberOffset current_ref_offset = start_ref_offset;
7226     for (size_t i = 0; i < num_fields; i++) {
7227       ArtField* field = &fields->At(i);
7228       VLOG(class_linker) << "LinkFields: " << (is_static ? "static" : "instance")
7229           << " class=" << PrettyClass(klass.Get()) << " field=" << PrettyField(field) << " offset="
7230           << field->GetOffsetDuringLinking();
7231       if (i != 0) {
7232         ArtField* const prev_field = &fields->At(i - 1);
7233         // NOTE: The field names can be the same. This is not possible in the Java language
7234         // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
7235         DCHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
7236       }
7237       Primitive::Type type = field->GetTypeAsPrimitiveType();
7238       bool is_primitive = type != Primitive::kPrimNot;
7239       if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
7240           strcmp("referent", field->GetName()) == 0) {
7241         is_primitive = true;  // We lied above, so we have to expect a lie here.
7242       }
7243       MemberOffset offset = field->GetOffsetDuringLinking();
7244       if (is_primitive) {
7245         if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
7246           // Shuffled before references.
7247           size_t type_size = Primitive::ComponentSize(type);
7248           CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
7249           CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
7250           CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
7251           CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
7252         }
7253       } else {
7254         CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
7255         current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
7256                                           sizeof(mirror::HeapReference<mirror::Object>));
7257       }
7258     }
7259     CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
7260   }
7261   return true;
7262 }
7263 
7264 //  Set the bitmap of reference instance field offsets.
CreateReferenceInstanceOffsets(Handle<mirror::Class> klass)7265 void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
7266   uint32_t reference_offsets = 0;
7267   mirror::Class* super_class = klass->GetSuperClass();
7268   // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
7269   if (super_class != nullptr) {
7270     reference_offsets = super_class->GetReferenceInstanceOffsets();
7271     // Compute reference offsets unless our superclass overflowed.
7272     if (reference_offsets != mirror::Class::kClassWalkSuper) {
7273       size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
7274       if (num_reference_fields != 0u) {
7275         // All of the fields that contain object references are guaranteed be grouped in memory
7276         // starting at an appropriately aligned address after super class object data.
7277         uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
7278                                         sizeof(mirror::HeapReference<mirror::Object>));
7279         uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
7280             sizeof(mirror::HeapReference<mirror::Object>);
7281         if (start_bit + num_reference_fields > 32) {
7282           reference_offsets = mirror::Class::kClassWalkSuper;
7283         } else {
7284           reference_offsets |= (0xffffffffu << start_bit) &
7285                                (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
7286         }
7287       }
7288     }
7289   }
7290   klass->SetReferenceInstanceOffsets(reference_offsets);
7291 }
7292 
ResolveString(const DexFile & dex_file,uint32_t string_idx,Handle<mirror::DexCache> dex_cache)7293 mirror::String* ClassLinker::ResolveString(const DexFile& dex_file,
7294                                            uint32_t string_idx,
7295                                            Handle<mirror::DexCache> dex_cache) {
7296   DCHECK(dex_cache.Get() != nullptr);
7297   mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
7298   if (resolved != nullptr) {
7299     return resolved;
7300   }
7301   uint32_t utf16_length;
7302   const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
7303   mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
7304   dex_cache->SetResolvedString(string_idx, string);
7305   return string;
7306 }
7307 
LookupString(const DexFile & dex_file,uint32_t string_idx,Handle<mirror::DexCache> dex_cache)7308 mirror::String* ClassLinker::LookupString(const DexFile& dex_file,
7309                                           uint32_t string_idx,
7310                                           Handle<mirror::DexCache> dex_cache) {
7311   DCHECK(dex_cache.Get() != nullptr);
7312   mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
7313   if (resolved != nullptr) {
7314     return resolved;
7315   }
7316   uint32_t utf16_length;
7317   const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
7318   mirror::String* string = intern_table_->LookupStrong(Thread::Current(), utf16_length, utf8_data);
7319   if (string != nullptr) {
7320     dex_cache->SetResolvedString(string_idx, string);
7321   }
7322   return string;
7323 }
7324 
ResolveType(const DexFile & dex_file,uint16_t type_idx,mirror::Class * referrer)7325 mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
7326                                         uint16_t type_idx,
7327                                         mirror::Class* referrer) {
7328   StackHandleScope<2> hs(Thread::Current());
7329   Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
7330   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
7331   return ResolveType(dex_file, type_idx, dex_cache, class_loader);
7332 }
7333 
ResolveType(const DexFile & dex_file,uint16_t type_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)7334 mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file,
7335                                         uint16_t type_idx,
7336                                         Handle<mirror::DexCache> dex_cache,
7337                                         Handle<mirror::ClassLoader> class_loader) {
7338   DCHECK(dex_cache.Get() != nullptr);
7339   mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
7340   if (resolved == nullptr) {
7341     Thread* self = Thread::Current();
7342     const char* descriptor = dex_file.StringByTypeIdx(type_idx);
7343     resolved = FindClass(self, descriptor, class_loader);
7344     if (resolved != nullptr) {
7345       // TODO: we used to throw here if resolved's class loader was not the
7346       //       boot class loader. This was to permit different classes with the
7347       //       same name to be loaded simultaneously by different loaders
7348       dex_cache->SetResolvedType(type_idx, resolved);
7349     } else {
7350       CHECK(self->IsExceptionPending())
7351           << "Expected pending exception for failed resolution of: " << descriptor;
7352       // Convert a ClassNotFoundException to a NoClassDefFoundError.
7353       StackHandleScope<1> hs(self);
7354       Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException()));
7355       if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
7356         DCHECK(resolved == nullptr);  // No Handle needed to preserve resolved.
7357         self->ClearException();
7358         ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
7359         self->GetException()->SetCause(cause.Get());
7360       }
7361     }
7362   }
7363   DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
7364       << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
7365   return resolved;
7366 }
7367 
7368 template <ClassLinker::ResolveMode kResolveMode>
ResolveMethod(const DexFile & dex_file,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,ArtMethod * referrer,InvokeType type)7369 ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
7370                                       uint32_t method_idx,
7371                                       Handle<mirror::DexCache> dex_cache,
7372                                       Handle<mirror::ClassLoader> class_loader,
7373                                       ArtMethod* referrer,
7374                                       InvokeType type) {
7375   DCHECK(dex_cache.Get() != nullptr);
7376   // Check for hit in the dex cache.
7377   ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
7378   if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
7379     DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
7380     if (kResolveMode == ClassLinker::kForceICCECheck) {
7381       if (resolved->CheckIncompatibleClassChange(type)) {
7382         ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
7383         return nullptr;
7384       }
7385     }
7386     return resolved;
7387   }
7388   // Fail, get the declaring class.
7389   const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7390   mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
7391   if (klass == nullptr) {
7392     DCHECK(Thread::Current()->IsExceptionPending());
7393     return nullptr;
7394   }
7395   // Scan using method_idx, this saves string compares but will only hit for matching dex
7396   // caches/files.
7397   switch (type) {
7398     case kDirect:  // Fall-through.
7399     case kStatic:
7400       resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7401       DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
7402       break;
7403     case kInterface:
7404       // We have to check whether the method id really belongs to an interface (dex static bytecode
7405       // constraint A15). Otherwise you must not invoke-interface on it.
7406       //
7407       // This is not symmetric to A12-A14 (direct, static, virtual), as using FindInterfaceMethod
7408       // assumes that the given type is an interface, and will check the interface table if the
7409       // method isn't declared in the class. So it may find an interface method (usually by name
7410       // in the handling below, but we do the constraint check early). In that case,
7411       // CheckIncompatibleClassChange will succeed (as it is called on an interface method)
7412       // unexpectedly.
7413       // Example:
7414       //    interface I {
7415       //      foo()
7416       //    }
7417       //    class A implements I {
7418       //      ...
7419       //    }
7420       //    class B extends A {
7421       //      ...
7422       //    }
7423       //    invoke-interface B.foo
7424       //      -> FindInterfaceMethod finds I.foo (interface method), not A.foo (miranda method)
7425       if (UNLIKELY(!klass->IsInterface())) {
7426         ThrowIncompatibleClassChangeError(klass,
7427                                           "Found class %s, but interface was expected",
7428                                           PrettyDescriptor(klass).c_str());
7429         return nullptr;
7430       } else {
7431         resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7432         DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
7433       }
7434       break;
7435     case kSuper:
7436       if (klass->IsInterface()) {
7437         resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7438       } else {
7439         resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7440       }
7441       break;
7442     case kVirtual:
7443       resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7444       break;
7445     default:
7446       LOG(FATAL) << "Unreachable - invocation type: " << type;
7447       UNREACHABLE();
7448   }
7449   if (resolved == nullptr) {
7450     // Search by name, which works across dex files.
7451     const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7452     const Signature signature = dex_file.GetMethodSignature(method_id);
7453     switch (type) {
7454       case kDirect:  // Fall-through.
7455       case kStatic:
7456         resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
7457         DCHECK(resolved == nullptr || resolved->GetDeclaringClassUnchecked() != nullptr);
7458         break;
7459       case kInterface:
7460         resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7461         DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
7462         break;
7463       case kSuper:
7464         if (klass->IsInterface()) {
7465           resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7466         } else {
7467           resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7468         }
7469         break;
7470       case kVirtual:
7471         resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7472         break;
7473     }
7474   }
7475   // If we found a method, check for incompatible class changes.
7476   if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
7477     // Be a good citizen and update the dex cache to speed subsequent calls.
7478     dex_cache->SetResolvedMethod(method_idx, resolved, image_pointer_size_);
7479     return resolved;
7480   } else {
7481     // If we had a method, it's an incompatible-class-change error.
7482     if (resolved != nullptr) {
7483       ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer);
7484     } else {
7485       // We failed to find the method which means either an access error, an incompatible class
7486       // change, or no such method. First try to find the method among direct and virtual methods.
7487       const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
7488       const Signature signature = dex_file.GetMethodSignature(method_id);
7489       switch (type) {
7490         case kDirect:
7491         case kStatic:
7492           resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7493           // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
7494           //       have had a resolved method before, which triggers the "true" branch above.
7495           break;
7496         case kInterface:
7497         case kVirtual:
7498         case kSuper:
7499           resolved = klass->FindDirectMethod(name, signature, image_pointer_size_);
7500           break;
7501       }
7502 
7503       // If we found something, check that it can be accessed by the referrer.
7504       bool exception_generated = false;
7505       if (resolved != nullptr && referrer != nullptr) {
7506         mirror::Class* methods_class = resolved->GetDeclaringClass();
7507         mirror::Class* referring_class = referrer->GetDeclaringClass();
7508         if (!referring_class->CanAccess(methods_class)) {
7509           ThrowIllegalAccessErrorClassForMethodDispatch(referring_class,
7510                                                         methods_class,
7511                                                         resolved,
7512                                                         type);
7513           exception_generated = true;
7514         } else if (!referring_class->CanAccessMember(methods_class, resolved->GetAccessFlags())) {
7515           ThrowIllegalAccessErrorMethod(referring_class, resolved);
7516           exception_generated = true;
7517         }
7518       }
7519       if (!exception_generated) {
7520         // Otherwise, throw an IncompatibleClassChangeError if we found something, and check
7521         // interface methods and throw if we find the method there. If we find nothing, throw a
7522         // NoSuchMethodError.
7523         switch (type) {
7524           case kDirect:
7525           case kStatic:
7526             if (resolved != nullptr) {
7527               ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
7528             } else {
7529               resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7530               if (resolved != nullptr) {
7531                 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
7532               } else {
7533                 ThrowNoSuchMethodError(type, klass, name, signature);
7534               }
7535             }
7536             break;
7537           case kInterface:
7538             if (resolved != nullptr) {
7539               ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
7540             } else {
7541               resolved = klass->FindVirtualMethod(name, signature, image_pointer_size_);
7542               if (resolved != nullptr) {
7543                 ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
7544               } else {
7545                 ThrowNoSuchMethodError(type, klass, name, signature);
7546               }
7547             }
7548             break;
7549           case kSuper:
7550             if (resolved != nullptr) {
7551               ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
7552             } else {
7553               ThrowNoSuchMethodError(type, klass, name, signature);
7554             }
7555             break;
7556           case kVirtual:
7557             if (resolved != nullptr) {
7558               ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
7559             } else {
7560               resolved = klass->FindInterfaceMethod(name, signature, image_pointer_size_);
7561               if (resolved != nullptr) {
7562                 ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
7563               } else {
7564                 ThrowNoSuchMethodError(type, klass, name, signature);
7565               }
7566             }
7567             break;
7568         }
7569       }
7570     }
7571     Thread::Current()->AssertPendingException();
7572     return nullptr;
7573   }
7574 }
7575 
ResolveMethodWithoutInvokeType(const DexFile & dex_file,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)7576 ArtMethod* ClassLinker::ResolveMethodWithoutInvokeType(const DexFile& dex_file,
7577                                                        uint32_t method_idx,
7578                                                        Handle<mirror::DexCache> dex_cache,
7579                                                        Handle<mirror::ClassLoader> class_loader) {
7580   ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx, image_pointer_size_);
7581   if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
7582     DCHECK(resolved->GetDeclaringClassUnchecked() != nullptr) << resolved->GetDexMethodIndex();
7583     return resolved;
7584   }
7585   // Fail, get the declaring class.
7586   const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7587   mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
7588   if (klass == nullptr) {
7589     Thread::Current()->AssertPendingException();
7590     return nullptr;
7591   }
7592   if (klass->IsInterface()) {
7593     LOG(FATAL) << "ResolveAmbiguousMethod: unexpected method in interface: " << PrettyClass(klass);
7594     return nullptr;
7595   }
7596 
7597   // Search both direct and virtual methods
7598   resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7599   if (resolved == nullptr) {
7600     resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx, image_pointer_size_);
7601   }
7602 
7603   return resolved;
7604 }
7605 
ResolveField(const DexFile & dex_file,uint32_t field_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,bool is_static)7606 ArtField* ClassLinker::ResolveField(const DexFile& dex_file,
7607                                     uint32_t field_idx,
7608                                     Handle<mirror::DexCache> dex_cache,
7609                                     Handle<mirror::ClassLoader> class_loader,
7610                                     bool is_static) {
7611   DCHECK(dex_cache.Get() != nullptr);
7612   ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
7613   if (resolved != nullptr) {
7614     return resolved;
7615   }
7616   const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
7617   Thread* const self = Thread::Current();
7618   StackHandleScope<1> hs(self);
7619   Handle<mirror::Class> klass(
7620       hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
7621   if (klass.Get() == nullptr) {
7622     DCHECK(Thread::Current()->IsExceptionPending());
7623     return nullptr;
7624   }
7625 
7626   if (is_static) {
7627     resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
7628   } else {
7629     resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
7630   }
7631 
7632   if (resolved == nullptr) {
7633     const char* name = dex_file.GetFieldName(field_id);
7634     const char* type = dex_file.GetFieldTypeDescriptor(field_id);
7635     if (is_static) {
7636       resolved = mirror::Class::FindStaticField(self, klass, name, type);
7637     } else {
7638       resolved = klass->FindInstanceField(name, type);
7639     }
7640     if (resolved == nullptr) {
7641       ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
7642       return nullptr;
7643     }
7644   }
7645   dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
7646   return resolved;
7647 }
7648 
ResolveFieldJLS(const DexFile & dex_file,uint32_t field_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)7649 ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
7650                                        uint32_t field_idx,
7651                                        Handle<mirror::DexCache> dex_cache,
7652                                        Handle<mirror::ClassLoader> class_loader) {
7653   DCHECK(dex_cache.Get() != nullptr);
7654   ArtField* resolved = dex_cache->GetResolvedField(field_idx, image_pointer_size_);
7655   if (resolved != nullptr) {
7656     return resolved;
7657   }
7658   const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
7659   Thread* self = Thread::Current();
7660   StackHandleScope<1> hs(self);
7661   Handle<mirror::Class> klass(
7662       hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
7663   if (klass.Get() == nullptr) {
7664     DCHECK(Thread::Current()->IsExceptionPending());
7665     return nullptr;
7666   }
7667 
7668   StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
7669   StringPiece type(dex_file.StringDataByIdx(
7670       dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
7671   resolved = mirror::Class::FindField(self, klass, name, type);
7672   if (resolved != nullptr) {
7673     dex_cache->SetResolvedField(field_idx, resolved, image_pointer_size_);
7674   } else {
7675     ThrowNoSuchFieldError("", klass.Get(), type, name);
7676   }
7677   return resolved;
7678 }
7679 
MethodShorty(uint32_t method_idx,ArtMethod * referrer,uint32_t * length)7680 const char* ClassLinker::MethodShorty(uint32_t method_idx,
7681                                       ArtMethod* referrer,
7682                                       uint32_t* length) {
7683   mirror::Class* declaring_class = referrer->GetDeclaringClass();
7684   mirror::DexCache* dex_cache = declaring_class->GetDexCache();
7685   const DexFile& dex_file = *dex_cache->GetDexFile();
7686   const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
7687   return dex_file.GetMethodShorty(method_id, length);
7688 }
7689 
7690 class DumpClassVisitor : public ClassVisitor {
7691  public:
DumpClassVisitor(int flags)7692   explicit DumpClassVisitor(int flags) : flags_(flags) {}
7693 
operator ()(mirror::Class * klass)7694   bool operator()(mirror::Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
7695     klass->DumpClass(LOG(ERROR), flags_);
7696     return true;
7697   }
7698 
7699  private:
7700   const int flags_;
7701 };
7702 
DumpAllClasses(int flags)7703 void ClassLinker::DumpAllClasses(int flags) {
7704   DumpClassVisitor visitor(flags);
7705   VisitClasses(&visitor);
7706 }
7707 
CreateOatMethod(const void * code)7708 static OatFile::OatMethod CreateOatMethod(const void* code) {
7709   CHECK(code != nullptr);
7710   const uint8_t* base = reinterpret_cast<const uint8_t*>(code);  // Base of data points at code.
7711   base -= sizeof(void*);  // Move backward so that code_offset != 0.
7712   const uint32_t code_offset = sizeof(void*);
7713   return OatFile::OatMethod(base, code_offset);
7714 }
7715 
IsQuickResolutionStub(const void * entry_point) const7716 bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
7717   return (entry_point == GetQuickResolutionStub()) ||
7718       (quick_resolution_trampoline_ == entry_point);
7719 }
7720 
IsQuickToInterpreterBridge(const void * entry_point) const7721 bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
7722   return (entry_point == GetQuickToInterpreterBridge()) ||
7723       (quick_to_interpreter_bridge_trampoline_ == entry_point);
7724 }
7725 
IsQuickGenericJniStub(const void * entry_point) const7726 bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
7727   return (entry_point == GetQuickGenericJniStub()) ||
7728       (quick_generic_jni_trampoline_ == entry_point);
7729 }
7730 
GetRuntimeQuickGenericJniStub() const7731 const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
7732   return GetQuickGenericJniStub();
7733 }
7734 
SetEntryPointsToCompiledCode(ArtMethod * method,const void * method_code) const7735 void ClassLinker::SetEntryPointsToCompiledCode(ArtMethod* method,
7736                                                const void* method_code) const {
7737   OatFile::OatMethod oat_method = CreateOatMethod(method_code);
7738   oat_method.LinkMethod(method);
7739 }
7740 
SetEntryPointsToInterpreter(ArtMethod * method) const7741 void ClassLinker::SetEntryPointsToInterpreter(ArtMethod* method) const {
7742   if (!method->IsNative()) {
7743     method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
7744   } else {
7745     const void* quick_method_code = GetQuickGenericJniStub();
7746     OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code);
7747     oat_method.LinkMethod(method);
7748   }
7749 }
7750 
DumpForSigQuit(std::ostream & os)7751 void ClassLinker::DumpForSigQuit(std::ostream& os) {
7752   ScopedObjectAccess soa(Thread::Current());
7753   if (dex_cache_boot_image_class_lookup_required_) {
7754     AddBootImageClassesToClassTable();
7755   }
7756   ReaderMutexLock mu(soa.Self(), *Locks::classlinker_classes_lock_);
7757   os << "Zygote loaded classes=" << NumZygoteClasses() << " post zygote classes="
7758      << NumNonZygoteClasses() << "\n";
7759 }
7760 
7761 class CountClassesVisitor : public ClassLoaderVisitor {
7762  public:
CountClassesVisitor()7763   CountClassesVisitor() : num_zygote_classes(0), num_non_zygote_classes(0) {}
7764 
Visit(mirror::ClassLoader * class_loader)7765   void Visit(mirror::ClassLoader* class_loader)
7766       SHARED_REQUIRES(Locks::classlinker_classes_lock_, Locks::mutator_lock_) OVERRIDE {
7767     ClassTable* const class_table = class_loader->GetClassTable();
7768     if (class_table != nullptr) {
7769       num_zygote_classes += class_table->NumZygoteClasses();
7770       num_non_zygote_classes += class_table->NumNonZygoteClasses();
7771     }
7772   }
7773 
7774   size_t num_zygote_classes;
7775   size_t num_non_zygote_classes;
7776 };
7777 
NumZygoteClasses() const7778 size_t ClassLinker::NumZygoteClasses() const {
7779   CountClassesVisitor visitor;
7780   VisitClassLoaders(&visitor);
7781   return visitor.num_zygote_classes + boot_class_table_.NumZygoteClasses();
7782 }
7783 
NumNonZygoteClasses() const7784 size_t ClassLinker::NumNonZygoteClasses() const {
7785   CountClassesVisitor visitor;
7786   VisitClassLoaders(&visitor);
7787   return visitor.num_non_zygote_classes + boot_class_table_.NumNonZygoteClasses();
7788 }
7789 
NumLoadedClasses()7790 size_t ClassLinker::NumLoadedClasses() {
7791   if (dex_cache_boot_image_class_lookup_required_) {
7792     AddBootImageClassesToClassTable();
7793   }
7794   ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
7795   // Only return non zygote classes since these are the ones which apps which care about.
7796   return NumNonZygoteClasses();
7797 }
7798 
GetClassesLockOwner()7799 pid_t ClassLinker::GetClassesLockOwner() {
7800   return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
7801 }
7802 
GetDexLockOwner()7803 pid_t ClassLinker::GetDexLockOwner() {
7804   return dex_lock_.GetExclusiveOwnerTid();
7805 }
7806 
SetClassRoot(ClassRoot class_root,mirror::Class * klass)7807 void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
7808   DCHECK(!init_done_);
7809 
7810   DCHECK(klass != nullptr);
7811   DCHECK(klass->GetClassLoader() == nullptr);
7812 
7813   mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
7814   DCHECK(class_roots != nullptr);
7815   DCHECK(class_roots->Get(class_root) == nullptr);
7816   class_roots->Set<false>(class_root, klass);
7817 }
7818 
GetClassRootDescriptor(ClassRoot class_root)7819 const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
7820   static const char* class_roots_descriptors[] = {
7821     "Ljava/lang/Class;",
7822     "Ljava/lang/Object;",
7823     "[Ljava/lang/Class;",
7824     "[Ljava/lang/Object;",
7825     "Ljava/lang/String;",
7826     "Ljava/lang/DexCache;",
7827     "Ljava/lang/ref/Reference;",
7828     "Ljava/lang/reflect/Constructor;",
7829     "Ljava/lang/reflect/Field;",
7830     "Ljava/lang/reflect/Method;",
7831     "Ljava/lang/reflect/Proxy;",
7832     "[Ljava/lang/String;",
7833     "[Ljava/lang/reflect/Constructor;",
7834     "[Ljava/lang/reflect/Field;",
7835     "[Ljava/lang/reflect/Method;",
7836     "Ljava/lang/ClassLoader;",
7837     "Ljava/lang/Throwable;",
7838     "Ljava/lang/ClassNotFoundException;",
7839     "Ljava/lang/StackTraceElement;",
7840     "Z",
7841     "B",
7842     "C",
7843     "D",
7844     "F",
7845     "I",
7846     "J",
7847     "S",
7848     "V",
7849     "[Z",
7850     "[B",
7851     "[C",
7852     "[D",
7853     "[F",
7854     "[I",
7855     "[J",
7856     "[S",
7857     "[Ljava/lang/StackTraceElement;",
7858   };
7859   static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
7860                 "Mismatch between class descriptors and class-root enum");
7861 
7862   const char* descriptor = class_roots_descriptors[class_root];
7863   CHECK(descriptor != nullptr);
7864   return descriptor;
7865 }
7866 
CreatePathClassLoader(Thread * self,const std::vector<const DexFile * > & dex_files)7867 jobject ClassLinker::CreatePathClassLoader(Thread* self,
7868                                            const std::vector<const DexFile*>& dex_files) {
7869   // SOAAlreadyRunnable is protected, and we need something to add a global reference.
7870   // We could move the jobject to the callers, but all call-sites do this...
7871   ScopedObjectAccessUnchecked soa(self);
7872 
7873   // For now, create a libcore-level DexFile for each ART DexFile. This "explodes" multidex.
7874   StackHandleScope<10> hs(self);
7875 
7876   ArtField* dex_elements_field =
7877       soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements);
7878 
7879   mirror::Class* dex_elements_class = dex_elements_field->GetType<true>();
7880   DCHECK(dex_elements_class != nullptr);
7881   DCHECK(dex_elements_class->IsArrayClass());
7882   Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements(hs.NewHandle(
7883       mirror::ObjectArray<mirror::Object>::Alloc(self, dex_elements_class, dex_files.size())));
7884   Handle<mirror::Class> h_dex_element_class =
7885       hs.NewHandle(dex_elements_class->GetComponentType());
7886 
7887   ArtField* element_file_field =
7888       soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
7889   DCHECK_EQ(h_dex_element_class.Get(), element_file_field->GetDeclaringClass());
7890 
7891   ArtField* cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
7892   DCHECK_EQ(cookie_field->GetDeclaringClass(), element_file_field->GetType<false>());
7893 
7894   ArtField* file_name_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_fileName);
7895   DCHECK_EQ(file_name_field->GetDeclaringClass(), element_file_field->GetType<false>());
7896 
7897   // Fill the elements array.
7898   int32_t index = 0;
7899   for (const DexFile* dex_file : dex_files) {
7900     StackHandleScope<4> hs2(self);
7901 
7902     // CreatePathClassLoader is only used by gtests. Index 0 of h_long_array is supposed to be the
7903     // oat file but we can leave it null.
7904     Handle<mirror::LongArray> h_long_array = hs2.NewHandle(mirror::LongArray::Alloc(
7905         self,
7906         kDexFileIndexStart + 1));
7907     DCHECK(h_long_array.Get() != nullptr);
7908     h_long_array->Set(kDexFileIndexStart, reinterpret_cast<intptr_t>(dex_file));
7909 
7910     Handle<mirror::Object> h_dex_file = hs2.NewHandle(
7911         cookie_field->GetDeclaringClass()->AllocObject(self));
7912     DCHECK(h_dex_file.Get() != nullptr);
7913     cookie_field->SetObject<false>(h_dex_file.Get(), h_long_array.Get());
7914 
7915     Handle<mirror::String> h_file_name = hs2.NewHandle(
7916         mirror::String::AllocFromModifiedUtf8(self, dex_file->GetLocation().c_str()));
7917     DCHECK(h_file_name.Get() != nullptr);
7918     file_name_field->SetObject<false>(h_dex_file.Get(), h_file_name.Get());
7919 
7920     Handle<mirror::Object> h_element = hs2.NewHandle(h_dex_element_class->AllocObject(self));
7921     DCHECK(h_element.Get() != nullptr);
7922     element_file_field->SetObject<false>(h_element.Get(), h_dex_file.Get());
7923 
7924     h_dex_elements->Set(index, h_element.Get());
7925     index++;
7926   }
7927   DCHECK_EQ(index, h_dex_elements->GetLength());
7928 
7929   // Create DexPathList.
7930   Handle<mirror::Object> h_dex_path_list = hs.NewHandle(
7931       dex_elements_field->GetDeclaringClass()->AllocObject(self));
7932   DCHECK(h_dex_path_list.Get() != nullptr);
7933   // Set elements.
7934   dex_elements_field->SetObject<false>(h_dex_path_list.Get(), h_dex_elements.Get());
7935 
7936   // Create PathClassLoader.
7937   Handle<mirror::Class> h_path_class_class = hs.NewHandle(
7938       soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader));
7939   Handle<mirror::Object> h_path_class_loader = hs.NewHandle(
7940       h_path_class_class->AllocObject(self));
7941   DCHECK(h_path_class_loader.Get() != nullptr);
7942   // Set DexPathList.
7943   ArtField* path_list_field =
7944       soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList);
7945   DCHECK(path_list_field != nullptr);
7946   path_list_field->SetObject<false>(h_path_class_loader.Get(), h_dex_path_list.Get());
7947 
7948   // Make a pretend boot-classpath.
7949   // TODO: Should we scan the image?
7950   ArtField* const parent_field =
7951       mirror::Class::FindField(self, hs.NewHandle(h_path_class_loader->GetClass()), "parent",
7952                                "Ljava/lang/ClassLoader;");
7953   DCHECK(parent_field != nullptr);
7954   mirror::Object* boot_cl =
7955       soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)->AllocObject(self);
7956   parent_field->SetObject<false>(h_path_class_loader.Get(), boot_cl);
7957 
7958   // Make it a global ref and return.
7959   ScopedLocalRef<jobject> local_ref(
7960       soa.Env(), soa.Env()->AddLocalReference<jobject>(h_path_class_loader.Get()));
7961   return soa.Env()->NewGlobalRef(local_ref.get());
7962 }
7963 
CreateRuntimeMethod(LinearAlloc * linear_alloc)7964 ArtMethod* ClassLinker::CreateRuntimeMethod(LinearAlloc* linear_alloc) {
7965   const size_t method_alignment = ArtMethod::Alignment(image_pointer_size_);
7966   const size_t method_size = ArtMethod::Size(image_pointer_size_);
7967   LengthPrefixedArray<ArtMethod>* method_array = AllocArtMethodArray(
7968       Thread::Current(),
7969       linear_alloc,
7970       1);
7971   ArtMethod* method = &method_array->At(0, method_size, method_alignment);
7972   CHECK(method != nullptr);
7973   method->SetDexMethodIndex(DexFile::kDexNoIndex);
7974   CHECK(method->IsRuntimeMethod());
7975   return method;
7976 }
7977 
DropFindArrayClassCache()7978 void ClassLinker::DropFindArrayClassCache() {
7979   std::fill_n(find_array_class_cache_, kFindArrayCacheSize, GcRoot<mirror::Class>(nullptr));
7980   find_array_class_cache_next_victim_ = 0;
7981 }
7982 
ClearClassTableStrongRoots() const7983 void ClassLinker::ClearClassTableStrongRoots() const {
7984   Thread* const self = Thread::Current();
7985   WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
7986   for (const ClassLoaderData& data : class_loaders_) {
7987     if (data.class_table != nullptr) {
7988       data.class_table->ClearStrongRoots();
7989     }
7990   }
7991 }
7992 
VisitClassLoaders(ClassLoaderVisitor * visitor) const7993 void ClassLinker::VisitClassLoaders(ClassLoaderVisitor* visitor) const {
7994   Thread* const self = Thread::Current();
7995   for (const ClassLoaderData& data : class_loaders_) {
7996     // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
7997     auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root));
7998     if (class_loader != nullptr) {
7999       visitor->Visit(class_loader);
8000     }
8001   }
8002 }
8003 
InsertDexFileInToClassLoader(mirror::Object * dex_file,mirror::ClassLoader * class_loader)8004 void ClassLinker::InsertDexFileInToClassLoader(mirror::Object* dex_file,
8005                                                mirror::ClassLoader* class_loader) {
8006   DCHECK(dex_file != nullptr);
8007   Thread* const self = Thread::Current();
8008   WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8009   ClassTable* const table = ClassTableForClassLoader(class_loader);
8010   DCHECK(table != nullptr);
8011   if (table->InsertStrongRoot(dex_file) && class_loader != nullptr) {
8012     // It was not already inserted, perform the write barrier to let the GC know the class loader's
8013     // class table was modified.
8014     Runtime::Current()->GetHeap()->WriteBarrierEveryFieldOf(class_loader);
8015   }
8016 }
8017 
CleanupClassLoaders()8018 void ClassLinker::CleanupClassLoaders() {
8019   Thread* const self = Thread::Current();
8020   WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
8021   for (auto it = class_loaders_.begin(); it != class_loaders_.end(); ) {
8022     const ClassLoaderData& data = *it;
8023     // Need to use DecodeJObject so that we get null for cleared JNI weak globals.
8024     auto* const class_loader = down_cast<mirror::ClassLoader*>(self->DecodeJObject(data.weak_root));
8025     if (class_loader != nullptr) {
8026       ++it;
8027     } else {
8028       VLOG(class_linker) << "Freeing class loader";
8029       DeleteClassLoader(self, data);
8030       it = class_loaders_.erase(it);
8031     }
8032   }
8033 }
8034 
GetResolvedClasses(bool ignore_boot_classes)8035 std::set<DexCacheResolvedClasses> ClassLinker::GetResolvedClasses(bool ignore_boot_classes) {
8036   ScopedTrace trace(__PRETTY_FUNCTION__);
8037   ScopedObjectAccess soa(Thread::Current());
8038   ScopedAssertNoThreadSuspension ants(soa.Self(), __FUNCTION__);
8039   std::set<DexCacheResolvedClasses> ret;
8040   VLOG(class_linker) << "Collecting resolved classes";
8041   const uint64_t start_time = NanoTime();
8042   ReaderMutexLock mu(soa.Self(), *DexLock());
8043   // Loop through all the dex caches and inspect resolved classes.
8044   for (const ClassLinker::DexCacheData& data : GetDexCachesData()) {
8045     if (soa.Self()->IsJWeakCleared(data.weak_root)) {
8046       continue;
8047     }
8048     mirror::DexCache* dex_cache =
8049         down_cast<mirror::DexCache*>(soa.Self()->DecodeJObject(data.weak_root));
8050     if (dex_cache == nullptr) {
8051       continue;
8052     }
8053     const DexFile* dex_file = dex_cache->GetDexFile();
8054     const std::string& location = dex_file->GetLocation();
8055     const size_t num_class_defs = dex_file->NumClassDefs();
8056     // Use the resolved types, this will miss array classes.
8057     const size_t num_types = dex_file->NumTypeIds();
8058     VLOG(class_linker) << "Collecting class profile for dex file " << location
8059                        << " types=" << num_types << " class_defs=" << num_class_defs;
8060     DexCacheResolvedClasses resolved_classes(dex_file->GetLocation(),
8061                                              dex_file->GetBaseLocation(),
8062                                              dex_file->GetLocationChecksum());
8063     size_t num_resolved = 0;
8064     std::unordered_set<uint16_t> class_set;
8065     CHECK_EQ(num_types, dex_cache->NumResolvedTypes());
8066     for (size_t i = 0; i < num_types; ++i) {
8067       mirror::Class* klass = dex_cache->GetResolvedType(i);
8068       // Filter out null class loader since that is the boot class loader.
8069       if (klass == nullptr || (ignore_boot_classes && klass->GetClassLoader() == nullptr)) {
8070         continue;
8071       }
8072       ++num_resolved;
8073       DCHECK(!klass->IsProxyClass());
8074       if (!klass->IsResolved()) {
8075         DCHECK(klass->IsErroneous());
8076         continue;
8077       }
8078       mirror::DexCache* klass_dex_cache = klass->GetDexCache();
8079       if (klass_dex_cache == dex_cache) {
8080         const size_t class_def_idx = klass->GetDexClassDefIndex();
8081         DCHECK(klass->IsResolved());
8082         CHECK_LT(class_def_idx, num_class_defs);
8083         class_set.insert(class_def_idx);
8084       }
8085     }
8086 
8087     if (!class_set.empty()) {
8088       auto it = ret.find(resolved_classes);
8089       if (it != ret.end()) {
8090         // Already have the key, union the class def idxs.
8091         it->AddClasses(class_set.begin(), class_set.end());
8092       } else {
8093         resolved_classes.AddClasses(class_set.begin(), class_set.end());
8094         ret.insert(resolved_classes);
8095       }
8096     }
8097 
8098     VLOG(class_linker) << "Dex location " << location << " has " << num_resolved << " / "
8099                        << num_class_defs << " resolved classes";
8100   }
8101   VLOG(class_linker) << "Collecting class profile took " << PrettyDuration(NanoTime() - start_time);
8102   return ret;
8103 }
8104 
GetClassDescriptorsForProfileKeys(const std::set<DexCacheResolvedClasses> & classes)8105 std::unordered_set<std::string> ClassLinker::GetClassDescriptorsForProfileKeys(
8106     const std::set<DexCacheResolvedClasses>& classes) {
8107   ScopedTrace trace(__PRETTY_FUNCTION__);
8108   std::unordered_set<std::string> ret;
8109   Thread* const self = Thread::Current();
8110   std::unordered_map<std::string, const DexFile*> location_to_dex_file;
8111   ScopedObjectAccess soa(self);
8112   ScopedAssertNoThreadSuspension ants(soa.Self(), __FUNCTION__);
8113   ReaderMutexLock mu(self, *DexLock());
8114   for (const ClassLinker::DexCacheData& data : GetDexCachesData()) {
8115     if (!self->IsJWeakCleared(data.weak_root)) {
8116       mirror::DexCache* dex_cache =
8117           down_cast<mirror::DexCache*>(soa.Self()->DecodeJObject(data.weak_root));
8118       if (dex_cache != nullptr) {
8119         const DexFile* dex_file = dex_cache->GetDexFile();
8120         // There could be duplicates if two dex files with the same location are mapped.
8121         location_to_dex_file.emplace(
8122             ProfileCompilationInfo::GetProfileDexFileKey(dex_file->GetLocation()), dex_file);
8123       }
8124     }
8125   }
8126   for (const DexCacheResolvedClasses& info : classes) {
8127     const std::string& profile_key = info.GetDexLocation();
8128     auto found = location_to_dex_file.find(profile_key);
8129     if (found != location_to_dex_file.end()) {
8130       const DexFile* dex_file = found->second;
8131       VLOG(profiler) << "Found opened dex file for " << dex_file->GetLocation() << " with "
8132                      << info.GetClasses().size() << " classes";
8133       DCHECK_EQ(dex_file->GetLocationChecksum(), info.GetLocationChecksum());
8134       for (uint16_t class_def_idx : info.GetClasses()) {
8135         if (class_def_idx >= dex_file->NumClassDefs()) {
8136           LOG(WARNING) << "Class def index " << class_def_idx << " >= " << dex_file->NumClassDefs();
8137           continue;
8138         }
8139         const DexFile::TypeId& type_id = dex_file->GetTypeId(
8140             dex_file->GetClassDef(class_def_idx).class_idx_);
8141         const char* descriptor = dex_file->GetTypeDescriptor(type_id);
8142         ret.insert(descriptor);
8143       }
8144     } else {
8145       VLOG(class_linker) << "Failed to find opened dex file for profile key " << profile_key;
8146     }
8147   }
8148   return ret;
8149 }
8150 
8151 // Instantiate ResolveMethod.
8152 template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kForceICCECheck>(
8153     const DexFile& dex_file,
8154     uint32_t method_idx,
8155     Handle<mirror::DexCache> dex_cache,
8156     Handle<mirror::ClassLoader> class_loader,
8157     ArtMethod* referrer,
8158     InvokeType type);
8159 template ArtMethod* ClassLinker::ResolveMethod<ClassLinker::kNoICCECheckForCache>(
8160     const DexFile& dex_file,
8161     uint32_t method_idx,
8162     Handle<mirror::DexCache> dex_cache,
8163     Handle<mirror::ClassLoader> class_loader,
8164     ArtMethod* referrer,
8165     InvokeType type);
8166 
8167 }  // namespace art
8168