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