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