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