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