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