Home | History | Annotate | Download | only in mirror
      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.h"
     18 
     19 #include "android-base/stringprintf.h"
     20 
     21 #include "art_field-inl.h"
     22 #include "art_method-inl.h"
     23 #include "class_ext.h"
     24 #include "class_linker-inl.h"
     25 #include "class_loader.h"
     26 #include "class-inl.h"
     27 #include "dex_cache.h"
     28 #include "dex_file-inl.h"
     29 #include "dex_file_annotations.h"
     30 #include "gc/accounting/card_table-inl.h"
     31 #include "handle_scope-inl.h"
     32 #include "method.h"
     33 #include "object_array-inl.h"
     34 #include "object-inl.h"
     35 #include "object-refvisitor-inl.h"
     36 #include "object_lock.h"
     37 #include "runtime.h"
     38 #include "thread.h"
     39 #include "throwable.h"
     40 #include "utils.h"
     41 #include "well_known_classes.h"
     42 
     43 namespace art {
     44 namespace mirror {
     45 
     46 using android::base::StringPrintf;
     47 
     48 GcRoot<Class> Class::java_lang_Class_;
     49 
     50 void Class::SetClassClass(ObjPtr<Class> java_lang_Class) {
     51   CHECK(java_lang_Class_.IsNull())
     52       << java_lang_Class_.Read()
     53       << " " << java_lang_Class;
     54   CHECK(java_lang_Class != nullptr);
     55   java_lang_Class->SetClassFlags(kClassFlagClass);
     56   java_lang_Class_ = GcRoot<Class>(java_lang_Class);
     57 }
     58 
     59 void Class::ResetClass() {
     60   CHECK(!java_lang_Class_.IsNull());
     61   java_lang_Class_ = GcRoot<Class>(nullptr);
     62 }
     63 
     64 void Class::VisitRoots(RootVisitor* visitor) {
     65   java_lang_Class_.VisitRootIfNonNull(visitor, RootInfo(kRootStickyClass));
     66 }
     67 
     68 ClassExt* Class::EnsureExtDataPresent(Thread* self) {
     69   ObjPtr<ClassExt> existing(GetExtData());
     70   if (!existing.IsNull()) {
     71     return existing.Ptr();
     72   }
     73   StackHandleScope<3> hs(self);
     74   // Handlerize 'this' since we are allocating here.
     75   Handle<Class> h_this(hs.NewHandle(this));
     76   // Clear exception so we can allocate.
     77   Handle<Throwable> throwable(hs.NewHandle(self->GetException()));
     78   self->ClearException();
     79   // Allocate the ClassExt
     80   Handle<ClassExt> new_ext(hs.NewHandle(ClassExt::Alloc(self)));
     81   if (new_ext == nullptr) {
     82     // OOM allocating the classExt.
     83     // TODO Should we restore the suppressed exception?
     84     self->AssertPendingOOMException();
     85     return nullptr;
     86   } else {
     87     MemberOffset ext_offset(OFFSET_OF_OBJECT_MEMBER(Class, ext_data_));
     88     bool set;
     89     // Set the ext_data_ field using CAS semantics.
     90     if (Runtime::Current()->IsActiveTransaction()) {
     91       set = h_this->CasFieldStrongSequentiallyConsistentObject<true>(ext_offset,
     92                                                                      ObjPtr<ClassExt>(nullptr),
     93                                                                      new_ext.Get());
     94     } else {
     95       set = h_this->CasFieldStrongSequentiallyConsistentObject<false>(ext_offset,
     96                                                                       ObjPtr<ClassExt>(nullptr),
     97                                                                       new_ext.Get());
     98     }
     99     ObjPtr<ClassExt> ret(set ? new_ext.Get() : h_this->GetExtData());
    100     DCHECK(!set || h_this->GetExtData() == new_ext.Get());
    101     CHECK(!ret.IsNull());
    102     // Restore the exception if there was one.
    103     if (throwable != nullptr) {
    104       self->SetException(throwable.Get());
    105     }
    106     return ret.Ptr();
    107   }
    108 }
    109 
    110 void Class::SetStatus(Handle<Class> h_this, Status new_status, Thread* self) {
    111   Status old_status = h_this->GetStatus();
    112   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
    113   bool class_linker_initialized = class_linker != nullptr && class_linker->IsInitialized();
    114   if (LIKELY(class_linker_initialized)) {
    115     if (UNLIKELY(new_status <= old_status &&
    116                  new_status != kStatusErrorUnresolved &&
    117                  new_status != kStatusErrorResolved &&
    118                  new_status != kStatusRetired)) {
    119       LOG(FATAL) << "Unexpected change back of class status for " << h_this->PrettyClass()
    120                  << " " << old_status << " -> " << new_status;
    121     }
    122     if (new_status >= kStatusResolved || old_status >= kStatusResolved) {
    123       // When classes are being resolved the resolution code should hold the lock.
    124       CHECK_EQ(h_this->GetLockOwnerThreadId(), self->GetThreadId())
    125             << "Attempt to change status of class while not holding its lock: "
    126             << h_this->PrettyClass() << " " << old_status << " -> " << new_status;
    127     }
    128   }
    129   if (UNLIKELY(IsErroneous(new_status))) {
    130     CHECK(!h_this->IsErroneous())
    131         << "Attempt to set as erroneous an already erroneous class "
    132         << h_this->PrettyClass()
    133         << " old_status: " << old_status << " new_status: " << new_status;
    134     CHECK_EQ(new_status == kStatusErrorResolved, old_status >= kStatusResolved);
    135     if (VLOG_IS_ON(class_linker)) {
    136       LOG(ERROR) << "Setting " << h_this->PrettyDescriptor() << " to erroneous.";
    137       if (self->IsExceptionPending()) {
    138         LOG(ERROR) << "Exception: " << self->GetException()->Dump();
    139       }
    140     }
    141 
    142     ObjPtr<ClassExt> ext(h_this->EnsureExtDataPresent(self));
    143     if (!ext.IsNull()) {
    144       self->AssertPendingException();
    145       ext->SetVerifyError(self->GetException());
    146     } else {
    147       self->AssertPendingOOMException();
    148     }
    149     self->AssertPendingException();
    150   }
    151 
    152   static_assert(sizeof(Status) == sizeof(uint32_t), "Size of status not equal to uint32");
    153   if (Runtime::Current()->IsActiveTransaction()) {
    154     h_this->SetField32Volatile<true>(StatusOffset(), new_status);
    155   } else {
    156     h_this->SetField32Volatile<false>(StatusOffset(), new_status);
    157   }
    158 
    159   // Setting the object size alloc fast path needs to be after the status write so that if the
    160   // alloc path sees a valid object size, we would know that it's initialized as long as it has a
    161   // load-acquire/fake dependency.
    162   if (new_status == kStatusInitialized && !h_this->IsVariableSize()) {
    163     DCHECK_EQ(h_this->GetObjectSizeAllocFastPath(), std::numeric_limits<uint32_t>::max());
    164     // Finalizable objects must always go slow path.
    165     if (!h_this->IsFinalizable()) {
    166       h_this->SetObjectSizeAllocFastPath(RoundUp(h_this->GetObjectSize(), kObjectAlignment));
    167     }
    168   }
    169 
    170   if (!class_linker_initialized) {
    171     // When the class linker is being initialized its single threaded and by definition there can be
    172     // no waiters. During initialization classes may appear temporary but won't be retired as their
    173     // size was statically computed.
    174   } else {
    175     // Classes that are being resolved or initialized need to notify waiters that the class status
    176     // changed. See ClassLinker::EnsureResolved and ClassLinker::WaitForInitializeClass.
    177     if (h_this->IsTemp()) {
    178       // Class is a temporary one, ensure that waiters for resolution get notified of retirement
    179       // so that they can grab the new version of the class from the class linker's table.
    180       CHECK_LT(new_status, kStatusResolved) << h_this->PrettyDescriptor();
    181       if (new_status == kStatusRetired || new_status == kStatusErrorUnresolved) {
    182         h_this->NotifyAll(self);
    183       }
    184     } else {
    185       CHECK_NE(new_status, kStatusRetired);
    186       if (old_status >= kStatusResolved || new_status >= kStatusResolved) {
    187         h_this->NotifyAll(self);
    188       }
    189     }
    190   }
    191 }
    192 
    193 void Class::SetDexCache(ObjPtr<DexCache> new_dex_cache) {
    194   SetFieldObjectTransaction(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache);
    195 }
    196 
    197 void Class::SetClassSize(uint32_t new_class_size) {
    198   if (kIsDebugBuild && new_class_size < GetClassSize()) {
    199     DumpClass(LOG_STREAM(FATAL_WITHOUT_ABORT), kDumpClassFullDetail);
    200     LOG(FATAL_WITHOUT_ABORT) << new_class_size << " vs " << GetClassSize();
    201     LOG(FATAL) << "class=" << PrettyTypeOf();
    202   }
    203   SetField32Transaction(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size);
    204 }
    205 
    206 // Return the class' name. The exact format is bizarre, but it's the specified behavior for
    207 // Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
    208 // but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
    209 // slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
    210 String* Class::ComputeName(Handle<Class> h_this) {
    211   String* name = h_this->GetName();
    212   if (name != nullptr) {
    213     return name;
    214   }
    215   std::string temp;
    216   const char* descriptor = h_this->GetDescriptor(&temp);
    217   Thread* self = Thread::Current();
    218   if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
    219     // The descriptor indicates that this is the class for
    220     // a primitive type; special-case the return value.
    221     const char* c_name = nullptr;
    222     switch (descriptor[0]) {
    223     case 'Z': c_name = "boolean"; break;
    224     case 'B': c_name = "byte";    break;
    225     case 'C': c_name = "char";    break;
    226     case 'S': c_name = "short";   break;
    227     case 'I': c_name = "int";     break;
    228     case 'J': c_name = "long";    break;
    229     case 'F': c_name = "float";   break;
    230     case 'D': c_name = "double";  break;
    231     case 'V': c_name = "void";    break;
    232     default:
    233       LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
    234     }
    235     name = String::AllocFromModifiedUtf8(self, c_name);
    236   } else {
    237     // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
    238     // components.
    239     name = String::AllocFromModifiedUtf8(self, DescriptorToDot(descriptor).c_str());
    240   }
    241   h_this->SetName(name);
    242   return name;
    243 }
    244 
    245 void Class::DumpClass(std::ostream& os, int flags) {
    246   if ((flags & kDumpClassFullDetail) == 0) {
    247     os << PrettyClass();
    248     if ((flags & kDumpClassClassLoader) != 0) {
    249       os << ' ' << GetClassLoader();
    250     }
    251     if ((flags & kDumpClassInitialized) != 0) {
    252       os << ' ' << GetStatus();
    253     }
    254     os << "\n";
    255     return;
    256   }
    257 
    258   Thread* const self = Thread::Current();
    259   StackHandleScope<2> hs(self);
    260   Handle<Class> h_this(hs.NewHandle(this));
    261   Handle<Class> h_super(hs.NewHandle(GetSuperClass()));
    262   auto image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
    263 
    264   std::string temp;
    265   os << "----- " << (IsInterface() ? "interface" : "class") << " "
    266      << "'" << GetDescriptor(&temp) << "' cl=" << GetClassLoader() << " -----\n",
    267   os << "  objectSize=" << SizeOf() << " "
    268      << "(" << (h_super != nullptr ? h_super->SizeOf() : -1) << " from super)\n",
    269   os << StringPrintf("  access=0x%04x.%04x\n",
    270       GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
    271   if (h_super != nullptr) {
    272     os << "  super='" << h_super->PrettyClass() << "' (cl=" << h_super->GetClassLoader()
    273        << ")\n";
    274   }
    275   if (IsArrayClass()) {
    276     os << "  componentType=" << PrettyClass(GetComponentType()) << "\n";
    277   }
    278   const size_t num_direct_interfaces = NumDirectInterfaces();
    279   if (num_direct_interfaces > 0) {
    280     os << "  interfaces (" << num_direct_interfaces << "):\n";
    281     for (size_t i = 0; i < num_direct_interfaces; ++i) {
    282       ObjPtr<Class> interface = GetDirectInterface(self, h_this.Get(), i);
    283       if (interface == nullptr) {
    284         os << StringPrintf("    %2zd: nullptr!\n", i);
    285       } else {
    286         ObjPtr<ClassLoader> cl = interface->GetClassLoader();
    287         os << StringPrintf("    %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl.Ptr());
    288       }
    289     }
    290   }
    291   if (!IsLoaded()) {
    292     os << "  class not yet loaded";
    293   } else {
    294     // After this point, this may have moved due to GetDirectInterface.
    295     os << "  vtable (" << h_this->NumVirtualMethods() << " entries, "
    296         << (h_super != nullptr ? h_super->NumVirtualMethods() : 0) << " in super):\n";
    297     for (size_t i = 0; i < NumVirtualMethods(); ++i) {
    298       os << StringPrintf("    %2zd: %s\n", i, ArtMethod::PrettyMethod(
    299           h_this->GetVirtualMethodDuringLinking(i, image_pointer_size)).c_str());
    300     }
    301     os << "  direct methods (" << h_this->NumDirectMethods() << " entries):\n";
    302     for (size_t i = 0; i < h_this->NumDirectMethods(); ++i) {
    303       os << StringPrintf("    %2zd: %s\n", i, ArtMethod::PrettyMethod(
    304           h_this->GetDirectMethod(i, image_pointer_size)).c_str());
    305     }
    306     if (h_this->NumStaticFields() > 0) {
    307       os << "  static fields (" << h_this->NumStaticFields() << " entries):\n";
    308       if (h_this->IsResolved()) {
    309         for (size_t i = 0; i < h_this->NumStaticFields(); ++i) {
    310           os << StringPrintf("    %2zd: %s\n", i,
    311                              ArtField::PrettyField(h_this->GetStaticField(i)).c_str());
    312         }
    313       } else {
    314         os << "    <not yet available>";
    315       }
    316     }
    317     if (h_this->NumInstanceFields() > 0) {
    318       os << "  instance fields (" << h_this->NumInstanceFields() << " entries):\n";
    319       if (h_this->IsResolved()) {
    320         for (size_t i = 0; i < h_this->NumInstanceFields(); ++i) {
    321           os << StringPrintf("    %2zd: %s\n", i,
    322                              ArtField::PrettyField(h_this->GetInstanceField(i)).c_str());
    323         }
    324       } else {
    325         os << "    <not yet available>";
    326       }
    327     }
    328   }
    329 }
    330 
    331 void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
    332   if (kIsDebugBuild && new_reference_offsets != kClassWalkSuper) {
    333     // Sanity check that the number of bits set in the reference offset bitmap
    334     // agrees with the number of references
    335     uint32_t count = 0;
    336     for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
    337       count += c->NumReferenceInstanceFieldsDuringLinking();
    338     }
    339     // +1 for the Class in Object.
    340     CHECK_EQ(static_cast<uint32_t>(POPCOUNT(new_reference_offsets)) + 1, count);
    341   }
    342   // Not called within a transaction.
    343   SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
    344                     new_reference_offsets);
    345 }
    346 
    347 bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) {
    348   size_t i = 0;
    349   size_t min_length = std::min(descriptor1.size(), descriptor2.size());
    350   while (i < min_length && descriptor1[i] == descriptor2[i]) {
    351     ++i;
    352   }
    353   if (descriptor1.find('/', i) != StringPiece::npos ||
    354       descriptor2.find('/', i) != StringPiece::npos) {
    355     return false;
    356   } else {
    357     return true;
    358   }
    359 }
    360 
    361 bool Class::IsInSamePackage(ObjPtr<Class> that) {
    362   ObjPtr<Class> klass1 = this;
    363   ObjPtr<Class> klass2 = that;
    364   if (klass1 == klass2) {
    365     return true;
    366   }
    367   // Class loaders must match.
    368   if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
    369     return false;
    370   }
    371   // Arrays are in the same package when their element classes are.
    372   while (klass1->IsArrayClass()) {
    373     klass1 = klass1->GetComponentType();
    374   }
    375   while (klass2->IsArrayClass()) {
    376     klass2 = klass2->GetComponentType();
    377   }
    378   // trivial check again for array types
    379   if (klass1 == klass2) {
    380     return true;
    381   }
    382   // Compare the package part of the descriptor string.
    383   std::string temp1, temp2;
    384   return IsInSamePackage(klass1->GetDescriptor(&temp1), klass2->GetDescriptor(&temp2));
    385 }
    386 
    387 bool Class::IsThrowableClass() {
    388   return WellKnownClasses::ToClass(WellKnownClasses::java_lang_Throwable)->IsAssignableFrom(this);
    389 }
    390 
    391 void Class::SetClassLoader(ObjPtr<ClassLoader> new_class_loader) {
    392   if (Runtime::Current()->IsActiveTransaction()) {
    393     SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
    394   } else {
    395     SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
    396   }
    397 }
    398 
    399 template <typename SignatureType>
    400 static inline ArtMethod* FindInterfaceMethodWithSignature(ObjPtr<Class> klass,
    401                                                           const StringPiece& name,
    402                                                           const SignatureType& signature,
    403                                                           PointerSize pointer_size)
    404     REQUIRES_SHARED(Locks::mutator_lock_) {
    405   // If the current class is not an interface, skip the search of its declared methods;
    406   // such lookup is used only to distinguish between IncompatibleClassChangeError and
    407   // NoSuchMethodError and the caller has already tried to search methods in the class.
    408   if (LIKELY(klass->IsInterface())) {
    409     // Search declared methods, both direct and virtual.
    410     // (This lookup is used also for invoke-static on interface classes.)
    411     for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
    412       if (method.GetName() == name && method.GetSignature() == signature) {
    413         return &method;
    414       }
    415     }
    416   }
    417 
    418   // TODO: If there is a unique maximally-specific non-abstract superinterface method,
    419   // we should return it, otherwise an arbitrary one can be returned.
    420   ObjPtr<IfTable> iftable = klass->GetIfTable();
    421   for (int32_t i = 0, iftable_count = iftable->Count(); i < iftable_count; ++i) {
    422     ObjPtr<Class> iface = iftable->GetInterface(i);
    423     for (ArtMethod& method : iface->GetVirtualMethodsSlice(pointer_size)) {
    424       if (method.GetName() == name && method.GetSignature() == signature) {
    425         return &method;
    426       }
    427     }
    428   }
    429 
    430   // Then search for public non-static methods in the java.lang.Object.
    431   if (LIKELY(klass->IsInterface())) {
    432     ObjPtr<Class> object_class = klass->GetSuperClass();
    433     DCHECK(object_class->IsObjectClass());
    434     for (ArtMethod& method : object_class->GetDeclaredMethodsSlice(pointer_size)) {
    435       if (method.IsPublic() && !method.IsStatic() &&
    436           method.GetName() == name && method.GetSignature() == signature) {
    437         return &method;
    438       }
    439     }
    440   }
    441   return nullptr;
    442 }
    443 
    444 ArtMethod* Class::FindInterfaceMethod(const StringPiece& name,
    445                                       const StringPiece& signature,
    446                                       PointerSize pointer_size) {
    447   return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
    448 }
    449 
    450 ArtMethod* Class::FindInterfaceMethod(const StringPiece& name,
    451                                       const Signature& signature,
    452                                       PointerSize pointer_size) {
    453   return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
    454 }
    455 
    456 ArtMethod* Class::FindInterfaceMethod(ObjPtr<DexCache> dex_cache,
    457                                       uint32_t dex_method_idx,
    458                                       PointerSize pointer_size) {
    459   // We always search by name and signature, ignoring the type index in the MethodId.
    460   const DexFile& dex_file = *dex_cache->GetDexFile();
    461   const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
    462   StringPiece name = dex_file.StringDataByIdx(method_id.name_idx_);
    463   const Signature signature = dex_file.GetMethodSignature(method_id);
    464   return FindInterfaceMethod(name, signature, pointer_size);
    465 }
    466 
    467 static inline bool IsValidInheritanceCheck(ObjPtr<mirror::Class> klass,
    468                                            ObjPtr<mirror::Class> declaring_class)
    469     REQUIRES_SHARED(Locks::mutator_lock_) {
    470   if (klass->IsArrayClass()) {
    471     return declaring_class->IsObjectClass();
    472   } else if (klass->IsInterface()) {
    473     return declaring_class->IsObjectClass() || declaring_class == klass;
    474   } else {
    475     return klass->IsSubClass(declaring_class);
    476   }
    477 }
    478 
    479 static inline bool IsInheritedMethod(ObjPtr<mirror::Class> klass,
    480                                      ObjPtr<mirror::Class> declaring_class,
    481                                      ArtMethod& method)
    482     REQUIRES_SHARED(Locks::mutator_lock_) {
    483   DCHECK_EQ(declaring_class, method.GetDeclaringClass());
    484   DCHECK_NE(klass, declaring_class);
    485   DCHECK(IsValidInheritanceCheck(klass, declaring_class));
    486   uint32_t access_flags = method.GetAccessFlags();
    487   if ((access_flags & (kAccPublic | kAccProtected)) != 0) {
    488     return true;
    489   }
    490   if ((access_flags & kAccPrivate) != 0) {
    491     return false;
    492   }
    493   for (; klass != declaring_class; klass = klass->GetSuperClass()) {
    494     if (!klass->IsInSamePackage(declaring_class)) {
    495       return false;
    496     }
    497   }
    498   return true;
    499 }
    500 
    501 template <typename SignatureType>
    502 static inline ArtMethod* FindClassMethodWithSignature(ObjPtr<Class> this_klass,
    503                                                       const StringPiece& name,
    504                                                       const SignatureType& signature,
    505                                                       PointerSize pointer_size)
    506     REQUIRES_SHARED(Locks::mutator_lock_) {
    507   // Search declared methods first.
    508   for (ArtMethod& method : this_klass->GetDeclaredMethodsSlice(pointer_size)) {
    509     ArtMethod* np_method = method.GetInterfaceMethodIfProxy(pointer_size);
    510     if (np_method->GetName() == name && np_method->GetSignature() == signature) {
    511       return &method;
    512     }
    513   }
    514 
    515   // Then search the superclass chain. If we find an inherited method, return it.
    516   // If we find a method that's not inherited because of access restrictions,
    517   // try to find a method inherited from an interface in copied methods.
    518   ObjPtr<Class> klass = this_klass->GetSuperClass();
    519   ArtMethod* uninherited_method = nullptr;
    520   for (; klass != nullptr; klass = klass->GetSuperClass()) {
    521     DCHECK(!klass->IsProxyClass());
    522     for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
    523       if (method.GetName() == name && method.GetSignature() == signature) {
    524         if (IsInheritedMethod(this_klass, klass, method)) {
    525           return &method;
    526         }
    527         uninherited_method = &method;
    528         break;
    529       }
    530     }
    531     if (uninherited_method != nullptr) {
    532       break;
    533     }
    534   }
    535 
    536   // Then search copied methods.
    537   // If we found a method that's not inherited, stop the search in its declaring class.
    538   ObjPtr<Class> end_klass = klass;
    539   DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
    540   klass = this_klass;
    541   if (UNLIKELY(klass->IsProxyClass())) {
    542     DCHECK(klass->GetCopiedMethodsSlice(pointer_size).empty());
    543     klass = klass->GetSuperClass();
    544   }
    545   for (; klass != end_klass; klass = klass->GetSuperClass()) {
    546     DCHECK(!klass->IsProxyClass());
    547     for (ArtMethod& method : klass->GetCopiedMethodsSlice(pointer_size)) {
    548       if (method.GetName() == name && method.GetSignature() == signature) {
    549         return &method;  // No further check needed, copied methods are inherited by definition.
    550       }
    551     }
    552   }
    553   return uninherited_method;  // Return the `uninherited_method` if any.
    554 }
    555 
    556 
    557 ArtMethod* Class::FindClassMethod(const StringPiece& name,
    558                                   const StringPiece& signature,
    559                                   PointerSize pointer_size) {
    560   return FindClassMethodWithSignature(this, name, signature, pointer_size);
    561 }
    562 
    563 ArtMethod* Class::FindClassMethod(const StringPiece& name,
    564                                   const Signature& signature,
    565                                   PointerSize pointer_size) {
    566   return FindClassMethodWithSignature(this, name, signature, pointer_size);
    567 }
    568 
    569 ArtMethod* Class::FindClassMethod(ObjPtr<DexCache> dex_cache,
    570                                   uint32_t dex_method_idx,
    571                                   PointerSize pointer_size) {
    572   // FIXME: Hijacking a proxy class by a custom class loader can break this assumption.
    573   DCHECK(!IsProxyClass());
    574 
    575   // First try to find a declared method by dex_method_idx if we have a dex_cache match.
    576   ObjPtr<DexCache> this_dex_cache = GetDexCache();
    577   if (this_dex_cache == dex_cache) {
    578     // Lookup is always performed in the class referenced by the MethodId.
    579     DCHECK_EQ(dex_type_idx_, GetDexFile().GetMethodId(dex_method_idx).class_idx_.index_);
    580     for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
    581       if (method.GetDexMethodIndex() == dex_method_idx) {
    582         return &method;
    583       }
    584     }
    585   }
    586   // If not found, we need to search by name and signature.
    587   const DexFile& dex_file = *dex_cache->GetDexFile();
    588   const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
    589   const Signature signature = dex_file.GetMethodSignature(method_id);
    590   StringPiece name;  // Delay strlen() until actually needed.
    591   // If we do not have a dex_cache match, try to find the declared method in this class now.
    592   if (this_dex_cache != dex_cache && !GetDeclaredMethodsSlice(pointer_size).empty()) {
    593     DCHECK(name.empty());
    594     name = dex_file.StringDataByIdx(method_id.name_idx_);
    595     for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
    596       if (method.GetName() == name && method.GetSignature() == signature) {
    597         return &method;
    598       }
    599     }
    600   }
    601 
    602   // Then search the superclass chain. If we find an inherited method, return it.
    603   // If we find a method that's not inherited because of access restrictions,
    604   // try to find a method inherited from an interface in copied methods.
    605   ArtMethod* uninherited_method = nullptr;
    606   ObjPtr<Class> klass = GetSuperClass();
    607   for (; klass != nullptr; klass = klass->GetSuperClass()) {
    608     ArtMethod* candidate_method = nullptr;
    609     ArraySlice<ArtMethod> declared_methods = klass->GetDeclaredMethodsSlice(pointer_size);
    610     if (klass->GetDexCache() == dex_cache) {
    611       // Matching dex_cache. We cannot compare the `dex_method_idx` anymore because
    612       // the type index differs, so compare the name index and proto index.
    613       for (ArtMethod& method : declared_methods) {
    614         const DexFile::MethodId& cmp_method_id = dex_file.GetMethodId(method.GetDexMethodIndex());
    615         if (cmp_method_id.name_idx_ == method_id.name_idx_ &&
    616             cmp_method_id.proto_idx_ == method_id.proto_idx_) {
    617           candidate_method = &method;
    618           break;
    619         }
    620       }
    621     } else {
    622       if (!declared_methods.empty() && name.empty()) {
    623         name = dex_file.StringDataByIdx(method_id.name_idx_);
    624       }
    625       for (ArtMethod& method : declared_methods) {
    626         if (method.GetName() == name && method.GetSignature() == signature) {
    627           candidate_method = &method;
    628           break;
    629         }
    630       }
    631     }
    632     if (candidate_method != nullptr) {
    633       if (IsInheritedMethod(this, klass, *candidate_method)) {
    634         return candidate_method;
    635       } else {
    636         uninherited_method = candidate_method;
    637         break;
    638       }
    639     }
    640   }
    641 
    642   // Then search copied methods.
    643   // If we found a method that's not inherited, stop the search in its declaring class.
    644   ObjPtr<Class> end_klass = klass;
    645   DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
    646   // After we have searched the declared methods of the super-class chain,
    647   // search copied methods which can contain methods from interfaces.
    648   for (klass = this; klass != end_klass; klass = klass->GetSuperClass()) {
    649     ArraySlice<ArtMethod> copied_methods = klass->GetCopiedMethodsSlice(pointer_size);
    650     if (!copied_methods.empty() && name.empty()) {
    651       name = dex_file.StringDataByIdx(method_id.name_idx_);
    652     }
    653     for (ArtMethod& method : copied_methods) {
    654       if (method.GetName() == name && method.GetSignature() == signature) {
    655         return &method;  // No further check needed, copied methods are inherited by definition.
    656       }
    657     }
    658   }
    659   return uninherited_method;  // Return the `uninherited_method` if any.
    660 }
    661 
    662 ArtMethod* Class::FindConstructor(const StringPiece& signature, PointerSize pointer_size) {
    663   // Internal helper, never called on proxy classes. We can skip GetInterfaceMethodIfProxy().
    664   DCHECK(!IsProxyClass());
    665   StringPiece name("<init>");
    666   for (ArtMethod& method : GetDirectMethodsSliceUnchecked(pointer_size)) {
    667     if (method.GetName() == name && method.GetSignature() == signature) {
    668       return &method;
    669     }
    670   }
    671   return nullptr;
    672 }
    673 
    674 ArtMethod* Class::FindDeclaredDirectMethodByName(const StringPiece& name,
    675                                                  PointerSize pointer_size) {
    676   for (auto& method : GetDirectMethods(pointer_size)) {
    677     ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
    678     if (name == np_method->GetName()) {
    679       return &method;
    680     }
    681   }
    682   return nullptr;
    683 }
    684 
    685 ArtMethod* Class::FindDeclaredVirtualMethodByName(const StringPiece& name,
    686                                                   PointerSize pointer_size) {
    687   for (auto& method : GetVirtualMethods(pointer_size)) {
    688     ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
    689     if (name == np_method->GetName()) {
    690       return &method;
    691     }
    692   }
    693   return nullptr;
    694 }
    695 
    696 ArtMethod* Class::FindVirtualMethodForInterfaceSuper(ArtMethod* method, PointerSize pointer_size) {
    697   DCHECK(method->GetDeclaringClass()->IsInterface());
    698   DCHECK(IsInterface()) << "Should only be called on a interface class";
    699   // Check if we have one defined on this interface first. This includes searching copied ones to
    700   // get any conflict methods. Conflict methods are copied into each subtype from the supertype. We
    701   // don't do any indirect method checks here.
    702   for (ArtMethod& iface_method : GetVirtualMethods(pointer_size)) {
    703     if (method->HasSameNameAndSignature(&iface_method)) {
    704       return &iface_method;
    705     }
    706   }
    707 
    708   std::vector<ArtMethod*> abstract_methods;
    709   // Search through the IFTable for a working version. We don't need to check for conflicts
    710   // because if there was one it would appear in this classes virtual_methods_ above.
    711 
    712   Thread* self = Thread::Current();
    713   StackHandleScope<2> hs(self);
    714   MutableHandle<IfTable> iftable(hs.NewHandle(GetIfTable()));
    715   MutableHandle<Class> iface(hs.NewHandle<Class>(nullptr));
    716   size_t iftable_count = GetIfTableCount();
    717   // Find the method. We don't need to check for conflicts because they would have been in the
    718   // copied virtuals of this interface.  Order matters, traverse in reverse topological order; most
    719   // subtypiest interfaces get visited first.
    720   for (size_t k = iftable_count; k != 0;) {
    721     k--;
    722     DCHECK_LT(k, iftable->Count());
    723     iface.Assign(iftable->GetInterface(k));
    724     // Iterate through every declared method on this interface. Each direct method's name/signature
    725     // is unique so the order of the inner loop doesn't matter.
    726     for (auto& method_iter : iface->GetDeclaredVirtualMethods(pointer_size)) {
    727       ArtMethod* current_method = &method_iter;
    728       if (current_method->HasSameNameAndSignature(method)) {
    729         if (current_method->IsDefault()) {
    730           // Handle JLS soft errors, a default method from another superinterface tree can
    731           // "override" an abstract method(s) from another superinterface tree(s).  To do this,
    732           // ignore any [default] method which are dominated by the abstract methods we've seen so
    733           // far. Check if overridden by any in abstract_methods. We do not need to check for
    734           // default_conflicts because we would hit those before we get to this loop.
    735           bool overridden = false;
    736           for (ArtMethod* possible_override : abstract_methods) {
    737             DCHECK(possible_override->HasSameNameAndSignature(current_method));
    738             if (iface->IsAssignableFrom(possible_override->GetDeclaringClass())) {
    739               overridden = true;
    740               break;
    741             }
    742           }
    743           if (!overridden) {
    744             return current_method;
    745           }
    746         } else {
    747           // Is not default.
    748           // This might override another default method. Just stash it for now.
    749           abstract_methods.push_back(current_method);
    750         }
    751       }
    752     }
    753   }
    754   // If we reach here we either never found any declaration of the method (in which case
    755   // 'abstract_methods' is empty or we found no non-overriden default methods in which case
    756   // 'abstract_methods' contains a number of abstract implementations of the methods. We choose one
    757   // of these arbitrarily.
    758   return abstract_methods.empty() ? nullptr : abstract_methods[0];
    759 }
    760 
    761 ArtMethod* Class::FindClassInitializer(PointerSize pointer_size) {
    762   for (ArtMethod& method : GetDirectMethods(pointer_size)) {
    763     if (method.IsClassInitializer()) {
    764       DCHECK_STREQ(method.GetName(), "<clinit>");
    765       DCHECK_STREQ(method.GetSignature().ToString().c_str(), "()V");
    766       return &method;
    767     }
    768   }
    769   return nullptr;
    770 }
    771 
    772 // Custom binary search to avoid double comparisons from std::binary_search.
    773 static ArtField* FindFieldByNameAndType(LengthPrefixedArray<ArtField>* fields,
    774                                         const StringPiece& name,
    775                                         const StringPiece& type)
    776     REQUIRES_SHARED(Locks::mutator_lock_) {
    777   if (fields == nullptr) {
    778     return nullptr;
    779   }
    780   size_t low = 0;
    781   size_t high = fields->size();
    782   ArtField* ret = nullptr;
    783   while (low < high) {
    784     size_t mid = (low + high) / 2;
    785     ArtField& field = fields->At(mid);
    786     // Fields are sorted by class, then name, then type descriptor. This is verified in dex file
    787     // verifier. There can be multiple fields with the same in the same class name due to proguard.
    788     int result = StringPiece(field.GetName()).Compare(name);
    789     if (result == 0) {
    790       result = StringPiece(field.GetTypeDescriptor()).Compare(type);
    791     }
    792     if (result < 0) {
    793       low = mid + 1;
    794     } else if (result > 0) {
    795       high = mid;
    796     } else {
    797       ret = &field;
    798       break;
    799     }
    800   }
    801   if (kIsDebugBuild) {
    802     ArtField* found = nullptr;
    803     for (ArtField& field : MakeIterationRangeFromLengthPrefixedArray(fields)) {
    804       if (name == field.GetName() && type == field.GetTypeDescriptor()) {
    805         found = &field;
    806         break;
    807       }
    808     }
    809     CHECK_EQ(found, ret) << "Found " << found->PrettyField() << " vs  " << ret->PrettyField();
    810   }
    811   return ret;
    812 }
    813 
    814 ArtField* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
    815   // Binary search by name. Interfaces are not relevant because they can't contain instance fields.
    816   return FindFieldByNameAndType(GetIFieldsPtr(), name, type);
    817 }
    818 
    819 ArtField* Class::FindDeclaredInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
    820   if (GetDexCache() == dex_cache) {
    821     for (ArtField& field : GetIFields()) {
    822       if (field.GetDexFieldIndex() == dex_field_idx) {
    823         return &field;
    824       }
    825     }
    826   }
    827   return nullptr;
    828 }
    829 
    830 ArtField* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
    831   // Is the field in this class, or any of its superclasses?
    832   // Interfaces are not relevant because they can't contain instance fields.
    833   for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
    834     ArtField* f = c->FindDeclaredInstanceField(name, type);
    835     if (f != nullptr) {
    836       return f;
    837     }
    838   }
    839   return nullptr;
    840 }
    841 
    842 ArtField* Class::FindInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
    843   // Is the field in this class, or any of its superclasses?
    844   // Interfaces are not relevant because they can't contain instance fields.
    845   for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
    846     ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
    847     if (f != nullptr) {
    848       return f;
    849     }
    850   }
    851   return nullptr;
    852 }
    853 
    854 ArtField* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
    855   DCHECK(type != nullptr);
    856   return FindFieldByNameAndType(GetSFieldsPtr(), name, type);
    857 }
    858 
    859 ArtField* Class::FindDeclaredStaticField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
    860   if (dex_cache == GetDexCache()) {
    861     for (ArtField& field : GetSFields()) {
    862       if (field.GetDexFieldIndex() == dex_field_idx) {
    863         return &field;
    864       }
    865     }
    866   }
    867   return nullptr;
    868 }
    869 
    870 ArtField* Class::FindStaticField(Thread* self,
    871                                  ObjPtr<Class> klass,
    872                                  const StringPiece& name,
    873                                  const StringPiece& type) {
    874   // Is the field in this class (or its interfaces), or any of its
    875   // superclasses (or their interfaces)?
    876   for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
    877     // Is the field in this class?
    878     ArtField* f = k->FindDeclaredStaticField(name, type);
    879     if (f != nullptr) {
    880       return f;
    881     }
    882     // Is this field in any of this class' interfaces?
    883     for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
    884       ObjPtr<Class> interface = GetDirectInterface(self, k, i);
    885       DCHECK(interface != nullptr);
    886       f = FindStaticField(self, interface, name, type);
    887       if (f != nullptr) {
    888         return f;
    889       }
    890     }
    891   }
    892   return nullptr;
    893 }
    894 
    895 ArtField* Class::FindStaticField(Thread* self,
    896                                  ObjPtr<Class> klass,
    897                                  ObjPtr<DexCache> dex_cache,
    898                                  uint32_t dex_field_idx) {
    899   for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
    900     // Is the field in this class?
    901     ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
    902     if (f != nullptr) {
    903       return f;
    904     }
    905     // Though GetDirectInterface() should not cause thread suspension when called
    906     // from here, it takes a Handle as an argument, so we need to wrap `k`.
    907     ScopedAssertNoThreadSuspension ants(__FUNCTION__);
    908     // Is this field in any of this class' interfaces?
    909     for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
    910       ObjPtr<Class> interface = GetDirectInterface(self, k, i);
    911       DCHECK(interface != nullptr);
    912       f = FindStaticField(self, interface, dex_cache, dex_field_idx);
    913       if (f != nullptr) {
    914         return f;
    915       }
    916     }
    917   }
    918   return nullptr;
    919 }
    920 
    921 ArtField* Class::FindField(Thread* self,
    922                            ObjPtr<Class> klass,
    923                            const StringPiece& name,
    924                            const StringPiece& type) {
    925   // Find a field using the JLS field resolution order
    926   for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
    927     // Is the field in this class?
    928     ArtField* f = k->FindDeclaredInstanceField(name, type);
    929     if (f != nullptr) {
    930       return f;
    931     }
    932     f = k->FindDeclaredStaticField(name, type);
    933     if (f != nullptr) {
    934       return f;
    935     }
    936     // Is this field in any of this class' interfaces?
    937     for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
    938       ObjPtr<Class> interface = GetDirectInterface(self, k, i);
    939       DCHECK(interface != nullptr);
    940       f = FindStaticField(self, interface, name, type);
    941       if (f != nullptr) {
    942         return f;
    943       }
    944     }
    945   }
    946   return nullptr;
    947 }
    948 
    949 void Class::SetSkipAccessChecksFlagOnAllMethods(PointerSize pointer_size) {
    950   DCHECK(IsVerified());
    951   for (auto& m : GetMethods(pointer_size)) {
    952     if (!m.IsNative() && m.IsInvokable()) {
    953       m.SetSkipAccessChecks();
    954     }
    955   }
    956 }
    957 
    958 const char* Class::GetDescriptor(std::string* storage) {
    959   if (IsPrimitive()) {
    960     return Primitive::Descriptor(GetPrimitiveType());
    961   } else if (IsArrayClass()) {
    962     return GetArrayDescriptor(storage);
    963   } else if (IsProxyClass()) {
    964     *storage = Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this);
    965     return storage->c_str();
    966   } else {
    967     const DexFile& dex_file = GetDexFile();
    968     const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
    969     return dex_file.GetTypeDescriptor(type_id);
    970   }
    971 }
    972 
    973 const char* Class::GetArrayDescriptor(std::string* storage) {
    974   std::string temp;
    975   const char* elem_desc = GetComponentType()->GetDescriptor(&temp);
    976   *storage = "[";
    977   *storage += elem_desc;
    978   return storage->c_str();
    979 }
    980 
    981 const DexFile::ClassDef* Class::GetClassDef() {
    982   uint16_t class_def_idx = GetDexClassDefIndex();
    983   if (class_def_idx == DexFile::kDexNoIndex16) {
    984     return nullptr;
    985   }
    986   return &GetDexFile().GetClassDef(class_def_idx);
    987 }
    988 
    989 dex::TypeIndex Class::GetDirectInterfaceTypeIdx(uint32_t idx) {
    990   DCHECK(!IsPrimitive());
    991   DCHECK(!IsArrayClass());
    992   return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_;
    993 }
    994 
    995 ObjPtr<Class> Class::GetDirectInterface(Thread* self, ObjPtr<Class> klass, uint32_t idx) {
    996   DCHECK(klass != nullptr);
    997   DCHECK(!klass->IsPrimitive());
    998   if (klass->IsArrayClass()) {
    999     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
   1000     // Use ClassLinker::LookupClass(); avoid poisoning ObjPtr<>s by ClassLinker::FindSystemClass().
   1001     ObjPtr<Class> interface;
   1002     if (idx == 0) {
   1003       interface = class_linker->LookupClass(self, "Ljava/lang/Cloneable;", nullptr);
   1004     } else {
   1005       DCHECK_EQ(1U, idx);
   1006       interface = class_linker->LookupClass(self, "Ljava/io/Serializable;", nullptr);
   1007     }
   1008     DCHECK(interface != nullptr);
   1009     return interface;
   1010   } else if (klass->IsProxyClass()) {
   1011     ObjPtr<ObjectArray<Class>> interfaces = klass->GetProxyInterfaces();
   1012     DCHECK(interfaces != nullptr);
   1013     return interfaces->Get(idx);
   1014   } else {
   1015     dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
   1016     ObjPtr<Class> interface = ClassLinker::LookupResolvedType(
   1017         type_idx, klass->GetDexCache(), klass->GetClassLoader());
   1018     return interface;
   1019   }
   1020 }
   1021 
   1022 ObjPtr<Class> Class::ResolveDirectInterface(Thread* self, Handle<Class> klass, uint32_t idx) {
   1023   ObjPtr<Class> interface = GetDirectInterface(self, klass.Get(), idx);
   1024   if (interface == nullptr) {
   1025     DCHECK(!klass->IsArrayClass());
   1026     DCHECK(!klass->IsProxyClass());
   1027     dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
   1028     interface = Runtime::Current()->GetClassLinker()->ResolveType(klass->GetDexFile(),
   1029                                                                   type_idx,
   1030                                                                   klass.Get());
   1031     CHECK(interface != nullptr || self->IsExceptionPending());
   1032   }
   1033   return interface;
   1034 }
   1035 
   1036 ObjPtr<Class> Class::GetCommonSuperClass(Handle<Class> klass) {
   1037   DCHECK(klass != nullptr);
   1038   DCHECK(!klass->IsInterface());
   1039   DCHECK(!IsInterface());
   1040   ObjPtr<Class> common_super_class = this;
   1041   while (!common_super_class->IsAssignableFrom(klass.Get())) {
   1042     ObjPtr<Class> old_common = common_super_class;
   1043     common_super_class = old_common->GetSuperClass();
   1044     DCHECK(common_super_class != nullptr) << old_common->PrettyClass();
   1045   }
   1046   return common_super_class;
   1047 }
   1048 
   1049 const char* Class::GetSourceFile() {
   1050   const DexFile& dex_file = GetDexFile();
   1051   const DexFile::ClassDef* dex_class_def = GetClassDef();
   1052   if (dex_class_def == nullptr) {
   1053     // Generated classes have no class def.
   1054     return nullptr;
   1055   }
   1056   return dex_file.GetSourceFile(*dex_class_def);
   1057 }
   1058 
   1059 std::string Class::GetLocation() {
   1060   ObjPtr<DexCache> dex_cache = GetDexCache();
   1061   if (dex_cache != nullptr && !IsProxyClass()) {
   1062     return dex_cache->GetLocation()->ToModifiedUtf8();
   1063   }
   1064   // Arrays and proxies are generated and have no corresponding dex file location.
   1065   return "generated class";
   1066 }
   1067 
   1068 const DexFile::TypeList* Class::GetInterfaceTypeList() {
   1069   const DexFile::ClassDef* class_def = GetClassDef();
   1070   if (class_def == nullptr) {
   1071     return nullptr;
   1072   }
   1073   return GetDexFile().GetInterfacesList(*class_def);
   1074 }
   1075 
   1076 void Class::PopulateEmbeddedVTable(PointerSize pointer_size) {
   1077   PointerArray* table = GetVTableDuringLinking();
   1078   CHECK(table != nullptr) << PrettyClass();
   1079   const size_t table_length = table->GetLength();
   1080   SetEmbeddedVTableLength(table_length);
   1081   for (size_t i = 0; i < table_length; i++) {
   1082     SetEmbeddedVTableEntry(i, table->GetElementPtrSize<ArtMethod*>(i, pointer_size), pointer_size);
   1083   }
   1084   // Keep java.lang.Object class's vtable around for since it's easier
   1085   // to be reused by array classes during their linking.
   1086   if (!IsObjectClass()) {
   1087     SetVTable(nullptr);
   1088   }
   1089 }
   1090 
   1091 class ReadBarrierOnNativeRootsVisitor {
   1092  public:
   1093   void operator()(ObjPtr<Object> obj ATTRIBUTE_UNUSED,
   1094                   MemberOffset offset ATTRIBUTE_UNUSED,
   1095                   bool is_static ATTRIBUTE_UNUSED) const {}
   1096 
   1097   void VisitRootIfNonNull(CompressedReference<Object>* root) const
   1098       REQUIRES_SHARED(Locks::mutator_lock_) {
   1099     if (!root->IsNull()) {
   1100       VisitRoot(root);
   1101     }
   1102   }
   1103 
   1104   void VisitRoot(CompressedReference<Object>* root) const
   1105       REQUIRES_SHARED(Locks::mutator_lock_) {
   1106     ObjPtr<Object> old_ref = root->AsMirrorPtr();
   1107     ObjPtr<Object> new_ref = ReadBarrier::BarrierForRoot(root);
   1108     if (old_ref != new_ref) {
   1109       // Update the field atomically. This may fail if mutator updates before us, but it's ok.
   1110       auto* atomic_root =
   1111           reinterpret_cast<Atomic<CompressedReference<Object>>*>(root);
   1112       atomic_root->CompareExchangeStrongSequentiallyConsistent(
   1113           CompressedReference<Object>::FromMirrorPtr(old_ref.Ptr()),
   1114           CompressedReference<Object>::FromMirrorPtr(new_ref.Ptr()));
   1115     }
   1116   }
   1117 };
   1118 
   1119 // The pre-fence visitor for Class::CopyOf().
   1120 class CopyClassVisitor {
   1121  public:
   1122   CopyClassVisitor(Thread* self,
   1123                    Handle<Class>* orig,
   1124                    size_t new_length,
   1125                    size_t copy_bytes,
   1126                    ImTable* imt,
   1127                    PointerSize pointer_size)
   1128       : self_(self), orig_(orig), new_length_(new_length),
   1129         copy_bytes_(copy_bytes), imt_(imt), pointer_size_(pointer_size) {
   1130   }
   1131 
   1132   void operator()(ObjPtr<Object> obj, size_t usable_size ATTRIBUTE_UNUSED) const
   1133       REQUIRES_SHARED(Locks::mutator_lock_) {
   1134     StackHandleScope<1> hs(self_);
   1135     Handle<mirror::Class> h_new_class_obj(hs.NewHandle(obj->AsClass()));
   1136     Object::CopyObject(h_new_class_obj.Get(), orig_->Get(), copy_bytes_);
   1137     Class::SetStatus(h_new_class_obj, Class::kStatusResolving, self_);
   1138     h_new_class_obj->PopulateEmbeddedVTable(pointer_size_);
   1139     h_new_class_obj->SetImt(imt_, pointer_size_);
   1140     h_new_class_obj->SetClassSize(new_length_);
   1141     // Visit all of the references to make sure there is no from space references in the native
   1142     // roots.
   1143     ObjPtr<Object>(h_new_class_obj.Get())->VisitReferences(
   1144         ReadBarrierOnNativeRootsVisitor(), VoidFunctor());
   1145   }
   1146 
   1147  private:
   1148   Thread* const self_;
   1149   Handle<Class>* const orig_;
   1150   const size_t new_length_;
   1151   const size_t copy_bytes_;
   1152   ImTable* imt_;
   1153   const PointerSize pointer_size_;
   1154   DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor);
   1155 };
   1156 
   1157 Class* Class::CopyOf(Thread* self, int32_t new_length, ImTable* imt, PointerSize pointer_size) {
   1158   DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class)));
   1159   // We may get copied by a compacting GC.
   1160   StackHandleScope<1> hs(self);
   1161   Handle<Class> h_this(hs.NewHandle(this));
   1162   gc::Heap* heap = Runtime::Current()->GetHeap();
   1163   // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf()
   1164   // to skip copying the tail part that we will overwrite here.
   1165   CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class), imt, pointer_size);
   1166   ObjPtr<Object> new_class = kMovingClasses ?
   1167       heap->AllocObject<true>(self, java_lang_Class_.Read(), new_length, visitor) :
   1168       heap->AllocNonMovableObject<true>(self, java_lang_Class_.Read(), new_length, visitor);
   1169   if (UNLIKELY(new_class == nullptr)) {
   1170     self->AssertPendingOOMException();
   1171     return nullptr;
   1172   }
   1173   return new_class->AsClass();
   1174 }
   1175 
   1176 bool Class::ProxyDescriptorEquals(const char* match) {
   1177   DCHECK(IsProxyClass());
   1178   return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this) == match;
   1179 }
   1180 
   1181 // TODO: Move this to java_lang_Class.cc?
   1182 ArtMethod* Class::GetDeclaredConstructor(
   1183     Thread* self, Handle<ObjectArray<Class>> args, PointerSize pointer_size) {
   1184   for (auto& m : GetDirectMethods(pointer_size)) {
   1185     // Skip <clinit> which is a static constructor, as well as non constructors.
   1186     if (m.IsStatic() || !m.IsConstructor()) {
   1187       continue;
   1188     }
   1189     // May cause thread suspension and exceptions.
   1190     if (m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->EqualParameters(args)) {
   1191       return &m;
   1192     }
   1193     if (UNLIKELY(self->IsExceptionPending())) {
   1194       return nullptr;
   1195     }
   1196   }
   1197   return nullptr;
   1198 }
   1199 
   1200 uint32_t Class::Depth() {
   1201   uint32_t depth = 0;
   1202   for (ObjPtr<Class> klass = this; klass->GetSuperClass() != nullptr; klass = klass->GetSuperClass()) {
   1203     depth++;
   1204   }
   1205   return depth;
   1206 }
   1207 
   1208 dex::TypeIndex Class::FindTypeIndexInOtherDexFile(const DexFile& dex_file) {
   1209   std::string temp;
   1210   const DexFile::TypeId* type_id = dex_file.FindTypeId(GetDescriptor(&temp));
   1211   return (type_id == nullptr) ? dex::TypeIndex() : dex_file.GetIndexForTypeId(*type_id);
   1212 }
   1213 
   1214 template <PointerSize kPointerSize, bool kTransactionActive>
   1215 ObjPtr<Method> Class::GetDeclaredMethodInternal(
   1216     Thread* self,
   1217     ObjPtr<Class> klass,
   1218     ObjPtr<String> name,
   1219     ObjPtr<ObjectArray<Class>> args) {
   1220   // Covariant return types permit the class to define multiple
   1221   // methods with the same name and parameter types. Prefer to
   1222   // return a non-synthetic method in such situations. We may
   1223   // still return a synthetic method to handle situations like
   1224   // escalated visibility. We never return miranda methods that
   1225   // were synthesized by the runtime.
   1226   constexpr uint32_t kSkipModifiers = kAccMiranda | kAccSynthetic;
   1227   StackHandleScope<3> hs(self);
   1228   auto h_method_name = hs.NewHandle(name);
   1229   if (UNLIKELY(h_method_name == nullptr)) {
   1230     ThrowNullPointerException("name == null");
   1231     return nullptr;
   1232   }
   1233   auto h_args = hs.NewHandle(args);
   1234   Handle<Class> h_klass = hs.NewHandle(klass);
   1235   ArtMethod* result = nullptr;
   1236   for (auto& m : h_klass->GetDeclaredVirtualMethods(kPointerSize)) {
   1237     auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
   1238     // May cause thread suspension.
   1239     ObjPtr<String> np_name = np_method->GetNameAsString(self);
   1240     if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
   1241       if (UNLIKELY(self->IsExceptionPending())) {
   1242         return nullptr;
   1243       }
   1244       continue;
   1245     }
   1246     auto modifiers = m.GetAccessFlags();
   1247     if ((modifiers & kSkipModifiers) == 0) {
   1248       return Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, &m);
   1249     }
   1250     if ((modifiers & kAccMiranda) == 0) {
   1251       result = &m;  // Remember as potential result if it's not a miranda method.
   1252     }
   1253   }
   1254   if (result == nullptr) {
   1255     for (auto& m : h_klass->GetDirectMethods(kPointerSize)) {
   1256       auto modifiers = m.GetAccessFlags();
   1257       if ((modifiers & kAccConstructor) != 0) {
   1258         continue;
   1259       }
   1260       auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
   1261       // May cause thread suspension.
   1262       ObjPtr<String> np_name = np_method->GetNameAsString(self);
   1263       if (np_name == nullptr) {
   1264         self->AssertPendingException();
   1265         return nullptr;
   1266       }
   1267       if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
   1268         if (UNLIKELY(self->IsExceptionPending())) {
   1269           return nullptr;
   1270         }
   1271         continue;
   1272       }
   1273       if ((modifiers & kSkipModifiers) == 0) {
   1274         return Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, &m);
   1275       }
   1276       // Direct methods cannot be miranda methods, so this potential result must be synthetic.
   1277       result = &m;
   1278     }
   1279   }
   1280   return result != nullptr
   1281       ? Method::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, result)
   1282       : nullptr;
   1283 }
   1284 
   1285 template
   1286 ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32, false>(
   1287     Thread* self,
   1288     ObjPtr<Class> klass,
   1289     ObjPtr<String> name,
   1290     ObjPtr<ObjectArray<Class>> args);
   1291 template
   1292 ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32, true>(
   1293     Thread* self,
   1294     ObjPtr<Class> klass,
   1295     ObjPtr<String> name,
   1296     ObjPtr<ObjectArray<Class>> args);
   1297 template
   1298 ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64, false>(
   1299     Thread* self,
   1300     ObjPtr<Class> klass,
   1301     ObjPtr<String> name,
   1302     ObjPtr<ObjectArray<Class>> args);
   1303 template
   1304 ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64, true>(
   1305     Thread* self,
   1306     ObjPtr<Class> klass,
   1307     ObjPtr<String> name,
   1308     ObjPtr<ObjectArray<Class>> args);
   1309 
   1310 template <PointerSize kPointerSize, bool kTransactionActive>
   1311 ObjPtr<Constructor> Class::GetDeclaredConstructorInternal(
   1312     Thread* self,
   1313     ObjPtr<Class> klass,
   1314     ObjPtr<ObjectArray<Class>> args) {
   1315   StackHandleScope<1> hs(self);
   1316   ArtMethod* result = klass->GetDeclaredConstructor(self, hs.NewHandle(args), kPointerSize);
   1317   return result != nullptr
   1318       ? Constructor::CreateFromArtMethod<kPointerSize, kTransactionActive>(self, result)
   1319       : nullptr;
   1320 }
   1321 
   1322 // Constructor::CreateFromArtMethod<kTransactionActive>(self, result)
   1323 
   1324 template
   1325 ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32, false>(
   1326     Thread* self,
   1327     ObjPtr<Class> klass,
   1328     ObjPtr<ObjectArray<Class>> args);
   1329 template
   1330 ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32, true>(
   1331     Thread* self,
   1332     ObjPtr<Class> klass,
   1333     ObjPtr<ObjectArray<Class>> args);
   1334 template
   1335 ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64, false>(
   1336     Thread* self,
   1337     ObjPtr<Class> klass,
   1338     ObjPtr<ObjectArray<Class>> args);
   1339 template
   1340 ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64, true>(
   1341     Thread* self,
   1342     ObjPtr<Class> klass,
   1343     ObjPtr<ObjectArray<Class>> args);
   1344 
   1345 int32_t Class::GetInnerClassFlags(Handle<Class> h_this, int32_t default_value) {
   1346   if (h_this->IsProxyClass() || h_this->GetDexCache() == nullptr) {
   1347     return default_value;
   1348   }
   1349   uint32_t flags;
   1350   if (!annotations::GetInnerClassFlags(h_this, &flags)) {
   1351     return default_value;
   1352   }
   1353   return flags;
   1354 }
   1355 
   1356 void Class::SetObjectSizeAllocFastPath(uint32_t new_object_size) {
   1357   if (Runtime::Current()->IsActiveTransaction()) {
   1358     SetField32Volatile<true>(ObjectSizeAllocFastPathOffset(), new_object_size);
   1359   } else {
   1360     SetField32Volatile<false>(ObjectSizeAllocFastPathOffset(), new_object_size);
   1361   }
   1362 }
   1363 
   1364 std::string Class::PrettyDescriptor(ObjPtr<mirror::Class> klass) {
   1365   if (klass == nullptr) {
   1366     return "null";
   1367   }
   1368   return klass->PrettyDescriptor();
   1369 }
   1370 
   1371 std::string Class::PrettyDescriptor() {
   1372   std::string temp;
   1373   return art::PrettyDescriptor(GetDescriptor(&temp));
   1374 }
   1375 
   1376 std::string Class::PrettyClass(ObjPtr<mirror::Class> c) {
   1377   if (c == nullptr) {
   1378     return "null";
   1379   }
   1380   return c->PrettyClass();
   1381 }
   1382 
   1383 std::string Class::PrettyClass() {
   1384   std::string result;
   1385   result += "java.lang.Class<";
   1386   result += PrettyDescriptor();
   1387   result += ">";
   1388   return result;
   1389 }
   1390 
   1391 std::string Class::PrettyClassAndClassLoader(ObjPtr<mirror::Class> c) {
   1392   if (c == nullptr) {
   1393     return "null";
   1394   }
   1395   return c->PrettyClassAndClassLoader();
   1396 }
   1397 
   1398 std::string Class::PrettyClassAndClassLoader() {
   1399   std::string result;
   1400   result += "java.lang.Class<";
   1401   result += PrettyDescriptor();
   1402   result += ",";
   1403   result += mirror::Object::PrettyTypeOf(GetClassLoader());
   1404   // TODO: add an identifying hash value for the loader
   1405   result += ">";
   1406   return result;
   1407 }
   1408 
   1409 template<VerifyObjectFlags kVerifyFlags> void Class::GetAccessFlagsDCheck() {
   1410   // Check class is loaded/retired or this is java.lang.String that has a
   1411   // circularity issue during loading the names of its members
   1412   DCHECK(IsIdxLoaded<kVerifyFlags>() || IsRetired<kVerifyFlags>() ||
   1413          IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>() ||
   1414          this == String::GetJavaLangString())
   1415               << "IsIdxLoaded=" << IsIdxLoaded<kVerifyFlags>()
   1416               << " IsRetired=" << IsRetired<kVerifyFlags>()
   1417               << " IsErroneous=" <<
   1418               IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>()
   1419               << " IsString=" << (this == String::GetJavaLangString())
   1420               << " status= " << GetStatus<kVerifyFlags>()
   1421               << " descriptor=" << PrettyDescriptor();
   1422 }
   1423 // Instantiate the common cases.
   1424 template void Class::GetAccessFlagsDCheck<kVerifyNone>();
   1425 template void Class::GetAccessFlagsDCheck<kVerifyThis>();
   1426 template void Class::GetAccessFlagsDCheck<kVerifyReads>();
   1427 template void Class::GetAccessFlagsDCheck<kVerifyWrites>();
   1428 template void Class::GetAccessFlagsDCheck<kVerifyAll>();
   1429 
   1430 }  // namespace mirror
   1431 }  // namespace art
   1432