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