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 "art_field-inl.h"
     20 #include "art_method-inl.h"
     21 #include "class_linker.h"
     22 #include "class_loader.h"
     23 #include "class-inl.h"
     24 #include "dex_cache.h"
     25 #include "dex_file-inl.h"
     26 #include "gc/accounting/card_table-inl.h"
     27 #include "handle_scope-inl.h"
     28 #include "object_array-inl.h"
     29 #include "object-inl.h"
     30 #include "runtime.h"
     31 #include "thread.h"
     32 #include "throwable.h"
     33 #include "utils.h"
     34 #include "well_known_classes.h"
     35 
     36 namespace art {
     37 namespace mirror {
     38 
     39 GcRoot<Class> Class::java_lang_Class_;
     40 
     41 void Class::SetClassClass(Class* java_lang_Class) {
     42   CHECK(java_lang_Class_.IsNull())
     43       << java_lang_Class_.Read()
     44       << " " << java_lang_Class;
     45   CHECK(java_lang_Class != nullptr);
     46   java_lang_Class_ = GcRoot<Class>(java_lang_Class);
     47 }
     48 
     49 void Class::ResetClass() {
     50   CHECK(!java_lang_Class_.IsNull());
     51   java_lang_Class_ = GcRoot<Class>(nullptr);
     52 }
     53 
     54 void Class::VisitRoots(RootCallback* callback, void* arg) {
     55   java_lang_Class_.VisitRootIfNonNull(callback, arg, RootInfo(kRootStickyClass));
     56 }
     57 
     58 void Class::SetStatus(Status new_status, Thread* self) {
     59   Status old_status = GetStatus();
     60   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
     61   bool class_linker_initialized = class_linker != nullptr && class_linker->IsInitialized();
     62   if (LIKELY(class_linker_initialized)) {
     63     if (UNLIKELY(new_status <= old_status && new_status != kStatusError &&
     64                  new_status != kStatusRetired)) {
     65       LOG(FATAL) << "Unexpected change back of class status for " << PrettyClass(this) << " "
     66           << old_status << " -> " << new_status;
     67     }
     68     if (new_status >= kStatusResolved || old_status >= kStatusResolved) {
     69       // When classes are being resolved the resolution code should hold the lock.
     70       CHECK_EQ(GetLockOwnerThreadId(), self->GetThreadId())
     71             << "Attempt to change status of class while not holding its lock: "
     72             << PrettyClass(this) << " " << old_status << " -> " << new_status;
     73     }
     74   }
     75   if (UNLIKELY(new_status == kStatusError)) {
     76     CHECK_NE(GetStatus(), kStatusError)
     77         << "Attempt to set as erroneous an already erroneous class " << PrettyClass(this);
     78 
     79     // Stash current exception.
     80     StackHandleScope<3> hs(self);
     81     ThrowLocation old_throw_location;
     82     Handle<mirror::Throwable> old_exception(hs.NewHandle(self->GetException(&old_throw_location)));
     83     CHECK(old_exception.Get() != nullptr);
     84     Handle<mirror::Object> old_throw_this_object(hs.NewHandle(old_throw_location.GetThis()));
     85     Handle<mirror::ArtMethod> old_throw_method(hs.NewHandle(old_throw_location.GetMethod()));
     86     uint32_t old_throw_dex_pc = old_throw_location.GetDexPc();
     87     bool is_exception_reported = self->IsExceptionReportedToInstrumentation();
     88     Class* eiie_class;
     89     // Do't attempt to use FindClass if we have an OOM error since this can try to do more
     90     // allocations and may cause infinite loops.
     91     bool throw_eiie = (old_exception.Get() == nullptr);
     92     if (!throw_eiie) {
     93       std::string temp;
     94       const char* old_exception_descriptor = old_exception->GetClass()->GetDescriptor(&temp);
     95       throw_eiie = (strcmp(old_exception_descriptor, "Ljava/lang/OutOfMemoryError;") != 0);
     96     }
     97     if (throw_eiie) {
     98       // Clear exception to call FindSystemClass.
     99       self->ClearException();
    100       eiie_class = Runtime::Current()->GetClassLinker()->FindSystemClass(
    101           self, "Ljava/lang/ExceptionInInitializerError;");
    102       CHECK(!self->IsExceptionPending());
    103       // Only verification errors, not initialization problems, should set a verify error.
    104       // This is to ensure that ThrowEarlierClassFailure will throw NoClassDefFoundError in that
    105       // case.
    106       Class* exception_class = old_exception->GetClass();
    107       if (!eiie_class->IsAssignableFrom(exception_class)) {
    108         SetVerifyErrorClass(exception_class);
    109       }
    110     }
    111 
    112     // Restore exception.
    113     ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(),
    114                                          old_throw_dex_pc);
    115     self->SetException(gc_safe_throw_location, old_exception.Get());
    116     self->SetExceptionReportedToInstrumentation(is_exception_reported);
    117   }
    118   COMPILE_ASSERT(sizeof(Status) == sizeof(uint32_t), size_of_status_not_uint32);
    119   if (Runtime::Current()->IsActiveTransaction()) {
    120     SetField32Volatile<true>(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status);
    121   } else {
    122     SetField32Volatile<false>(OFFSET_OF_OBJECT_MEMBER(Class, status_), new_status);
    123   }
    124 
    125   if (!class_linker_initialized) {
    126     // When the class linker is being initialized its single threaded and by definition there can be
    127     // no waiters. During initialization classes may appear temporary but won't be retired as their
    128     // size was statically computed.
    129   } else {
    130     // Classes that are being resolved or initialized need to notify waiters that the class status
    131     // changed. See ClassLinker::EnsureResolved and ClassLinker::WaitForInitializeClass.
    132     if (IsTemp()) {
    133       // Class is a temporary one, ensure that waiters for resolution get notified of retirement
    134       // so that they can grab the new version of the class from the class linker's table.
    135       CHECK_LT(new_status, kStatusResolved) << PrettyDescriptor(this);
    136       if (new_status == kStatusRetired || new_status == kStatusError) {
    137         NotifyAll(self);
    138       }
    139     } else {
    140       CHECK_NE(new_status, kStatusRetired);
    141       if (old_status >= kStatusResolved || new_status >= kStatusResolved) {
    142         NotifyAll(self);
    143       }
    144     }
    145   }
    146 }
    147 
    148 void Class::SetDexCache(DexCache* new_dex_cache) {
    149   SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache);
    150   SetDexCacheStrings(new_dex_cache != nullptr ? new_dex_cache->GetStrings() : nullptr);
    151 }
    152 
    153 void Class::SetClassSize(uint32_t new_class_size) {
    154   if (kIsDebugBuild && (new_class_size < GetClassSize())) {
    155     DumpClass(LOG(ERROR), kDumpClassFullDetail);
    156     CHECK_GE(new_class_size, GetClassSize()) << " class=" << PrettyTypeOf(this);
    157   }
    158   // Not called within a transaction.
    159   SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size);
    160 }
    161 
    162 // Return the class' name. The exact format is bizarre, but it's the specified behavior for
    163 // Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
    164 // but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
    165 // slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
    166 String* Class::ComputeName(Handle<Class> h_this) {
    167   String* name = h_this->GetName();
    168   if (name != nullptr) {
    169     return name;
    170   }
    171   std::string temp;
    172   const char* descriptor = h_this->GetDescriptor(&temp);
    173   Thread* self = Thread::Current();
    174   if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
    175     // The descriptor indicates that this is the class for
    176     // a primitive type; special-case the return value.
    177     const char* c_name = nullptr;
    178     switch (descriptor[0]) {
    179     case 'Z': c_name = "boolean"; break;
    180     case 'B': c_name = "byte";    break;
    181     case 'C': c_name = "char";    break;
    182     case 'S': c_name = "short";   break;
    183     case 'I': c_name = "int";     break;
    184     case 'J': c_name = "long";    break;
    185     case 'F': c_name = "float";   break;
    186     case 'D': c_name = "double";  break;
    187     case 'V': c_name = "void";    break;
    188     default:
    189       LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
    190     }
    191     name = String::AllocFromModifiedUtf8(self, c_name);
    192   } else {
    193     // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
    194     // components.
    195     name = String::AllocFromModifiedUtf8(self, DescriptorToDot(descriptor).c_str());
    196   }
    197   h_this->SetName(name);
    198   return name;
    199 }
    200 
    201 void Class::DumpClass(std::ostream& os, int flags) {
    202   if ((flags & kDumpClassFullDetail) == 0) {
    203     os << PrettyClass(this);
    204     if ((flags & kDumpClassClassLoader) != 0) {
    205       os << ' ' << GetClassLoader();
    206     }
    207     if ((flags & kDumpClassInitialized) != 0) {
    208       os << ' ' << GetStatus();
    209     }
    210     os << "\n";
    211     return;
    212   }
    213 
    214   Thread* self = Thread::Current();
    215   StackHandleScope<2> hs(self);
    216   Handle<mirror::Class> h_this(hs.NewHandle(this));
    217   Handle<mirror::Class> h_super(hs.NewHandle(GetSuperClass()));
    218 
    219   std::string temp;
    220   os << "----- " << (IsInterface() ? "interface" : "class") << " "
    221      << "'" << GetDescriptor(&temp) << "' cl=" << GetClassLoader() << " -----\n",
    222   os << "  objectSize=" << SizeOf() << " "
    223      << "(" << (h_super.Get() != nullptr ? h_super->SizeOf() : -1) << " from super)\n",
    224   os << StringPrintf("  access=0x%04x.%04x\n",
    225       GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
    226   if (h_super.Get() != nullptr) {
    227     os << "  super='" << PrettyClass(h_super.Get()) << "' (cl=" << h_super->GetClassLoader()
    228        << ")\n";
    229   }
    230   if (IsArrayClass()) {
    231     os << "  componentType=" << PrettyClass(GetComponentType()) << "\n";
    232   }
    233   const size_t num_direct_interfaces = NumDirectInterfaces();
    234   if (num_direct_interfaces > 0) {
    235     os << "  interfaces (" << num_direct_interfaces << "):\n";
    236     for (size_t i = 0; i < num_direct_interfaces; ++i) {
    237       Class* interface = GetDirectInterface(self, h_this, i);
    238       const ClassLoader* cl = interface->GetClassLoader();
    239       os << StringPrintf("    %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl);
    240     }
    241   }
    242   if (!IsLoaded()) {
    243     os << "  class not yet loaded";
    244   } else {
    245     // After this point, this may have moved due to GetDirectInterface.
    246     os << "  vtable (" << h_this->NumVirtualMethods() << " entries, "
    247         << (h_super.Get() != nullptr ? h_super->NumVirtualMethods() : 0) << " in super):\n";
    248     for (size_t i = 0; i < NumVirtualMethods(); ++i) {
    249       os << StringPrintf("    %2zd: %s\n", i,
    250                          PrettyMethod(h_this->GetVirtualMethodDuringLinking(i)).c_str());
    251     }
    252     os << "  direct methods (" << h_this->NumDirectMethods() << " entries):\n";
    253     for (size_t i = 0; i < h_this->NumDirectMethods(); ++i) {
    254       os << StringPrintf("    %2zd: %s\n", i, PrettyMethod(h_this->GetDirectMethod(i)).c_str());
    255     }
    256     if (h_this->NumStaticFields() > 0) {
    257       os << "  static fields (" << h_this->NumStaticFields() << " entries):\n";
    258       if (h_this->IsResolved() || h_this->IsErroneous()) {
    259         for (size_t i = 0; i < h_this->NumStaticFields(); ++i) {
    260           os << StringPrintf("    %2zd: %s\n", i, PrettyField(h_this->GetStaticField(i)).c_str());
    261         }
    262       } else {
    263         os << "    <not yet available>";
    264       }
    265     }
    266     if (h_this->NumInstanceFields() > 0) {
    267       os << "  instance fields (" << h_this->NumInstanceFields() << " entries):\n";
    268       if (h_this->IsResolved() || h_this->IsErroneous()) {
    269         for (size_t i = 0; i < h_this->NumInstanceFields(); ++i) {
    270           os << StringPrintf("    %2zd: %s\n", i, PrettyField(h_this->GetInstanceField(i)).c_str());
    271         }
    272       } else {
    273         os << "    <not yet available>";
    274       }
    275     }
    276   }
    277 }
    278 
    279 void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
    280   if (new_reference_offsets != CLASS_WALK_SUPER) {
    281     // Sanity check that the number of bits set in the reference offset bitmap
    282     // agrees with the number of references
    283     size_t count = 0;
    284     for (Class* c = this; c != nullptr; c = c->GetSuperClass()) {
    285       count += c->NumReferenceInstanceFieldsDuringLinking();
    286     }
    287     CHECK_EQ((size_t)POPCOUNT(new_reference_offsets), count);
    288   }
    289   // Not called within a transaction.
    290   SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
    291                     new_reference_offsets);
    292 }
    293 
    294 void Class::SetReferenceStaticOffsets(uint32_t new_reference_offsets) {
    295   if (new_reference_offsets != CLASS_WALK_SUPER) {
    296     // Sanity check that the number of bits set in the reference offset bitmap
    297     // agrees with the number of references
    298     CHECK_EQ((size_t)POPCOUNT(new_reference_offsets),
    299              NumReferenceStaticFieldsDuringLinking());
    300   }
    301   // Not called within a transaction.
    302   SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_static_offsets_),
    303                     new_reference_offsets);
    304 }
    305 
    306 bool Class::IsInSamePackage(const StringPiece& descriptor1, const StringPiece& descriptor2) {
    307   size_t i = 0;
    308   while (descriptor1[i] != '\0' && descriptor1[i] == descriptor2[i]) {
    309     ++i;
    310   }
    311   if (descriptor1.find('/', i) != StringPiece::npos ||
    312       descriptor2.find('/', i) != StringPiece::npos) {
    313     return false;
    314   } else {
    315     return true;
    316   }
    317 }
    318 
    319 bool Class::IsInSamePackage(Class* that) {
    320   Class* klass1 = this;
    321   Class* klass2 = that;
    322   if (klass1 == klass2) {
    323     return true;
    324   }
    325   // Class loaders must match.
    326   if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
    327     return false;
    328   }
    329   // Arrays are in the same package when their element classes are.
    330   while (klass1->IsArrayClass()) {
    331     klass1 = klass1->GetComponentType();
    332   }
    333   while (klass2->IsArrayClass()) {
    334     klass2 = klass2->GetComponentType();
    335   }
    336   // trivial check again for array types
    337   if (klass1 == klass2) {
    338     return true;
    339   }
    340   // Compare the package part of the descriptor string.
    341   std::string temp1, temp2;
    342   return IsInSamePackage(klass1->GetDescriptor(&temp1), klass2->GetDescriptor(&temp2));
    343 }
    344 
    345 bool Class::IsStringClass() const {
    346   return this == String::GetJavaLangString();
    347 }
    348 
    349 bool Class::IsThrowableClass() {
    350   return WellKnownClasses::ToClass(WellKnownClasses::java_lang_Throwable)->IsAssignableFrom(this);
    351 }
    352 
    353 void Class::SetClassLoader(ClassLoader* new_class_loader) {
    354   if (Runtime::Current()->IsActiveTransaction()) {
    355     SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
    356   } else {
    357     SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
    358   }
    359 }
    360 
    361 ArtMethod* Class::FindInterfaceMethod(const StringPiece& name, const StringPiece& signature) {
    362   // Check the current class before checking the interfaces.
    363   ArtMethod* method = FindDeclaredVirtualMethod(name, signature);
    364   if (method != nullptr) {
    365     return method;
    366   }
    367 
    368   int32_t iftable_count = GetIfTableCount();
    369   IfTable* iftable = GetIfTable();
    370   for (int32_t i = 0; i < iftable_count; ++i) {
    371     method = iftable->GetInterface(i)->FindDeclaredVirtualMethod(name, signature);
    372     if (method != nullptr) {
    373       return method;
    374     }
    375   }
    376   return nullptr;
    377 }
    378 
    379 ArtMethod* Class::FindInterfaceMethod(const StringPiece& name, const Signature& signature) {
    380   // Check the current class before checking the interfaces.
    381   ArtMethod* method = FindDeclaredVirtualMethod(name, signature);
    382   if (method != nullptr) {
    383     return method;
    384   }
    385 
    386   int32_t iftable_count = GetIfTableCount();
    387   IfTable* iftable = GetIfTable();
    388   for (int32_t i = 0; i < iftable_count; ++i) {
    389     method = iftable->GetInterface(i)->FindDeclaredVirtualMethod(name, signature);
    390     if (method != nullptr) {
    391       return method;
    392     }
    393   }
    394   return nullptr;
    395 }
    396 
    397 ArtMethod* Class::FindInterfaceMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
    398   // Check the current class before checking the interfaces.
    399   ArtMethod* method = FindDeclaredVirtualMethod(dex_cache, dex_method_idx);
    400   if (method != nullptr) {
    401     return method;
    402   }
    403 
    404   int32_t iftable_count = GetIfTableCount();
    405   IfTable* iftable = GetIfTable();
    406   for (int32_t i = 0; i < iftable_count; ++i) {
    407     method = iftable->GetInterface(i)->FindDeclaredVirtualMethod(dex_cache, dex_method_idx);
    408     if (method != nullptr) {
    409       return method;
    410     }
    411   }
    412   return nullptr;
    413 }
    414 
    415 ArtMethod* Class::FindDeclaredDirectMethod(const StringPiece& name, const StringPiece& signature) {
    416   for (size_t i = 0; i < NumDirectMethods(); ++i) {
    417     ArtMethod* method = GetDirectMethod(i);
    418     if (name == method->GetName() && method->GetSignature() == signature) {
    419       return method;
    420     }
    421   }
    422   return nullptr;
    423 }
    424 
    425 ArtMethod* Class::FindDeclaredDirectMethod(const StringPiece& name, const Signature& signature) {
    426   for (size_t i = 0; i < NumDirectMethods(); ++i) {
    427     ArtMethod* method = GetDirectMethod(i);
    428     if (name == method->GetName() && signature == method->GetSignature()) {
    429       return method;
    430     }
    431   }
    432   return nullptr;
    433 }
    434 
    435 ArtMethod* Class::FindDeclaredDirectMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
    436   if (GetDexCache() == dex_cache) {
    437     for (size_t i = 0; i < NumDirectMethods(); ++i) {
    438       ArtMethod* method = GetDirectMethod(i);
    439       if (method->GetDexMethodIndex() == dex_method_idx) {
    440         return method;
    441       }
    442     }
    443   }
    444   return nullptr;
    445 }
    446 
    447 ArtMethod* Class::FindDirectMethod(const StringPiece& name, const StringPiece& signature) {
    448   for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
    449     ArtMethod* method = klass->FindDeclaredDirectMethod(name, signature);
    450     if (method != nullptr) {
    451       return method;
    452     }
    453   }
    454   return nullptr;
    455 }
    456 
    457 ArtMethod* Class::FindDirectMethod(const StringPiece& name, const Signature& signature) {
    458   for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
    459     ArtMethod* method = klass->FindDeclaredDirectMethod(name, signature);
    460     if (method != nullptr) {
    461       return method;
    462     }
    463   }
    464   return nullptr;
    465 }
    466 
    467 ArtMethod* Class::FindDirectMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
    468   for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
    469     ArtMethod* method = klass->FindDeclaredDirectMethod(dex_cache, dex_method_idx);
    470     if (method != nullptr) {
    471       return method;
    472     }
    473   }
    474   return nullptr;
    475 }
    476 
    477 ArtMethod* Class::FindDeclaredVirtualMethod(const StringPiece& name, const StringPiece& signature) {
    478   for (size_t i = 0; i < NumVirtualMethods(); ++i) {
    479     ArtMethod* method = GetVirtualMethod(i);
    480     if (name == method->GetName() && method->GetSignature() == signature) {
    481       return method;
    482     }
    483   }
    484   return nullptr;
    485 }
    486 
    487 ArtMethod* Class::FindDeclaredVirtualMethod(const StringPiece& name, const Signature& signature) {
    488   for (size_t i = 0; i < NumVirtualMethods(); ++i) {
    489     ArtMethod* method = GetVirtualMethod(i);
    490     if (name == method->GetName() && signature == method->GetSignature()) {
    491       return method;
    492     }
    493   }
    494   return nullptr;
    495 }
    496 
    497 ArtMethod* Class::FindDeclaredVirtualMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
    498   if (GetDexCache() == dex_cache) {
    499     for (size_t i = 0; i < NumVirtualMethods(); ++i) {
    500       ArtMethod* method = GetVirtualMethod(i);
    501       if (method->GetDexMethodIndex() == dex_method_idx &&
    502           // A miranda method may have a different DexCache and is always created by linking,
    503           // never *declared* in the class.
    504           !method->IsMiranda()) {
    505         return method;
    506       }
    507     }
    508   }
    509   return nullptr;
    510 }
    511 
    512 ArtMethod* Class::FindVirtualMethod(const StringPiece& name, const StringPiece& signature) {
    513   for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
    514     ArtMethod* method = klass->FindDeclaredVirtualMethod(name, signature);
    515     if (method != nullptr) {
    516       return method;
    517     }
    518   }
    519   return nullptr;
    520 }
    521 
    522 ArtMethod* Class::FindVirtualMethod(const StringPiece& name, const Signature& signature) {
    523   for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
    524     ArtMethod* method = klass->FindDeclaredVirtualMethod(name, signature);
    525     if (method != nullptr) {
    526       return method;
    527     }
    528   }
    529   return nullptr;
    530 }
    531 
    532 ArtMethod* Class::FindVirtualMethod(const DexCache* dex_cache, uint32_t dex_method_idx) {
    533   for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
    534     ArtMethod* method = klass->FindDeclaredVirtualMethod(dex_cache, dex_method_idx);
    535     if (method != nullptr) {
    536       return method;
    537     }
    538   }
    539   return nullptr;
    540 }
    541 
    542 ArtMethod* Class::FindClassInitializer() {
    543   for (size_t i = 0; i < NumDirectMethods(); ++i) {
    544     ArtMethod* method = GetDirectMethod(i);
    545     if (method->IsClassInitializer()) {
    546       DCHECK_STREQ(method->GetName(), "<clinit>");
    547       DCHECK_STREQ(method->GetSignature().ToString().c_str(), "()V");
    548       return method;
    549     }
    550   }
    551   return nullptr;
    552 }
    553 
    554 ArtField* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
    555   // Is the field in this class?
    556   // Interfaces are not relevant because they can't contain instance fields.
    557   for (size_t i = 0; i < NumInstanceFields(); ++i) {
    558     ArtField* f = GetInstanceField(i);
    559     if (name == f->GetName() && type == f->GetTypeDescriptor()) {
    560       return f;
    561     }
    562   }
    563   return nullptr;
    564 }
    565 
    566 ArtField* Class::FindDeclaredInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) {
    567   if (GetDexCache() == dex_cache) {
    568     for (size_t i = 0; i < NumInstanceFields(); ++i) {
    569       ArtField* f = GetInstanceField(i);
    570       if (f->GetDexFieldIndex() == dex_field_idx) {
    571         return f;
    572       }
    573     }
    574   }
    575   return nullptr;
    576 }
    577 
    578 ArtField* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
    579   // Is the field in this class, or any of its superclasses?
    580   // Interfaces are not relevant because they can't contain instance fields.
    581   for (Class* c = this; c != nullptr; c = c->GetSuperClass()) {
    582     ArtField* f = c->FindDeclaredInstanceField(name, type);
    583     if (f != nullptr) {
    584       return f;
    585     }
    586   }
    587   return nullptr;
    588 }
    589 
    590 ArtField* Class::FindInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) {
    591   // Is the field in this class, or any of its superclasses?
    592   // Interfaces are not relevant because they can't contain instance fields.
    593   for (Class* c = this; c != nullptr; c = c->GetSuperClass()) {
    594     ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
    595     if (f != nullptr) {
    596       return f;
    597     }
    598   }
    599   return nullptr;
    600 }
    601 
    602 ArtField* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
    603   DCHECK(type != nullptr);
    604   for (size_t i = 0; i < NumStaticFields(); ++i) {
    605     ArtField* f = GetStaticField(i);
    606     if (name == f->GetName() && type == f->GetTypeDescriptor()) {
    607       return f;
    608     }
    609   }
    610   return nullptr;
    611 }
    612 
    613 ArtField* Class::FindDeclaredStaticField(const DexCache* dex_cache, uint32_t dex_field_idx) {
    614   if (dex_cache == GetDexCache()) {
    615     for (size_t i = 0; i < NumStaticFields(); ++i) {
    616       ArtField* f = GetStaticField(i);
    617       if (f->GetDexFieldIndex() == dex_field_idx) {
    618         return f;
    619       }
    620     }
    621   }
    622   return nullptr;
    623 }
    624 
    625 ArtField* Class::FindStaticField(Thread* self, Handle<Class> klass, const StringPiece& name,
    626                                  const StringPiece& type) {
    627   // Is the field in this class (or its interfaces), or any of its
    628   // superclasses (or their interfaces)?
    629   for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
    630     // Is the field in this class?
    631     ArtField* f = k->FindDeclaredStaticField(name, type);
    632     if (f != nullptr) {
    633       return f;
    634     }
    635     // Wrap k incase it moves during GetDirectInterface.
    636     StackHandleScope<1> hs(self);
    637     HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
    638     // Is this field in any of this class' interfaces?
    639     for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
    640       StackHandleScope<1> hs(self);
    641       Handle<mirror::Class> interface(hs.NewHandle(GetDirectInterface(self, h_k, i)));
    642       f = FindStaticField(self, interface, name, type);
    643       if (f != nullptr) {
    644         return f;
    645       }
    646     }
    647   }
    648   return nullptr;
    649 }
    650 
    651 ArtField* Class::FindStaticField(Thread* self, Handle<Class> klass, const DexCache* dex_cache,
    652                                  uint32_t dex_field_idx) {
    653   for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
    654     // Is the field in this class?
    655     ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
    656     if (f != nullptr) {
    657       return f;
    658     }
    659     // Wrap k incase it moves during GetDirectInterface.
    660     StackHandleScope<1> hs(self);
    661     HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
    662     // Is this field in any of this class' interfaces?
    663     for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
    664       StackHandleScope<1> hs(self);
    665       Handle<mirror::Class> interface(hs.NewHandle(GetDirectInterface(self, h_k, i)));
    666       f = FindStaticField(self, interface, dex_cache, dex_field_idx);
    667       if (f != nullptr) {
    668         return f;
    669       }
    670     }
    671   }
    672   return nullptr;
    673 }
    674 
    675 ArtField* Class::FindField(Thread* self, Handle<Class> klass, const StringPiece& name,
    676                            const StringPiece& type) {
    677   // Find a field using the JLS field resolution order
    678   for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
    679     // Is the field in this class?
    680     ArtField* f = k->FindDeclaredInstanceField(name, type);
    681     if (f != nullptr) {
    682       return f;
    683     }
    684     f = k->FindDeclaredStaticField(name, type);
    685     if (f != nullptr) {
    686       return f;
    687     }
    688     // Is this field in any of this class' interfaces?
    689     StackHandleScope<1> hs(self);
    690     HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
    691     for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
    692       StackHandleScope<1> hs(self);
    693       Handle<mirror::Class> interface(hs.NewHandle(GetDirectInterface(self, h_k, i)));
    694       f = interface->FindStaticField(self, interface, name, type);
    695       if (f != nullptr) {
    696         return f;
    697       }
    698     }
    699   }
    700   return nullptr;
    701 }
    702 
    703 static void SetPreverifiedFlagOnMethods(mirror::ObjectArray<mirror::ArtMethod>* methods)
    704     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
    705   if (methods != nullptr) {
    706     for (int32_t index = 0, end = methods->GetLength(); index < end; ++index) {
    707       mirror::ArtMethod* method = methods->GetWithoutChecks(index);
    708       DCHECK(method != nullptr);
    709       if (!method->IsNative() && !method->IsAbstract()) {
    710         method->SetPreverified();
    711       }
    712     }
    713   }
    714 }
    715 
    716 void Class::SetPreverifiedFlagOnAllMethods() {
    717   DCHECK(IsVerified());
    718   SetPreverifiedFlagOnMethods(GetDirectMethods());
    719   SetPreverifiedFlagOnMethods(GetVirtualMethods());
    720 }
    721 
    722 const char* Class::GetDescriptor(std::string* storage) {
    723   if (IsPrimitive()) {
    724     return Primitive::Descriptor(GetPrimitiveType());
    725   } else if (IsArrayClass()) {
    726     return GetArrayDescriptor(storage);
    727   } else if (IsProxyClass()) {
    728     *storage = Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this);
    729     return storage->c_str();
    730   } else {
    731     const DexFile& dex_file = GetDexFile();
    732     const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
    733     return dex_file.GetTypeDescriptor(type_id);
    734   }
    735 }
    736 
    737 const char* Class::GetArrayDescriptor(std::string* storage) {
    738   std::string temp;
    739   const char* elem_desc = GetComponentType()->GetDescriptor(&temp);
    740   *storage = "[";
    741   *storage += elem_desc;
    742   return storage->c_str();
    743 }
    744 
    745 const DexFile::ClassDef* Class::GetClassDef() {
    746   uint16_t class_def_idx = GetDexClassDefIndex();
    747   if (class_def_idx == DexFile::kDexNoIndex16) {
    748     return nullptr;
    749   }
    750   return &GetDexFile().GetClassDef(class_def_idx);
    751 }
    752 
    753 uint16_t Class::GetDirectInterfaceTypeIdx(uint32_t idx) {
    754   DCHECK(!IsPrimitive());
    755   DCHECK(!IsArrayClass());
    756   return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_;
    757 }
    758 
    759 mirror::Class* Class::GetDirectInterface(Thread* self, Handle<mirror::Class> klass, uint32_t idx) {
    760   DCHECK(klass.Get() != nullptr);
    761   DCHECK(!klass->IsPrimitive());
    762   if (klass->IsArrayClass()) {
    763     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
    764     if (idx == 0) {
    765       return class_linker->FindSystemClass(self, "Ljava/lang/Cloneable;");
    766     } else {
    767       DCHECK_EQ(1U, idx);
    768       return class_linker->FindSystemClass(self, "Ljava/io/Serializable;");
    769     }
    770   } else if (klass->IsProxyClass()) {
    771     mirror::ObjectArray<mirror::Class>* interfaces = klass.Get()->GetInterfaces();
    772     DCHECK(interfaces != nullptr);
    773     return interfaces->Get(idx);
    774   } else {
    775     uint16_t type_idx = klass->GetDirectInterfaceTypeIdx(idx);
    776     mirror::Class* interface = klass->GetDexCache()->GetResolvedType(type_idx);
    777     if (interface == nullptr) {
    778       interface = Runtime::Current()->GetClassLinker()->ResolveType(klass->GetDexFile(), type_idx,
    779                                                                     klass.Get());
    780       CHECK(interface != nullptr || self->IsExceptionPending());
    781     }
    782     return interface;
    783   }
    784 }
    785 
    786 const char* Class::GetSourceFile() {
    787   const DexFile& dex_file = GetDexFile();
    788   const DexFile::ClassDef* dex_class_def = GetClassDef();
    789   if (dex_class_def == nullptr) {
    790     // Generated classes have no class def.
    791     return nullptr;
    792   }
    793   return dex_file.GetSourceFile(*dex_class_def);
    794 }
    795 
    796 std::string Class::GetLocation() {
    797   mirror::DexCache* dex_cache = GetDexCache();
    798   if (dex_cache != nullptr && !IsProxyClass()) {
    799     return dex_cache->GetLocation()->ToModifiedUtf8();
    800   }
    801   // Arrays and proxies are generated and have no corresponding dex file location.
    802   return "generated class";
    803 }
    804 
    805 const DexFile::TypeList* Class::GetInterfaceTypeList() {
    806   const DexFile::ClassDef* class_def = GetClassDef();
    807   if (class_def == nullptr) {
    808     return nullptr;
    809   }
    810   return GetDexFile().GetInterfacesList(*class_def);
    811 }
    812 
    813 void Class::PopulateEmbeddedImtAndVTable(StackHandleScope<kImtSize>* imt_handle_scope) {
    814   for (uint32_t i = 0; i < kImtSize; i++) {
    815     // Replace null with conflict.
    816     mirror::Object* obj = imt_handle_scope->GetReference(i);
    817     DCHECK(obj != nullptr);
    818     SetEmbeddedImTableEntry(i, obj->AsArtMethod());
    819   }
    820 
    821   ObjectArray<ArtMethod>* table = GetVTableDuringLinking();
    822   CHECK(table != nullptr) << PrettyClass(this);
    823   SetEmbeddedVTableLength(table->GetLength());
    824   for (int32_t i = 0; i < table->GetLength(); i++) {
    825     SetEmbeddedVTableEntry(i, table->GetWithoutChecks(i));
    826   }
    827 
    828   // Keep java.lang.Object class's vtable around for since it's easier
    829   // to be reused by array classes during their linking.
    830   if (!IsObjectClass()) {
    831     SetVTable(nullptr);
    832   }
    833 }
    834 
    835 // The pre-fence visitor for Class::CopyOf().
    836 class CopyClassVisitor {
    837  public:
    838   explicit CopyClassVisitor(Thread* self, Handle<mirror::Class>* orig,
    839                             size_t new_length, size_t copy_bytes,
    840                             StackHandleScope<mirror::Class::kImtSize>* imt_handle_scope)
    841       : self_(self), orig_(orig), new_length_(new_length),
    842         copy_bytes_(copy_bytes), imt_handle_scope_(imt_handle_scope) {
    843   }
    844 
    845   void operator()(Object* obj, size_t usable_size) const
    846       SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
    847     UNUSED(usable_size);
    848     mirror::Class* new_class_obj = obj->AsClass();
    849     mirror::Object::CopyObject(self_, new_class_obj, orig_->Get(), copy_bytes_);
    850     new_class_obj->SetStatus(Class::kStatusResolving, self_);
    851     new_class_obj->PopulateEmbeddedImtAndVTable(imt_handle_scope_);
    852     new_class_obj->SetClassSize(new_length_);
    853   }
    854 
    855  private:
    856   Thread* const self_;
    857   Handle<mirror::Class>* const orig_;
    858   const size_t new_length_;
    859   const size_t copy_bytes_;
    860   StackHandleScope<mirror::Class::kImtSize>* const imt_handle_scope_;
    861   DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor);
    862 };
    863 
    864 Class* Class::CopyOf(Thread* self, int32_t new_length,
    865                      StackHandleScope<kImtSize>* imt_handle_scope) {
    866   DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class)));
    867   // We may get copied by a compacting GC.
    868   StackHandleScope<1> hs(self);
    869   Handle<mirror::Class> h_this(hs.NewHandle(this));
    870   gc::Heap* heap = Runtime::Current()->GetHeap();
    871   // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf()
    872   // to skip copying the tail part that we will overwrite here.
    873   CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class), imt_handle_scope);
    874   mirror::Object* new_class =
    875       kMovingClasses
    876          ? heap->AllocObject<true>(self, java_lang_Class_.Read(), new_length, visitor)
    877          : heap->AllocNonMovableObject<true>(self, java_lang_Class_.Read(), new_length, visitor);
    878   if (UNLIKELY(new_class == nullptr)) {
    879     CHECK(self->IsExceptionPending());  // Expect an OOME.
    880     return nullptr;
    881   }
    882   return new_class->AsClass();
    883 }
    884 
    885 }  // namespace mirror
    886 }  // namespace art
    887