class.cc revision 0042c6d49b8488c78f0b937063e316e8d6244439
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::FindDeclaredVirtualMethodByName(const StringPiece& name, size_t pointer_size) {
509  for (auto& method : GetVirtualMethods(pointer_size)) {
510    ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
511    if (name == np_method->GetName()) {
512      return &method;
513    }
514  }
515  return nullptr;
516}
517
518ArtMethod* Class::FindVirtualMethod(
519    const StringPiece& name, const StringPiece& signature, size_t pointer_size) {
520  for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
521    ArtMethod* method = klass->FindDeclaredVirtualMethod(name, signature, pointer_size);
522    if (method != nullptr) {
523      return method;
524    }
525  }
526  return nullptr;
527}
528
529ArtMethod* Class::FindVirtualMethod(
530    const StringPiece& name, const Signature& signature, size_t pointer_size) {
531  for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
532    ArtMethod* method = klass->FindDeclaredVirtualMethod(name, signature, pointer_size);
533    if (method != nullptr) {
534      return method;
535    }
536  }
537  return nullptr;
538}
539
540ArtMethod* Class::FindVirtualMethod(
541    const DexCache* dex_cache, uint32_t dex_method_idx, size_t pointer_size) {
542  for (Class* klass = this; klass != nullptr; klass = klass->GetSuperClass()) {
543    ArtMethod* method = klass->FindDeclaredVirtualMethod(dex_cache, dex_method_idx, pointer_size);
544    if (method != nullptr) {
545      return method;
546    }
547  }
548  return nullptr;
549}
550
551ArtMethod* Class::FindClassInitializer(size_t pointer_size) {
552  for (ArtMethod& method : GetDirectMethods(pointer_size)) {
553    if (method.IsClassInitializer()) {
554      DCHECK_STREQ(method.GetName(), "<clinit>");
555      DCHECK_STREQ(method.GetSignature().ToString().c_str(), "()V");
556      return &method;
557    }
558  }
559  return nullptr;
560}
561
562ArtField* Class::FindDeclaredInstanceField(const StringPiece& name, const StringPiece& type) {
563  // Is the field in this class?
564  // Interfaces are not relevant because they can't contain instance fields.
565  for (size_t i = 0; i < NumInstanceFields(); ++i) {
566    ArtField* f = GetInstanceField(i);
567    if (name == f->GetName() && type == f->GetTypeDescriptor()) {
568      return f;
569    }
570  }
571  return nullptr;
572}
573
574ArtField* Class::FindDeclaredInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) {
575  if (GetDexCache() == dex_cache) {
576    for (size_t i = 0; i < NumInstanceFields(); ++i) {
577      ArtField* f = GetInstanceField(i);
578      if (f->GetDexFieldIndex() == dex_field_idx) {
579        return f;
580      }
581    }
582  }
583  return nullptr;
584}
585
586ArtField* Class::FindInstanceField(const StringPiece& name, const StringPiece& type) {
587  // Is the field in this class, or any of its superclasses?
588  // Interfaces are not relevant because they can't contain instance fields.
589  for (Class* c = this; c != nullptr; c = c->GetSuperClass()) {
590    ArtField* f = c->FindDeclaredInstanceField(name, type);
591    if (f != nullptr) {
592      return f;
593    }
594  }
595  return nullptr;
596}
597
598ArtField* Class::FindInstanceField(const DexCache* dex_cache, uint32_t dex_field_idx) {
599  // Is the field in this class, or any of its superclasses?
600  // Interfaces are not relevant because they can't contain instance fields.
601  for (Class* c = this; c != nullptr; c = c->GetSuperClass()) {
602    ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
603    if (f != nullptr) {
604      return f;
605    }
606  }
607  return nullptr;
608}
609
610ArtField* Class::FindDeclaredStaticField(const StringPiece& name, const StringPiece& type) {
611  DCHECK(type != nullptr);
612  for (size_t i = 0; i < NumStaticFields(); ++i) {
613    ArtField* f = GetStaticField(i);
614    if (name == f->GetName() && type == f->GetTypeDescriptor()) {
615      return f;
616    }
617  }
618  return nullptr;
619}
620
621ArtField* Class::FindDeclaredStaticField(const DexCache* dex_cache, uint32_t dex_field_idx) {
622  if (dex_cache == GetDexCache()) {
623    for (size_t i = 0; i < NumStaticFields(); ++i) {
624      ArtField* f = GetStaticField(i);
625      if (f->GetDexFieldIndex() == dex_field_idx) {
626        return f;
627      }
628    }
629  }
630  return nullptr;
631}
632
633ArtField* Class::FindStaticField(Thread* self, Handle<Class> klass, const StringPiece& name,
634                                 const StringPiece& type) {
635  // Is the field in this class (or its interfaces), or any of its
636  // superclasses (or their interfaces)?
637  for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
638    // Is the field in this class?
639    ArtField* f = k->FindDeclaredStaticField(name, type);
640    if (f != nullptr) {
641      return f;
642    }
643    // Wrap k incase it moves during GetDirectInterface.
644    StackHandleScope<1> hs(self);
645    HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
646    // Is this field in any of this class' interfaces?
647    for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
648      StackHandleScope<1> hs2(self);
649      Handle<mirror::Class> interface(hs2.NewHandle(GetDirectInterface(self, h_k, i)));
650      f = FindStaticField(self, interface, name, type);
651      if (f != nullptr) {
652        return f;
653      }
654    }
655  }
656  return nullptr;
657}
658
659ArtField* Class::FindStaticField(Thread* self, Handle<Class> klass, const DexCache* dex_cache,
660                                 uint32_t dex_field_idx) {
661  for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
662    // Is the field in this class?
663    ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
664    if (f != nullptr) {
665      return f;
666    }
667    // Wrap k incase it moves during GetDirectInterface.
668    StackHandleScope<1> hs(self);
669    HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
670    // Is this field in any of this class' interfaces?
671    for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
672      StackHandleScope<1> hs2(self);
673      Handle<mirror::Class> interface(hs2.NewHandle(GetDirectInterface(self, h_k, i)));
674      f = FindStaticField(self, interface, dex_cache, dex_field_idx);
675      if (f != nullptr) {
676        return f;
677      }
678    }
679  }
680  return nullptr;
681}
682
683ArtField* Class::FindField(Thread* self, Handle<Class> klass, const StringPiece& name,
684                           const StringPiece& type) {
685  // Find a field using the JLS field resolution order
686  for (Class* k = klass.Get(); k != nullptr; k = k->GetSuperClass()) {
687    // Is the field in this class?
688    ArtField* f = k->FindDeclaredInstanceField(name, type);
689    if (f != nullptr) {
690      return f;
691    }
692    f = k->FindDeclaredStaticField(name, type);
693    if (f != nullptr) {
694      return f;
695    }
696    // Is this field in any of this class' interfaces?
697    StackHandleScope<1> hs(self);
698    HandleWrapper<mirror::Class> h_k(hs.NewHandleWrapper(&k));
699    for (uint32_t i = 0; i < h_k->NumDirectInterfaces(); ++i) {
700      StackHandleScope<1> hs2(self);
701      Handle<mirror::Class> interface(hs2.NewHandle(GetDirectInterface(self, h_k, i)));
702      f = interface->FindStaticField(self, interface, name, type);
703      if (f != nullptr) {
704        return f;
705      }
706    }
707  }
708  return nullptr;
709}
710
711void Class::SetPreverifiedFlagOnAllMethods(size_t pointer_size) {
712  DCHECK(IsVerified());
713  for (auto& m : GetDirectMethods(pointer_size)) {
714    if (!m.IsNative() && !m.IsAbstract()) {
715      m.SetPreverified();
716    }
717  }
718  for (auto& m : GetVirtualMethods(pointer_size)) {
719    if (!m.IsNative() && !m.IsAbstract()) {
720      m.SetPreverified();
721    }
722  }
723}
724
725const char* Class::GetDescriptor(std::string* storage) {
726  if (IsPrimitive()) {
727    return Primitive::Descriptor(GetPrimitiveType());
728  } else if (IsArrayClass()) {
729    return GetArrayDescriptor(storage);
730  } else if (IsProxyClass()) {
731    *storage = Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this);
732    return storage->c_str();
733  } else {
734    const DexFile& dex_file = GetDexFile();
735    const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
736    return dex_file.GetTypeDescriptor(type_id);
737  }
738}
739
740const char* Class::GetArrayDescriptor(std::string* storage) {
741  std::string temp;
742  const char* elem_desc = GetComponentType()->GetDescriptor(&temp);
743  *storage = "[";
744  *storage += elem_desc;
745  return storage->c_str();
746}
747
748const DexFile::ClassDef* Class::GetClassDef() {
749  uint16_t class_def_idx = GetDexClassDefIndex();
750  if (class_def_idx == DexFile::kDexNoIndex16) {
751    return nullptr;
752  }
753  return &GetDexFile().GetClassDef(class_def_idx);
754}
755
756uint16_t Class::GetDirectInterfaceTypeIdx(uint32_t idx) {
757  DCHECK(!IsPrimitive());
758  DCHECK(!IsArrayClass());
759  return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_;
760}
761
762mirror::Class* Class::GetDirectInterface(Thread* self, Handle<mirror::Class> klass,
763                                         uint32_t idx) {
764  DCHECK(klass.Get() != nullptr);
765  DCHECK(!klass->IsPrimitive());
766  if (klass->IsArrayClass()) {
767    ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
768    if (idx == 0) {
769      return class_linker->FindSystemClass(self, "Ljava/lang/Cloneable;");
770    } else {
771      DCHECK_EQ(1U, idx);
772      return class_linker->FindSystemClass(self, "Ljava/io/Serializable;");
773    }
774  } else if (klass->IsProxyClass()) {
775    mirror::ObjectArray<mirror::Class>* interfaces = klass.Get()->GetInterfaces();
776    DCHECK(interfaces != nullptr);
777    return interfaces->Get(idx);
778  } else {
779    uint16_t type_idx = klass->GetDirectInterfaceTypeIdx(idx);
780    mirror::Class* interface = klass->GetDexCache()->GetResolvedType(type_idx);
781    if (interface == nullptr) {
782      interface = Runtime::Current()->GetClassLinker()->ResolveType(klass->GetDexFile(), type_idx,
783                                                                    klass.Get());
784      CHECK(interface != nullptr || self->IsExceptionPending());
785    }
786    return interface;
787  }
788}
789
790const char* Class::GetSourceFile() {
791  const DexFile& dex_file = GetDexFile();
792  const DexFile::ClassDef* dex_class_def = GetClassDef();
793  if (dex_class_def == nullptr) {
794    // Generated classes have no class def.
795    return nullptr;
796  }
797  return dex_file.GetSourceFile(*dex_class_def);
798}
799
800std::string Class::GetLocation() {
801  mirror::DexCache* dex_cache = GetDexCache();
802  if (dex_cache != nullptr && !IsProxyClass()) {
803    return dex_cache->GetLocation()->ToModifiedUtf8();
804  }
805  // Arrays and proxies are generated and have no corresponding dex file location.
806  return "generated class";
807}
808
809const DexFile::TypeList* Class::GetInterfaceTypeList() {
810  const DexFile::ClassDef* class_def = GetClassDef();
811  if (class_def == nullptr) {
812    return nullptr;
813  }
814  return GetDexFile().GetInterfacesList(*class_def);
815}
816
817void Class::PopulateEmbeddedImtAndVTable(ArtMethod* const (&methods)[kImtSize],
818                                         size_t pointer_size) {
819  for (size_t i = 0; i < kImtSize; i++) {
820    auto method = methods[i];
821    DCHECK(method != nullptr);
822    SetEmbeddedImTableEntry(i, method, pointer_size);
823  }
824  PointerArray* table = GetVTableDuringLinking();
825  CHECK(table != nullptr) << PrettyClass(this);
826  const size_t table_length = table->GetLength();
827  SetEmbeddedVTableLength(table_length);
828  for (size_t i = 0; i < table_length; i++) {
829    SetEmbeddedVTableEntry(i, table->GetElementPtrSize<ArtMethod*>(i, pointer_size), pointer_size);
830  }
831  // Keep java.lang.Object class's vtable around for since it's easier
832  // to be reused by array classes during their linking.
833  if (!IsObjectClass()) {
834    SetVTable(nullptr);
835  }
836}
837
838class ReadBarrierOnNativeRootsVisitor {
839 public:
840  void operator()(mirror::Object* obj ATTRIBUTE_UNUSED,
841                  MemberOffset offset ATTRIBUTE_UNUSED,
842                  bool is_static ATTRIBUTE_UNUSED) const {}
843
844  void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root) const
845      SHARED_REQUIRES(Locks::mutator_lock_) {
846    if (!root->IsNull()) {
847      VisitRoot(root);
848    }
849  }
850
851  void VisitRoot(mirror::CompressedReference<mirror::Object>* root) const
852      SHARED_REQUIRES(Locks::mutator_lock_) {
853    mirror::Object* old_ref = root->AsMirrorPtr();
854    mirror::Object* new_ref = ReadBarrier::BarrierForRoot(root);
855    if (old_ref != new_ref) {
856      // Update the field atomically. This may fail if mutator updates before us, but it's ok.
857      auto* atomic_root =
858          reinterpret_cast<Atomic<mirror::CompressedReference<mirror::Object>>*>(root);
859      atomic_root->CompareExchangeStrongSequentiallyConsistent(
860          mirror::CompressedReference<mirror::Object>::FromMirrorPtr(old_ref),
861          mirror::CompressedReference<mirror::Object>::FromMirrorPtr(new_ref));
862    }
863  }
864};
865
866// The pre-fence visitor for Class::CopyOf().
867class CopyClassVisitor {
868 public:
869  CopyClassVisitor(Thread* self, Handle<mirror::Class>* orig, size_t new_length,
870                   size_t copy_bytes, ArtMethod* const (&imt)[mirror::Class::kImtSize],
871                   size_t pointer_size)
872      : self_(self), orig_(orig), new_length_(new_length),
873        copy_bytes_(copy_bytes), imt_(imt), pointer_size_(pointer_size) {
874  }
875
876  void operator()(mirror::Object* obj, size_t usable_size ATTRIBUTE_UNUSED) const
877      SHARED_REQUIRES(Locks::mutator_lock_) {
878    StackHandleScope<1> hs(self_);
879    Handle<mirror::Class> h_new_class_obj(hs.NewHandle(obj->AsClass()));
880    mirror::Object::CopyObject(self_, h_new_class_obj.Get(), orig_->Get(), copy_bytes_);
881    mirror::Class::SetStatus(h_new_class_obj, Class::kStatusResolving, self_);
882    h_new_class_obj->PopulateEmbeddedImtAndVTable(imt_, pointer_size_);
883    h_new_class_obj->SetClassSize(new_length_);
884    // Visit all of the references to make sure there is no from space references in the native
885    // roots.
886    static_cast<mirror::Object*>(h_new_class_obj.Get())->VisitReferences(
887        ReadBarrierOnNativeRootsVisitor(), VoidFunctor());
888  }
889
890 private:
891  Thread* const self_;
892  Handle<mirror::Class>* const orig_;
893  const size_t new_length_;
894  const size_t copy_bytes_;
895  ArtMethod* const (&imt_)[mirror::Class::kImtSize];
896  const size_t pointer_size_;
897  DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor);
898};
899
900Class* Class::CopyOf(Thread* self, int32_t new_length,
901                     ArtMethod* const (&imt)[mirror::Class::kImtSize], size_t pointer_size) {
902  DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class)));
903  // We may get copied by a compacting GC.
904  StackHandleScope<1> hs(self);
905  Handle<mirror::Class> h_this(hs.NewHandle(this));
906  gc::Heap* heap = Runtime::Current()->GetHeap();
907  // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf()
908  // to skip copying the tail part that we will overwrite here.
909  CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class), imt, pointer_size);
910  mirror::Object* new_class = kMovingClasses ?
911      heap->AllocObject<true>(self, java_lang_Class_.Read(), new_length, visitor) :
912      heap->AllocNonMovableObject<true>(self, java_lang_Class_.Read(), new_length, visitor);
913  if (UNLIKELY(new_class == nullptr)) {
914    self->AssertPendingOOMException();
915    return nullptr;
916  }
917  return new_class->AsClass();
918}
919
920bool Class::ProxyDescriptorEquals(const char* match) {
921  DCHECK(IsProxyClass());
922  return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this) == match;
923}
924
925// TODO: Move this to java_lang_Class.cc?
926ArtMethod* Class::GetDeclaredConstructor(
927    Thread* self, Handle<mirror::ObjectArray<mirror::Class>> args) {
928  for (auto& m : GetDirectMethods(sizeof(void*))) {
929    // Skip <clinit> which is a static constructor, as well as non constructors.
930    if (m.IsStatic() || !m.IsConstructor()) {
931      continue;
932    }
933    // May cause thread suspension and exceptions.
934    if (m.GetInterfaceMethodIfProxy(sizeof(void*))->EqualParameters(args)) {
935      return &m;
936    }
937    if (UNLIKELY(self->IsExceptionPending())) {
938      return nullptr;
939    }
940  }
941  return nullptr;
942}
943
944uint32_t Class::Depth() {
945  uint32_t depth = 0;
946  for (Class* klass = this; klass->GetSuperClass() != nullptr; klass = klass->GetSuperClass()) {
947    depth++;
948  }
949  return depth;
950}
951
952}  // namespace mirror
953}  // namespace art
954