class-inl.h revision 059ef3ddb2088f926ac452889e0953fdcd646a5e
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#ifndef ART_RUNTIME_MIRROR_CLASS_INL_H_
18#define ART_RUNTIME_MIRROR_CLASS_INL_H_
19
20#include "class.h"
21
22#include "art_field-inl.h"
23#include "art_method.h"
24#include "art_method-inl.h"
25#include "class_loader.h"
26#include "common_throws.h"
27#include "dex_cache.h"
28#include "dex_file.h"
29#include "gc/heap-inl.h"
30#include "iftable.h"
31#include "length_prefixed_array.h"
32#include "object_array-inl.h"
33#include "read_barrier-inl.h"
34#include "reference-inl.h"
35#include "runtime.h"
36#include "string.h"
37#include "utils.h"
38
39namespace art {
40namespace mirror {
41
42template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
43inline uint32_t Class::GetObjectSize() {
44  // Note: Extra parentheses to avoid the comma being interpreted as macro parameter separator.
45  DCHECK((!IsVariableSize<kVerifyFlags, kReadBarrierOption>())) << " class=" << PrettyTypeOf(this);
46  return GetField32(ObjectSizeOffset());
47}
48
49inline Class* Class::GetSuperClass() {
50  // Can only get super class for loaded classes (hack for when runtime is
51  // initializing)
52  DCHECK(IsLoaded() || IsErroneous() || !Runtime::Current()->IsStarted()) << IsLoaded();
53  return GetFieldObject<Class>(OFFSET_OF_OBJECT_MEMBER(Class, super_class_));
54}
55
56inline ClassLoader* Class::GetClassLoader() {
57  return GetFieldObject<ClassLoader>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_));
58}
59
60template<VerifyObjectFlags kVerifyFlags>
61inline DexCache* Class::GetDexCache() {
62  return GetFieldObject<DexCache, kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_));
63}
64
65inline LengthPrefixedArray<ArtMethod>* Class::GetDirectMethodsPtr() {
66  DCHECK(IsLoaded() || IsErroneous());
67  return GetDirectMethodsPtrUnchecked();
68}
69
70inline LengthPrefixedArray<ArtMethod>* Class::GetDirectMethodsPtrUnchecked() {
71  return reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
72      GetField64(OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_)));
73}
74
75inline LengthPrefixedArray<ArtMethod>* Class::GetVirtualMethodsPtrUnchecked() {
76  return reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
77      GetField64(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_)));
78}
79
80inline void Class::SetDirectMethodsPtr(LengthPrefixedArray<ArtMethod>* new_direct_methods) {
81  DCHECK(GetDirectMethodsPtrUnchecked() == nullptr);
82  SetDirectMethodsPtrUnchecked(new_direct_methods);
83}
84
85inline void Class::SetDirectMethodsPtrUnchecked(
86    LengthPrefixedArray<ArtMethod>* new_direct_methods) {
87  SetField64<false>(OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_),
88                    reinterpret_cast<uint64_t>(new_direct_methods));
89}
90
91inline ArtMethod* Class::GetDirectMethodUnchecked(size_t i, size_t pointer_size) {
92  CheckPointerSize(pointer_size);
93  auto* methods = GetDirectMethodsPtrUnchecked();
94  DCHECK(methods != nullptr);
95  return &methods->At(i,
96                      ArtMethod::Size(pointer_size),
97                      ArtMethod::Alignment(pointer_size));
98}
99
100inline ArtMethod* Class::GetDirectMethod(size_t i, size_t pointer_size) {
101  CheckPointerSize(pointer_size);
102  auto* methods = GetDirectMethodsPtr();
103  DCHECK(methods != nullptr);
104  return &methods->At(i,
105                      ArtMethod::Size(pointer_size),
106                      ArtMethod::Alignment(pointer_size));
107}
108
109template<VerifyObjectFlags kVerifyFlags>
110inline LengthPrefixedArray<ArtMethod>* Class::GetVirtualMethodsPtr() {
111  DCHECK(IsLoaded<kVerifyFlags>() || IsErroneous<kVerifyFlags>());
112  return GetVirtualMethodsPtrUnchecked();
113}
114
115inline void Class::SetVirtualMethodsPtr(LengthPrefixedArray<ArtMethod>* new_virtual_methods) {
116  // TODO: we reassign virtual methods to grow the table for miranda
117  // methods.. they should really just be assigned once.
118  SetField64<false>(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_),
119                    reinterpret_cast<uint64_t>(new_virtual_methods));
120}
121
122template<VerifyObjectFlags kVerifyFlags>
123inline ArtMethod* Class::GetVirtualMethod(size_t i, size_t pointer_size) {
124  CheckPointerSize(pointer_size);
125  DCHECK(IsResolved<kVerifyFlags>() || IsErroneous<kVerifyFlags>())
126      << PrettyClass(this) << " status=" << GetStatus();
127  return GetVirtualMethodUnchecked(i, pointer_size);
128}
129
130inline ArtMethod* Class::GetVirtualMethodDuringLinking(size_t i, size_t pointer_size) {
131  CheckPointerSize(pointer_size);
132  DCHECK(IsLoaded() || IsErroneous());
133  return GetVirtualMethodUnchecked(i, pointer_size);
134}
135
136inline ArtMethod* Class::GetVirtualMethodUnchecked(size_t i, size_t pointer_size) {
137  CheckPointerSize(pointer_size);
138  LengthPrefixedArray<ArtMethod>* methods = GetVirtualMethodsPtrUnchecked();
139  DCHECK(methods != nullptr);
140  return &methods->At(i,
141                      ArtMethod::Size(pointer_size),
142                      ArtMethod::Alignment(pointer_size));
143}
144
145inline PointerArray* Class::GetVTable() {
146  DCHECK(IsResolved() || IsErroneous());
147  return GetFieldObject<PointerArray>(OFFSET_OF_OBJECT_MEMBER(Class, vtable_));
148}
149
150inline PointerArray* Class::GetVTableDuringLinking() {
151  DCHECK(IsLoaded() || IsErroneous());
152  return GetFieldObject<PointerArray>(OFFSET_OF_OBJECT_MEMBER(Class, vtable_));
153}
154
155inline void Class::SetVTable(PointerArray* new_vtable) {
156  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, vtable_), new_vtable);
157}
158
159inline MemberOffset Class::EmbeddedImTableEntryOffset(uint32_t i, size_t pointer_size) {
160  DCHECK_LT(i, kImtSize);
161  return MemberOffset(
162      EmbeddedImTableOffset(pointer_size).Uint32Value() + i * ImTableEntrySize(pointer_size));
163}
164
165inline ArtMethod* Class::GetEmbeddedImTableEntry(uint32_t i, size_t pointer_size) {
166  DCHECK(ShouldHaveEmbeddedImtAndVTable());
167  return GetFieldPtrWithSize<ArtMethod*>(
168      EmbeddedImTableEntryOffset(i, pointer_size), pointer_size);
169}
170
171inline void Class::SetEmbeddedImTableEntry(uint32_t i, ArtMethod* method, size_t pointer_size) {
172  DCHECK(ShouldHaveEmbeddedImtAndVTable());
173  SetFieldPtrWithSize<false>(EmbeddedImTableEntryOffset(i, pointer_size), method, pointer_size);
174}
175
176inline bool Class::HasVTable() {
177  return GetVTable() != nullptr || ShouldHaveEmbeddedImtAndVTable();
178}
179
180inline int32_t Class::GetVTableLength() {
181  if (ShouldHaveEmbeddedImtAndVTable()) {
182    return GetEmbeddedVTableLength();
183  }
184  return GetVTable() != nullptr ? GetVTable()->GetLength() : 0;
185}
186
187inline ArtMethod* Class::GetVTableEntry(uint32_t i, size_t pointer_size) {
188  if (ShouldHaveEmbeddedImtAndVTable()) {
189    return GetEmbeddedVTableEntry(i, pointer_size);
190  }
191  auto* vtable = GetVTable();
192  DCHECK(vtable != nullptr);
193  return vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size);
194}
195
196inline int32_t Class::GetEmbeddedVTableLength() {
197  return GetField32(MemberOffset(EmbeddedVTableLengthOffset()));
198}
199
200inline void Class::SetEmbeddedVTableLength(int32_t len) {
201  SetField32<false>(MemberOffset(EmbeddedVTableLengthOffset()), len);
202}
203
204inline MemberOffset Class::EmbeddedVTableEntryOffset(uint32_t i, size_t pointer_size) {
205  return MemberOffset(
206      EmbeddedVTableOffset(pointer_size).Uint32Value() + i * VTableEntrySize(pointer_size));
207}
208
209inline ArtMethod* Class::GetEmbeddedVTableEntry(uint32_t i, size_t pointer_size) {
210  return GetFieldPtrWithSize<ArtMethod*>(EmbeddedVTableEntryOffset(i, pointer_size), pointer_size);
211}
212
213inline void Class::SetEmbeddedVTableEntryUnchecked(
214    uint32_t i, ArtMethod* method, size_t pointer_size) {
215  SetFieldPtrWithSize<false>(EmbeddedVTableEntryOffset(i, pointer_size), method, pointer_size);
216}
217
218inline void Class::SetEmbeddedVTableEntry(uint32_t i, ArtMethod* method, size_t pointer_size) {
219  auto* vtable = GetVTableDuringLinking();
220  CHECK_EQ(method, vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size));
221  SetEmbeddedVTableEntryUnchecked(i, method, pointer_size);
222}
223
224inline bool Class::Implements(Class* klass) {
225  DCHECK(klass != nullptr);
226  DCHECK(klass->IsInterface()) << PrettyClass(this);
227  // All interfaces implemented directly and by our superclass, and
228  // recursively all super-interfaces of those interfaces, are listed
229  // in iftable_, so we can just do a linear scan through that.
230  int32_t iftable_count = GetIfTableCount();
231  IfTable* iftable = GetIfTable();
232  for (int32_t i = 0; i < iftable_count; i++) {
233    if (iftable->GetInterface(i) == klass) {
234      return true;
235    }
236  }
237  return false;
238}
239
240// Determine whether "this" is assignable from "src", where both of these
241// are array classes.
242//
243// Consider an array class, e.g. Y[][], where Y is a subclass of X.
244//   Y[][]            = Y[][] --> true (identity)
245//   X[][]            = Y[][] --> true (element superclass)
246//   Y                = Y[][] --> false
247//   Y[]              = Y[][] --> false
248//   Object           = Y[][] --> true (everything is an object)
249//   Object[]         = Y[][] --> true
250//   Object[][]       = Y[][] --> true
251//   Object[][][]     = Y[][] --> false (too many []s)
252//   Serializable     = Y[][] --> true (all arrays are Serializable)
253//   Serializable[]   = Y[][] --> true
254//   Serializable[][] = Y[][] --> false (unless Y is Serializable)
255//
256// Don't forget about primitive types.
257//   Object[]         = int[] --> false
258//
259inline bool Class::IsArrayAssignableFromArray(Class* src) {
260  DCHECK(IsArrayClass())  << PrettyClass(this);
261  DCHECK(src->IsArrayClass()) << PrettyClass(src);
262  return GetComponentType()->IsAssignableFrom(src->GetComponentType());
263}
264
265inline bool Class::IsAssignableFromArray(Class* src) {
266  DCHECK(!IsInterface()) << PrettyClass(this);  // handled first in IsAssignableFrom
267  DCHECK(src->IsArrayClass()) << PrettyClass(src);
268  if (!IsArrayClass()) {
269    // If "this" is not also an array, it must be Object.
270    // src's super should be java_lang_Object, since it is an array.
271    Class* java_lang_Object = src->GetSuperClass();
272    DCHECK(java_lang_Object != nullptr) << PrettyClass(src);
273    DCHECK(java_lang_Object->GetSuperClass() == nullptr) << PrettyClass(src);
274    return this == java_lang_Object;
275  }
276  return IsArrayAssignableFromArray(src);
277}
278
279template <bool throw_on_failure, bool use_referrers_cache>
280inline bool Class::ResolvedFieldAccessTest(Class* access_to, ArtField* field,
281                                           uint32_t field_idx, DexCache* dex_cache) {
282  DCHECK_EQ(use_referrers_cache, dex_cache == nullptr);
283  if (UNLIKELY(!this->CanAccess(access_to))) {
284    // The referrer class can't access the field's declaring class but may still be able
285    // to access the field if the FieldId specifies an accessible subclass of the declaring
286    // class rather than the declaring class itself.
287    DexCache* referrer_dex_cache = use_referrers_cache ? this->GetDexCache() : dex_cache;
288    uint32_t class_idx = referrer_dex_cache->GetDexFile()->GetFieldId(field_idx).class_idx_;
289    // The referenced class has already been resolved with the field, get it from the dex cache.
290    Class* dex_access_to = referrer_dex_cache->GetResolvedType(class_idx);
291    DCHECK(dex_access_to != nullptr);
292    if (UNLIKELY(!this->CanAccess(dex_access_to))) {
293      if (throw_on_failure) {
294        ThrowIllegalAccessErrorClass(this, dex_access_to);
295      }
296      return false;
297    }
298    DCHECK_EQ(this->CanAccessMember(access_to, field->GetAccessFlags()),
299              this->CanAccessMember(dex_access_to, field->GetAccessFlags()));
300  }
301  if (LIKELY(this->CanAccessMember(access_to, field->GetAccessFlags()))) {
302    return true;
303  }
304  if (throw_on_failure) {
305    ThrowIllegalAccessErrorField(this, field);
306  }
307  return false;
308}
309
310template <bool throw_on_failure, bool use_referrers_cache, InvokeType throw_invoke_type>
311inline bool Class::ResolvedMethodAccessTest(Class* access_to, ArtMethod* method,
312                                            uint32_t method_idx, DexCache* dex_cache) {
313  static_assert(throw_on_failure || throw_invoke_type == kStatic, "Non-default throw invoke type");
314  DCHECK_EQ(use_referrers_cache, dex_cache == nullptr);
315  if (UNLIKELY(!this->CanAccess(access_to))) {
316    // The referrer class can't access the method's declaring class but may still be able
317    // to access the method if the MethodId specifies an accessible subclass of the declaring
318    // class rather than the declaring class itself.
319    DexCache* referrer_dex_cache = use_referrers_cache ? this->GetDexCache() : dex_cache;
320    uint32_t class_idx = referrer_dex_cache->GetDexFile()->GetMethodId(method_idx).class_idx_;
321    // The referenced class has already been resolved with the method, get it from the dex cache.
322    Class* dex_access_to = referrer_dex_cache->GetResolvedType(class_idx);
323    DCHECK(dex_access_to != nullptr);
324    if (UNLIKELY(!this->CanAccess(dex_access_to))) {
325      if (throw_on_failure) {
326        ThrowIllegalAccessErrorClassForMethodDispatch(this, dex_access_to,
327                                                      method, throw_invoke_type);
328      }
329      return false;
330    }
331    DCHECK_EQ(this->CanAccessMember(access_to, method->GetAccessFlags()),
332              this->CanAccessMember(dex_access_to, method->GetAccessFlags()));
333  }
334  if (LIKELY(this->CanAccessMember(access_to, method->GetAccessFlags()))) {
335    return true;
336  }
337  if (throw_on_failure) {
338    ThrowIllegalAccessErrorMethod(this, method);
339  }
340  return false;
341}
342
343inline bool Class::CanAccessResolvedField(Class* access_to, ArtField* field,
344                                          DexCache* dex_cache, uint32_t field_idx) {
345  return ResolvedFieldAccessTest<false, false>(access_to, field, field_idx, dex_cache);
346}
347
348inline bool Class::CheckResolvedFieldAccess(Class* access_to, ArtField* field,
349                                            uint32_t field_idx) {
350  return ResolvedFieldAccessTest<true, true>(access_to, field, field_idx, nullptr);
351}
352
353inline bool Class::CanAccessResolvedMethod(Class* access_to, ArtMethod* method,
354                                           DexCache* dex_cache, uint32_t method_idx) {
355  return ResolvedMethodAccessTest<false, false, kStatic>(access_to, method, method_idx, dex_cache);
356}
357
358template <InvokeType throw_invoke_type>
359inline bool Class::CheckResolvedMethodAccess(Class* access_to, ArtMethod* method,
360                                             uint32_t method_idx) {
361  return ResolvedMethodAccessTest<true, true, throw_invoke_type>(access_to, method, method_idx,
362                                                                 nullptr);
363}
364
365inline bool Class::IsSubClass(Class* klass) {
366  DCHECK(!IsInterface()) << PrettyClass(this);
367  DCHECK(!IsArrayClass()) << PrettyClass(this);
368  Class* current = this;
369  do {
370    if (current == klass) {
371      return true;
372    }
373    current = current->GetSuperClass();
374  } while (current != nullptr);
375  return false;
376}
377
378inline ArtMethod* Class::FindVirtualMethodForInterface(ArtMethod* method, size_t pointer_size) {
379  Class* declaring_class = method->GetDeclaringClass();
380  DCHECK(declaring_class != nullptr) << PrettyClass(this);
381  DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
382  // TODO cache to improve lookup speed
383  const int32_t iftable_count = GetIfTableCount();
384  IfTable* iftable = GetIfTable();
385  for (int32_t i = 0; i < iftable_count; i++) {
386    if (iftable->GetInterface(i) == declaring_class) {
387      return iftable->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
388          method->GetMethodIndex(), pointer_size);
389    }
390  }
391  return nullptr;
392}
393
394inline ArtMethod* Class::FindVirtualMethodForVirtual(ArtMethod* method, size_t pointer_size) {
395  DCHECK(!method->GetDeclaringClass()->IsInterface() || method->IsMiranda());
396  // The argument method may from a super class.
397  // Use the index to a potentially overridden one for this instance's class.
398  return GetVTableEntry(method->GetMethodIndex(), pointer_size);
399}
400
401inline ArtMethod* Class::FindVirtualMethodForSuper(ArtMethod* method, size_t pointer_size) {
402  DCHECK(!method->GetDeclaringClass()->IsInterface());
403  return GetSuperClass()->GetVTableEntry(method->GetMethodIndex(), pointer_size);
404}
405
406inline ArtMethod* Class::FindVirtualMethodForVirtualOrInterface(ArtMethod* method,
407                                                                size_t pointer_size) {
408  if (method->IsDirect()) {
409    return method;
410  }
411  if (method->GetDeclaringClass()->IsInterface() && !method->IsMiranda()) {
412    return FindVirtualMethodForInterface(method, pointer_size);
413  }
414  return FindVirtualMethodForVirtual(method, pointer_size);
415}
416
417inline IfTable* Class::GetIfTable() {
418  return GetFieldObject<IfTable>(OFFSET_OF_OBJECT_MEMBER(Class, iftable_));
419}
420
421inline int32_t Class::GetIfTableCount() {
422  IfTable* iftable = GetIfTable();
423  if (iftable == nullptr) {
424    return 0;
425  }
426  return iftable->Count();
427}
428
429inline void Class::SetIfTable(IfTable* new_iftable) {
430  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, iftable_), new_iftable);
431}
432
433inline LengthPrefixedArray<ArtField>* Class::GetIFieldsPtr() {
434  DCHECK(IsLoaded() || IsErroneous());
435  return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
436}
437
438inline MemberOffset Class::GetFirstReferenceInstanceFieldOffset() {
439  Class* super_class = GetSuperClass();
440  return (super_class != nullptr)
441      ? MemberOffset(RoundUp(super_class->GetObjectSize(),
442                             sizeof(mirror::HeapReference<mirror::Object>)))
443      : ClassOffset();
444}
445
446inline MemberOffset Class::GetFirstReferenceStaticFieldOffset(size_t pointer_size) {
447  DCHECK(IsResolved());
448  uint32_t base = sizeof(mirror::Class);  // Static fields come after the class.
449  if (ShouldHaveEmbeddedImtAndVTable()) {
450    // Static fields come after the embedded tables.
451    base = mirror::Class::ComputeClassSize(
452        true, GetEmbeddedVTableLength(), 0, 0, 0, 0, 0, pointer_size);
453  }
454  return MemberOffset(base);
455}
456
457inline MemberOffset Class::GetFirstReferenceStaticFieldOffsetDuringLinking(size_t pointer_size) {
458  DCHECK(IsLoaded());
459  uint32_t base = sizeof(mirror::Class);  // Static fields come after the class.
460  if (ShouldHaveEmbeddedImtAndVTable()) {
461    // Static fields come after the embedded tables.
462    base = mirror::Class::ComputeClassSize(true, GetVTableDuringLinking()->GetLength(),
463                                           0, 0, 0, 0, 0, pointer_size);
464  }
465  return MemberOffset(base);
466}
467
468inline void Class::SetIFieldsPtr(LengthPrefixedArray<ArtField>* new_ifields) {
469  DCHECK(GetIFieldsPtrUnchecked() == nullptr);
470  return SetFieldPtr<false>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
471}
472
473inline void Class::SetIFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_ifields) {
474  SetFieldPtr<false, true, kVerifyNone>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
475}
476
477inline LengthPrefixedArray<ArtField>* Class::GetSFieldsPtrUnchecked() {
478  return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
479}
480
481inline LengthPrefixedArray<ArtField>* Class::GetIFieldsPtrUnchecked() {
482  return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
483}
484
485inline LengthPrefixedArray<ArtField>* Class::GetSFieldsPtr() {
486  DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
487  return GetSFieldsPtrUnchecked();
488}
489
490inline void Class::SetSFieldsPtr(LengthPrefixedArray<ArtField>* new_sfields) {
491  DCHECK((IsRetired() && new_sfields == nullptr) ||
492         GetFieldPtr<ArtField*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_)) == nullptr);
493  SetFieldPtr<false>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
494}
495
496inline void Class::SetSFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_sfields) {
497  SetFieldPtr<false, true, kVerifyNone>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
498}
499
500inline ArtField* Class::GetStaticField(uint32_t i) {
501  return &GetSFieldsPtr()->At(i);
502}
503
504inline ArtField* Class::GetInstanceField(uint32_t i) {
505  return &GetIFieldsPtr()->At(i);
506}
507
508template<VerifyObjectFlags kVerifyFlags>
509inline uint32_t Class::GetReferenceInstanceOffsets() {
510  DCHECK(IsResolved<kVerifyFlags>() || IsErroneous<kVerifyFlags>());
511  return GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_));
512}
513
514inline void Class::SetClinitThreadId(pid_t new_clinit_thread_id) {
515  if (Runtime::Current()->IsActiveTransaction()) {
516    SetField32<true>(OFFSET_OF_OBJECT_MEMBER(Class, clinit_thread_id_), new_clinit_thread_id);
517  } else {
518    SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, clinit_thread_id_), new_clinit_thread_id);
519  }
520}
521
522inline void Class::SetVerifyErrorClass(Class* klass) {
523  CHECK(klass != nullptr) << PrettyClass(this);
524  if (Runtime::Current()->IsActiveTransaction()) {
525    SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, verify_error_class_), klass);
526  } else {
527    SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, verify_error_class_), klass);
528  }
529}
530
531template<VerifyObjectFlags kVerifyFlags>
532inline uint32_t Class::GetAccessFlags() {
533  // Check class is loaded/retired or this is java.lang.String that has a
534  // circularity issue during loading the names of its members
535  DCHECK(IsIdxLoaded<kVerifyFlags>() || IsRetired<kVerifyFlags>() ||
536         IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>() ||
537         this == String::GetJavaLangString())
538      << "IsIdxLoaded=" << IsIdxLoaded<kVerifyFlags>()
539      << " IsRetired=" << IsRetired<kVerifyFlags>()
540      << " IsErroneous=" <<
541          IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>()
542      << " IsString=" << (this == String::GetJavaLangString())
543      << " descriptor=" << PrettyDescriptor(this);
544  return GetField32<kVerifyFlags>(AccessFlagsOffset());
545}
546
547inline String* Class::GetName() {
548  return GetFieldObject<String>(OFFSET_OF_OBJECT_MEMBER(Class, name_));
549}
550inline void Class::SetName(String* name) {
551  if (Runtime::Current()->IsActiveTransaction()) {
552    SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, name_), name);
553  } else {
554    SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, name_), name);
555  }
556}
557
558template<VerifyObjectFlags kVerifyFlags>
559inline Primitive::Type Class::GetPrimitiveType() {
560  static_assert(sizeof(Primitive::Type) == sizeof(int32_t),
561                "art::Primitive::Type and int32_t have different sizes.");
562  int32_t v32 = GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, primitive_type_));
563  Primitive::Type type = static_cast<Primitive::Type>(v32 & 0xFFFF);
564  DCHECK_EQ(static_cast<size_t>(v32 >> 16), Primitive::ComponentSizeShift(type));
565  return type;
566}
567
568template<VerifyObjectFlags kVerifyFlags>
569inline size_t Class::GetPrimitiveTypeSizeShift() {
570  static_assert(sizeof(Primitive::Type) == sizeof(int32_t),
571                "art::Primitive::Type and int32_t have different sizes.");
572  int32_t v32 = GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, primitive_type_));
573  size_t size_shift = static_cast<Primitive::Type>(v32 >> 16);
574  DCHECK_EQ(size_shift, Primitive::ComponentSizeShift(static_cast<Primitive::Type>(v32 & 0xFFFF)));
575  return size_shift;
576}
577
578inline void Class::CheckObjectAlloc() {
579  DCHECK(!IsArrayClass())
580      << PrettyClass(this)
581      << "A array shouldn't be allocated through this "
582      << "as it requires a pre-fence visitor that sets the class size.";
583  DCHECK(!IsClassClass())
584      << PrettyClass(this)
585      << "A class object shouldn't be allocated through this "
586      << "as it requires a pre-fence visitor that sets the class size.";
587  DCHECK(!IsStringClass())
588      << PrettyClass(this)
589      << "A string shouldn't be allocated through this "
590      << "as it requires a pre-fence visitor that sets the class size.";
591  DCHECK(IsInstantiable()) << PrettyClass(this);
592  // TODO: decide whether we want this check. It currently fails during bootstrap.
593  // DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
594  DCHECK_GE(this->object_size_, sizeof(Object));
595}
596
597template<bool kIsInstrumented, bool kCheckAddFinalizer>
598inline Object* Class::Alloc(Thread* self, gc::AllocatorType allocator_type) {
599  CheckObjectAlloc();
600  gc::Heap* heap = Runtime::Current()->GetHeap();
601  const bool add_finalizer = kCheckAddFinalizer && IsFinalizable();
602  if (!kCheckAddFinalizer) {
603    DCHECK(!IsFinalizable());
604  }
605  mirror::Object* obj =
606      heap->AllocObjectWithAllocator<kIsInstrumented, false>(self, this, this->object_size_,
607                                                             allocator_type, VoidFunctor());
608  if (add_finalizer && LIKELY(obj != nullptr)) {
609    heap->AddFinalizerReference(self, &obj);
610    if (UNLIKELY(self->IsExceptionPending())) {
611      // Failed to allocate finalizer reference, it means that the whole allocation failed.
612      obj = nullptr;
613    }
614  }
615  return obj;
616}
617
618inline Object* Class::AllocObject(Thread* self) {
619  return Alloc<true>(self, Runtime::Current()->GetHeap()->GetCurrentAllocator());
620}
621
622inline Object* Class::AllocNonMovableObject(Thread* self) {
623  return Alloc<true>(self, Runtime::Current()->GetHeap()->GetCurrentNonMovingAllocator());
624}
625
626inline uint32_t Class::ComputeClassSize(bool has_embedded_tables,
627                                        uint32_t num_vtable_entries,
628                                        uint32_t num_8bit_static_fields,
629                                        uint32_t num_16bit_static_fields,
630                                        uint32_t num_32bit_static_fields,
631                                        uint32_t num_64bit_static_fields,
632                                        uint32_t num_ref_static_fields,
633                                        size_t pointer_size) {
634  // Space used by java.lang.Class and its instance fields.
635  uint32_t size = sizeof(Class);
636  // Space used by embedded tables.
637  if (has_embedded_tables) {
638    const uint32_t embedded_imt_size = kImtSize * ImTableEntrySize(pointer_size);
639    const uint32_t embedded_vtable_size = num_vtable_entries * VTableEntrySize(pointer_size);
640    size = RoundUp(size + sizeof(uint32_t) /* embedded vtable len */, pointer_size) +
641        embedded_imt_size + embedded_vtable_size;
642  }
643
644  // Space used by reference statics.
645  size += num_ref_static_fields * sizeof(HeapReference<Object>);
646  if (!IsAligned<8>(size) && num_64bit_static_fields > 0) {
647    uint32_t gap = 8 - (size & 0x7);
648    size += gap;  // will be padded
649    // Shuffle 4-byte fields forward.
650    while (gap >= sizeof(uint32_t) && num_32bit_static_fields != 0) {
651      --num_32bit_static_fields;
652      gap -= sizeof(uint32_t);
653    }
654    // Shuffle 2-byte fields forward.
655    while (gap >= sizeof(uint16_t) && num_16bit_static_fields != 0) {
656      --num_16bit_static_fields;
657      gap -= sizeof(uint16_t);
658    }
659    // Shuffle byte fields forward.
660    while (gap >= sizeof(uint8_t) && num_8bit_static_fields != 0) {
661      --num_8bit_static_fields;
662      gap -= sizeof(uint8_t);
663    }
664  }
665  // Guaranteed to be at least 4 byte aligned. No need for further alignments.
666  // Space used for primitive static fields.
667  size += num_8bit_static_fields * sizeof(uint8_t) + num_16bit_static_fields * sizeof(uint16_t) +
668      num_32bit_static_fields * sizeof(uint32_t) + num_64bit_static_fields * sizeof(uint64_t);
669  return size;
670}
671
672template <typename Visitor>
673inline void Class::VisitReferences(mirror::Class* klass, const Visitor& visitor) {
674  VisitInstanceFieldsReferences(klass, visitor);
675  // Right after a class is allocated, but not yet loaded
676  // (kStatusNotReady, see ClassLinker::LoadClass()), GC may find it
677  // and scan it. IsTemp() may call Class::GetAccessFlags() but may
678  // fail in the DCHECK in Class::GetAccessFlags() because the class
679  // status is kStatusNotReady. To avoid it, rely on IsResolved()
680  // only. This is fine because a temp class never goes into the
681  // kStatusResolved state.
682  if (IsResolved()) {
683    // Temp classes don't ever populate imt/vtable or static fields and they are not even
684    // allocated with the right size for those. Also, unresolved classes don't have fields
685    // linked yet.
686    VisitStaticFieldsReferences(this, visitor);
687  }
688  // Since this class is reachable, we must also visit the associated roots when we scan it.
689  VisitNativeRoots(visitor, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
690}
691
692template<ReadBarrierOption kReadBarrierOption>
693inline bool Class::IsReferenceClass() const {
694  return this == Reference::GetJavaLangRefReference<kReadBarrierOption>();
695}
696
697template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
698inline bool Class::IsClassClass() {
699  Class* java_lang_Class = GetClass<kVerifyFlags, kReadBarrierOption>()->
700      template GetClass<kVerifyFlags, kReadBarrierOption>();
701  return this == java_lang_Class;
702}
703
704inline const DexFile& Class::GetDexFile() {
705  return *GetDexCache()->GetDexFile();
706}
707
708inline bool Class::DescriptorEquals(const char* match) {
709  if (IsArrayClass()) {
710    return match[0] == '[' && GetComponentType()->DescriptorEquals(match + 1);
711  } else if (IsPrimitive()) {
712    return strcmp(Primitive::Descriptor(GetPrimitiveType()), match) == 0;
713  } else if (IsProxyClass()) {
714    return ProxyDescriptorEquals(match);
715  } else {
716    const DexFile& dex_file = GetDexFile();
717    const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
718    return strcmp(dex_file.GetTypeDescriptor(type_id), match) == 0;
719  }
720}
721
722inline void Class::AssertInitializedOrInitializingInThread(Thread* self) {
723  if (kIsDebugBuild && !IsInitialized()) {
724    CHECK(IsInitializing()) << PrettyClass(this) << " is not initializing: " << GetStatus();
725    CHECK_EQ(GetClinitThreadId(), self->GetTid()) << PrettyClass(this)
726                                                  << " is initializing in a different thread";
727  }
728}
729
730inline ObjectArray<Class>* Class::GetInterfaces() {
731  CHECK(IsProxyClass());
732  // First static field.
733  auto* field = GetStaticField(0);
734  DCHECK_STREQ(field->GetName(), "interfaces");
735  MemberOffset field_offset = field->GetOffset();
736  return GetFieldObject<ObjectArray<Class>>(field_offset);
737}
738
739inline ObjectArray<ObjectArray<Class>>* Class::GetThrows() {
740  CHECK(IsProxyClass());
741  // Second static field.
742  auto* field = GetStaticField(1);
743  DCHECK_STREQ(field->GetName(), "throws");
744  MemberOffset field_offset = field->GetOffset();
745  return GetFieldObject<ObjectArray<ObjectArray<Class>>>(field_offset);
746}
747
748inline MemberOffset Class::GetDisableIntrinsicFlagOffset() {
749  CHECK(IsReferenceClass());
750  // First static field
751  auto* field = GetStaticField(0);
752  DCHECK_STREQ(field->GetName(), "disableIntrinsic");
753  return field->GetOffset();
754}
755
756inline MemberOffset Class::GetSlowPathFlagOffset() {
757  CHECK(IsReferenceClass());
758  // Second static field
759  auto* field = GetStaticField(1);
760  DCHECK_STREQ(field->GetName(), "slowPathEnabled");
761  return field->GetOffset();
762}
763
764inline bool Class::GetSlowPathEnabled() {
765  return GetFieldBoolean(GetSlowPathFlagOffset());
766}
767
768inline void Class::SetSlowPath(bool enabled) {
769  SetFieldBoolean<false, false>(GetSlowPathFlagOffset(), enabled);
770}
771
772inline void Class::InitializeClassVisitor::operator()(
773    mirror::Object* obj, size_t usable_size) const {
774  DCHECK_LE(class_size_, usable_size);
775  // Avoid AsClass as object is not yet in live bitmap or allocation stack.
776  mirror::Class* klass = down_cast<mirror::Class*>(obj);
777  // DCHECK(klass->IsClass());
778  klass->SetClassSize(class_size_);
779  klass->SetPrimitiveType(Primitive::kPrimNot);  // Default to not being primitive.
780  klass->SetDexClassDefIndex(DexFile::kDexNoIndex16);  // Default to no valid class def index.
781  klass->SetDexTypeIndex(DexFile::kDexNoIndex16);  // Default to no valid type index.
782}
783
784inline void Class::SetAccessFlags(uint32_t new_access_flags) {
785  // Called inside a transaction when setting pre-verified flag during boot image compilation.
786  if (Runtime::Current()->IsActiveTransaction()) {
787    SetField32<true>(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_), new_access_flags);
788  } else {
789    SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_), new_access_flags);
790  }
791}
792
793inline uint32_t Class::NumDirectInterfaces() {
794  if (IsPrimitive()) {
795    return 0;
796  } else if (IsArrayClass()) {
797    return 2;
798  } else if (IsProxyClass()) {
799    mirror::ObjectArray<mirror::Class>* interfaces = GetInterfaces();
800    return interfaces != nullptr ? interfaces->GetLength() : 0;
801  } else {
802    const DexFile::TypeList* interfaces = GetInterfaceTypeList();
803    if (interfaces == nullptr) {
804      return 0;
805    } else {
806      return interfaces->Size();
807    }
808  }
809}
810
811inline void Class::SetDexCacheStrings(ObjectArray<String>* new_dex_cache_strings) {
812  SetFieldObject<false>(DexCacheStringsOffset(), new_dex_cache_strings);
813}
814
815inline ObjectArray<String>* Class::GetDexCacheStrings() {
816  return GetFieldObject<ObjectArray<String>>(DexCacheStringsOffset());
817}
818
819template<class Visitor>
820void mirror::Class::VisitNativeRoots(Visitor& visitor, size_t pointer_size) {
821  for (ArtField& field : GetSFieldsUnchecked()) {
822    // Visit roots first in case the declaring class gets moved.
823    field.VisitRoots(visitor);
824    if (kIsDebugBuild && IsResolved()) {
825      CHECK_EQ(field.GetDeclaringClass(), this) << GetStatus();
826    }
827  }
828  for (ArtField& field : GetIFieldsUnchecked()) {
829    // Visit roots first in case the declaring class gets moved.
830    field.VisitRoots(visitor);
831    if (kIsDebugBuild && IsResolved()) {
832      CHECK_EQ(field.GetDeclaringClass(), this) << GetStatus();
833    }
834  }
835  for (ArtMethod& method : GetDirectMethods(pointer_size)) {
836    method.VisitRoots(visitor);
837  }
838  for (ArtMethod& method : GetVirtualMethods(pointer_size)) {
839    method.VisitRoots(visitor);
840  }
841}
842
843inline IterationRange<StrideIterator<ArtMethod>> Class::GetDirectMethods(size_t pointer_size) {
844  CheckPointerSize(pointer_size);
845  return MakeIterationRangeFromLengthPrefixedArray(GetDirectMethodsPtrUnchecked(),
846                                                   ArtMethod::Size(pointer_size),
847                                                   ArtMethod::Alignment(pointer_size));
848}
849
850inline IterationRange<StrideIterator<ArtMethod>> Class::GetVirtualMethods(size_t pointer_size) {
851  CheckPointerSize(pointer_size);
852  return MakeIterationRangeFromLengthPrefixedArray(GetVirtualMethodsPtrUnchecked(),
853                                                   ArtMethod::Size(pointer_size),
854                                                   ArtMethod::Alignment(pointer_size));
855}
856
857inline IterationRange<StrideIterator<ArtField>> Class::GetIFields() {
858  return MakeIterationRangeFromLengthPrefixedArray(GetIFieldsPtr());
859}
860
861inline IterationRange<StrideIterator<ArtField>> Class::GetSFields() {
862  return MakeIterationRangeFromLengthPrefixedArray(GetSFieldsPtr());
863}
864
865inline IterationRange<StrideIterator<ArtField>> Class::GetIFieldsUnchecked() {
866  return MakeIterationRangeFromLengthPrefixedArray(GetIFieldsPtrUnchecked());
867}
868
869inline IterationRange<StrideIterator<ArtField>> Class::GetSFieldsUnchecked() {
870  return MakeIterationRangeFromLengthPrefixedArray(GetSFieldsPtrUnchecked());
871}
872
873inline MemberOffset Class::EmbeddedImTableOffset(size_t pointer_size) {
874  CheckPointerSize(pointer_size);
875  // Round up since we want the embedded imt and vtable to be pointer size aligned in case 64 bits.
876  // Add 32 bits for embedded vtable length.
877  return MemberOffset(
878      RoundUp(EmbeddedVTableLengthOffset().Uint32Value() + sizeof(uint32_t), pointer_size));
879}
880
881inline MemberOffset Class::EmbeddedVTableOffset(size_t pointer_size) {
882  CheckPointerSize(pointer_size);
883  return MemberOffset(EmbeddedImTableOffset(pointer_size).Uint32Value() +
884                      kImtSize * ImTableEntrySize(pointer_size));
885}
886
887inline void Class::CheckPointerSize(size_t pointer_size) {
888  DCHECK(ValidPointerSize(pointer_size)) << pointer_size;
889  DCHECK_EQ(pointer_size, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
890}
891
892template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
893inline Class* Class::GetComponentType() {
894  return GetFieldObject<Class, kVerifyFlags, kReadBarrierOption>(ComponentTypeOffset());
895}
896
897template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
898inline bool Class::IsArrayClass() {
899  return GetComponentType<kVerifyFlags, kReadBarrierOption>() != nullptr;
900}
901
902inline bool Class::IsAssignableFrom(Class* src) {
903  DCHECK(src != nullptr);
904  if (this == src) {
905    // Can always assign to things of the same type.
906    return true;
907  } else if (IsObjectClass()) {
908    // Can assign any reference to java.lang.Object.
909    return !src->IsPrimitive();
910  } else if (IsInterface()) {
911    return src->Implements(this);
912  } else if (src->IsArrayClass()) {
913    return IsAssignableFromArray(src);
914  } else {
915    return !src->IsInterface() && src->IsSubClass(this);
916  }
917}
918
919inline uint32_t Class::NumDirectMethods() {
920  LengthPrefixedArray<ArtMethod>* arr = GetDirectMethodsPtrUnchecked();
921  return arr != nullptr ? arr->Length() : 0u;
922}
923
924inline uint32_t Class::NumVirtualMethods() {
925  LengthPrefixedArray<ArtMethod>* arr = GetVirtualMethodsPtrUnchecked();
926  return arr != nullptr ? arr->Length() : 0u;
927}
928
929inline uint32_t Class::NumInstanceFields() {
930  LengthPrefixedArray<ArtField>* arr = GetIFieldsPtrUnchecked();
931  return arr != nullptr ? arr->Length() : 0u;
932}
933
934inline uint32_t Class::NumStaticFields() {
935  LengthPrefixedArray<ArtField>* arr = GetSFieldsPtrUnchecked();
936  return arr != nullptr ? arr->Length() : 0u;
937}
938
939}  // namespace mirror
940}  // namespace art
941
942#endif  // ART_RUNTIME_MIRROR_CLASS_INL_H_
943