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.h"
23 #include "art_method.h"
24 #include "base/array_slice.h"
25 #include "base/iteration_range.h"
26 #include "base/length_prefixed_array.h"
27 #include "base/stride_iterator.h"
28 #include "base/utils.h"
29 #include "class_linker.h"
30 #include "class_loader.h"
31 #include "common_throws.h"
32 #include "dex/dex_file-inl.h"
33 #include "dex/invoke_type.h"
34 #include "dex_cache.h"
35 #include "iftable-inl.h"
36 #include "imtable.h"
37 #include "object-inl.h"
38 #include "object_array.h"
39 #include "read_barrier-inl.h"
40 #include "runtime.h"
41 #include "string.h"
42 #include "subtype_check.h"
43 #include "thread-current-inl.h"
44 
45 namespace art {
46 namespace mirror {
47 
48 template<VerifyObjectFlags kVerifyFlags>
GetObjectSize()49 inline uint32_t Class::GetObjectSize() {
50   // Note: Extra parentheses to avoid the comma being interpreted as macro parameter separator.
51   DCHECK((!IsVariableSize<kVerifyFlags>())) << "class=" << PrettyTypeOf();
52   return GetField32(ObjectSizeOffset());
53 }
54 
55 template<VerifyObjectFlags kVerifyFlags>
GetObjectSizeAllocFastPath()56 inline uint32_t Class::GetObjectSizeAllocFastPath() {
57   // Note: Extra parentheses to avoid the comma being interpreted as macro parameter separator.
58   DCHECK((!IsVariableSize<kVerifyFlags>())) << "class=" << PrettyTypeOf();
59   return GetField32(ObjectSizeAllocFastPathOffset());
60 }
61 
62 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetSuperClass()63 inline ObjPtr<Class> Class::GetSuperClass() {
64   // Can only get super class for loaded classes (hack for when runtime is
65   // initializing)
66   DCHECK(IsLoaded<kVerifyFlags>() ||
67          IsErroneous<kVerifyFlags>() ||
68          !Runtime::Current()->IsStarted()) << IsLoaded();
69   return GetFieldObject<Class, kVerifyFlags, kReadBarrierOption>(
70       OFFSET_OF_OBJECT_MEMBER(Class, super_class_));
71 }
72 
SetSuperClass(ObjPtr<Class> new_super_class)73 inline void Class::SetSuperClass(ObjPtr<Class> new_super_class) {
74   // Super class is assigned once, except during class linker initialization.
75   if (kIsDebugBuild) {
76     ObjPtr<Class> old_super_class =
77         GetFieldObject<Class>(OFFSET_OF_OBJECT_MEMBER(Class, super_class_));
78     DCHECK(old_super_class == nullptr || old_super_class == new_super_class);
79   }
80   DCHECK(new_super_class != nullptr);
81   SetFieldObject</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
82       OFFSET_OF_OBJECT_MEMBER(Class, super_class_), new_super_class);
83 }
84 
HasSuperClass()85 inline bool Class::HasSuperClass() {
86   // No read barrier is needed for comparing with null. See ReadBarrierOption.
87   return GetSuperClass<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr;
88 }
89 
90 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetClassLoader()91 inline ObjPtr<ClassLoader> Class::GetClassLoader() {
92   return GetFieldObject<ClassLoader, kVerifyFlags, kReadBarrierOption>(
93       OFFSET_OF_OBJECT_MEMBER(Class, class_loader_));
94 }
95 
96 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetExtData()97 inline ObjPtr<ClassExt> Class::GetExtData() {
98   return GetFieldObject<ClassExt, kVerifyFlags, kReadBarrierOption>(
99       OFFSET_OF_OBJECT_MEMBER(Class, ext_data_));
100 }
101 
102 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetDexCache()103 inline ObjPtr<DexCache> Class::GetDexCache() {
104   return GetFieldObject<DexCache, kVerifyFlags, kReadBarrierOption>(
105       OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_));
106 }
107 
GetCopiedMethodsStartOffset()108 inline uint32_t Class::GetCopiedMethodsStartOffset() {
109   // Object::GetFieldShort returns an int16_t value, but
110   // Class::copied_methods_offset_ is an uint16_t value; cast the
111   // latter to uint16_t before returning it as an uint32_t value, so
112   // that uint16_t values between 2^15 and 2^16-1 are correctly
113   // handled.
114   return static_cast<uint16_t>(
115       GetFieldShort(OFFSET_OF_OBJECT_MEMBER(Class, copied_methods_offset_)));
116 }
117 
GetDirectMethodsStartOffset()118 inline uint32_t Class::GetDirectMethodsStartOffset() {
119   return 0;
120 }
121 
GetVirtualMethodsStartOffset()122 inline uint32_t Class::GetVirtualMethodsStartOffset() {
123   // Object::GetFieldShort returns an int16_t value, but
124   // Class::virtual_method_offset_ is an uint16_t value; cast the
125   // latter to uint16_t before returning it as an uint32_t value, so
126   // that uint16_t values between 2^15 and 2^16-1 are correctly
127   // handled.
128   return static_cast<uint16_t>(
129       GetFieldShort(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_offset_)));
130 }
131 
132 template<VerifyObjectFlags kVerifyFlags>
GetDirectMethodsSlice(PointerSize pointer_size)133 inline ArraySlice<ArtMethod> Class::GetDirectMethodsSlice(PointerSize pointer_size) {
134   DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
135   return GetDirectMethodsSliceUnchecked(pointer_size);
136 }
137 
GetDirectMethodsSliceUnchecked(PointerSize pointer_size)138 inline ArraySlice<ArtMethod> Class::GetDirectMethodsSliceUnchecked(PointerSize pointer_size) {
139   return GetMethodsSliceRangeUnchecked(GetMethodsPtr(),
140                                        pointer_size,
141                                        GetDirectMethodsStartOffset(),
142                                        GetVirtualMethodsStartOffset());
143 }
144 
145 template<VerifyObjectFlags kVerifyFlags>
GetDeclaredMethodsSlice(PointerSize pointer_size)146 inline ArraySlice<ArtMethod> Class::GetDeclaredMethodsSlice(PointerSize pointer_size) {
147   DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
148   return GetDeclaredMethodsSliceUnchecked(pointer_size);
149 }
150 
GetDeclaredMethodsSliceUnchecked(PointerSize pointer_size)151 inline ArraySlice<ArtMethod> Class::GetDeclaredMethodsSliceUnchecked(PointerSize pointer_size) {
152   return GetMethodsSliceRangeUnchecked(GetMethodsPtr(),
153                                        pointer_size,
154                                        GetDirectMethodsStartOffset(),
155                                        GetCopiedMethodsStartOffset());
156 }
157 
158 template<VerifyObjectFlags kVerifyFlags>
GetDeclaredVirtualMethodsSlice(PointerSize pointer_size)159 inline ArraySlice<ArtMethod> Class::GetDeclaredVirtualMethodsSlice(PointerSize pointer_size) {
160   DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
161   return GetDeclaredVirtualMethodsSliceUnchecked(pointer_size);
162 }
163 
GetDeclaredVirtualMethodsSliceUnchecked(PointerSize pointer_size)164 inline ArraySlice<ArtMethod> Class::GetDeclaredVirtualMethodsSliceUnchecked(
165     PointerSize pointer_size) {
166   return GetMethodsSliceRangeUnchecked(GetMethodsPtr(),
167                                        pointer_size,
168                                        GetVirtualMethodsStartOffset(),
169                                        GetCopiedMethodsStartOffset());
170 }
171 
172 template<VerifyObjectFlags kVerifyFlags>
GetVirtualMethodsSlice(PointerSize pointer_size)173 inline ArraySlice<ArtMethod> Class::GetVirtualMethodsSlice(PointerSize pointer_size) {
174   DCHECK(IsLoaded() || IsErroneous());
175   return GetVirtualMethodsSliceUnchecked(pointer_size);
176 }
177 
GetVirtualMethodsSliceUnchecked(PointerSize pointer_size)178 inline ArraySlice<ArtMethod> Class::GetVirtualMethodsSliceUnchecked(PointerSize pointer_size) {
179   LengthPrefixedArray<ArtMethod>* methods = GetMethodsPtr();
180   return GetMethodsSliceRangeUnchecked(methods,
181                                        pointer_size,
182                                        GetVirtualMethodsStartOffset(),
183                                        NumMethods(methods));
184 }
185 
186 template<VerifyObjectFlags kVerifyFlags>
GetCopiedMethodsSlice(PointerSize pointer_size)187 inline ArraySlice<ArtMethod> Class::GetCopiedMethodsSlice(PointerSize pointer_size) {
188   DCHECK(IsLoaded() || IsErroneous());
189   return GetCopiedMethodsSliceUnchecked(pointer_size);
190 }
191 
GetCopiedMethodsSliceUnchecked(PointerSize pointer_size)192 inline ArraySlice<ArtMethod> Class::GetCopiedMethodsSliceUnchecked(PointerSize pointer_size) {
193   LengthPrefixedArray<ArtMethod>* methods = GetMethodsPtr();
194   return GetMethodsSliceRangeUnchecked(methods,
195                                        pointer_size,
196                                        GetCopiedMethodsStartOffset(),
197                                        NumMethods(methods));
198 }
199 
GetMethodsPtr()200 inline LengthPrefixedArray<ArtMethod>* Class::GetMethodsPtr() {
201   return reinterpret_cast<LengthPrefixedArray<ArtMethod>*>(
202       static_cast<uintptr_t>(GetField64(OFFSET_OF_OBJECT_MEMBER(Class, methods_))));
203 }
204 
205 template<VerifyObjectFlags kVerifyFlags>
GetMethodsSlice(PointerSize pointer_size)206 inline ArraySlice<ArtMethod> Class::GetMethodsSlice(PointerSize pointer_size) {
207   DCHECK(IsLoaded() || IsErroneous());
208   LengthPrefixedArray<ArtMethod>* methods = GetMethodsPtr();
209   return GetMethodsSliceRangeUnchecked(methods, pointer_size, 0, NumMethods(methods));
210 }
211 
GetMethodsSliceRangeUnchecked(LengthPrefixedArray<ArtMethod> * methods,PointerSize pointer_size,uint32_t start_offset,uint32_t end_offset)212 inline ArraySlice<ArtMethod> Class::GetMethodsSliceRangeUnchecked(
213     LengthPrefixedArray<ArtMethod>* methods,
214     PointerSize pointer_size,
215     uint32_t start_offset,
216     uint32_t end_offset) {
217   DCHECK_LE(start_offset, end_offset);
218   DCHECK_LE(end_offset, NumMethods(methods));
219   uint32_t size = end_offset - start_offset;
220   if (size == 0u) {
221     return ArraySlice<ArtMethod>();
222   }
223   DCHECK(methods != nullptr);
224   DCHECK_LE(end_offset, methods->size());
225   size_t method_size = ArtMethod::Size(pointer_size);
226   size_t method_alignment = ArtMethod::Alignment(pointer_size);
227   ArraySlice<ArtMethod> slice(&methods->At(0u, method_size, method_alignment),
228                               methods->size(),
229                               method_size);
230   return slice.SubArray(start_offset, size);
231 }
232 
NumMethods()233 inline uint32_t Class::NumMethods() {
234   return NumMethods(GetMethodsPtr());
235 }
236 
NumMethods(LengthPrefixedArray<ArtMethod> * methods)237 inline uint32_t Class::NumMethods(LengthPrefixedArray<ArtMethod>* methods) {
238   return (methods == nullptr) ? 0 : methods->size();
239 }
240 
GetDirectMethodUnchecked(size_t i,PointerSize pointer_size)241 inline ArtMethod* Class::GetDirectMethodUnchecked(size_t i, PointerSize pointer_size) {
242   CheckPointerSize(pointer_size);
243   return &GetDirectMethodsSliceUnchecked(pointer_size)[i];
244 }
245 
GetDirectMethod(size_t i,PointerSize pointer_size)246 inline ArtMethod* Class::GetDirectMethod(size_t i, PointerSize pointer_size) {
247   CheckPointerSize(pointer_size);
248   return &GetDirectMethodsSlice(pointer_size)[i];
249 }
250 
SetMethodsPtr(LengthPrefixedArray<ArtMethod> * new_methods,uint32_t num_direct,uint32_t num_virtual)251 inline void Class::SetMethodsPtr(LengthPrefixedArray<ArtMethod>* new_methods,
252                                  uint32_t num_direct,
253                                  uint32_t num_virtual) {
254   DCHECK(GetMethodsPtr() == nullptr);
255   SetMethodsPtrUnchecked(new_methods, num_direct, num_virtual);
256 }
257 
258 
SetMethodsPtrUnchecked(LengthPrefixedArray<ArtMethod> * new_methods,uint32_t num_direct,uint32_t num_virtual)259 inline void Class::SetMethodsPtrUnchecked(LengthPrefixedArray<ArtMethod>* new_methods,
260                                           uint32_t num_direct,
261                                           uint32_t num_virtual) {
262   DCHECK_LE(num_direct + num_virtual, (new_methods == nullptr) ? 0 : new_methods->size());
263   SetField64<false>(OFFSET_OF_OBJECT_MEMBER(Class, methods_),
264                     static_cast<uint64_t>(reinterpret_cast<uintptr_t>(new_methods)));
265   SetFieldShort<false>(OFFSET_OF_OBJECT_MEMBER(Class, copied_methods_offset_),
266                     dchecked_integral_cast<uint16_t>(num_direct + num_virtual));
267   SetFieldShort<false>(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_offset_),
268                        dchecked_integral_cast<uint16_t>(num_direct));
269 }
270 
271 template<VerifyObjectFlags kVerifyFlags>
GetVirtualMethod(size_t i,PointerSize pointer_size)272 inline ArtMethod* Class::GetVirtualMethod(size_t i, PointerSize pointer_size) {
273   CheckPointerSize(pointer_size);
274   DCHECK(IsResolved<kVerifyFlags>() || IsErroneous<kVerifyFlags>())
275       << Class::PrettyClass() << " status=" << GetStatus();
276   return GetVirtualMethodUnchecked(i, pointer_size);
277 }
278 
GetVirtualMethodDuringLinking(size_t i,PointerSize pointer_size)279 inline ArtMethod* Class::GetVirtualMethodDuringLinking(size_t i, PointerSize pointer_size) {
280   CheckPointerSize(pointer_size);
281   DCHECK(IsLoaded() || IsErroneous());
282   return GetVirtualMethodUnchecked(i, pointer_size);
283 }
284 
GetVirtualMethodUnchecked(size_t i,PointerSize pointer_size)285 inline ArtMethod* Class::GetVirtualMethodUnchecked(size_t i, PointerSize pointer_size) {
286   CheckPointerSize(pointer_size);
287   return &GetVirtualMethodsSliceUnchecked(pointer_size)[i];
288 }
289 
290 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetVTable()291 inline ObjPtr<PointerArray> Class::GetVTable() {
292   DCHECK(IsLoaded<kVerifyFlags>() || IsErroneous<kVerifyFlags>());
293   return GetFieldObject<PointerArray, kVerifyFlags, kReadBarrierOption>(
294       OFFSET_OF_OBJECT_MEMBER(Class, vtable_));
295 }
296 
GetVTableDuringLinking()297 inline ObjPtr<PointerArray> Class::GetVTableDuringLinking() {
298   DCHECK(IsLoaded() || IsErroneous());
299   return GetFieldObject<PointerArray>(OFFSET_OF_OBJECT_MEMBER(Class, vtable_));
300 }
301 
SetVTable(ObjPtr<PointerArray> new_vtable)302 inline void Class::SetVTable(ObjPtr<PointerArray> new_vtable) {
303   SetFieldObject</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
304       OFFSET_OF_OBJECT_MEMBER(Class, vtable_), new_vtable);
305 }
306 
307 template<VerifyObjectFlags kVerifyFlags>
ShouldHaveImt()308 inline bool Class::ShouldHaveImt() {
309   return ShouldHaveEmbeddedVTable<kVerifyFlags>();
310 }
311 
312 template<VerifyObjectFlags kVerifyFlags>
ShouldHaveEmbeddedVTable()313 inline bool Class::ShouldHaveEmbeddedVTable() {
314   return IsInstantiable<kVerifyFlags>();
315 }
316 
HasVTable()317 inline bool Class::HasVTable() {
318   // No read barrier is needed for comparing with null. See ReadBarrierOption.
319   return GetVTable<kDefaultVerifyFlags, kWithoutReadBarrier>() != nullptr ||
320          ShouldHaveEmbeddedVTable();
321 }
322 
323 template<VerifyObjectFlags kVerifyFlags>
GetVTableLength()324 inline int32_t Class::GetVTableLength() {
325   if (ShouldHaveEmbeddedVTable<kVerifyFlags>()) {
326     return GetEmbeddedVTableLength();
327   }
328   // We do not need a read barrier here as the length is constant,
329   // both from-space and to-space vtables shall yield the same result.
330   ObjPtr<PointerArray> vtable = GetVTable<kVerifyFlags, kWithoutReadBarrier>();
331   return vtable != nullptr ? vtable->GetLength() : 0;
332 }
333 
334 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetVTableEntry(uint32_t i,PointerSize pointer_size)335 inline ArtMethod* Class::GetVTableEntry(uint32_t i, PointerSize pointer_size) {
336   if (ShouldHaveEmbeddedVTable<kVerifyFlags>()) {
337     return GetEmbeddedVTableEntry(i, pointer_size);
338   }
339   ObjPtr<PointerArray> vtable = GetVTable<kVerifyFlags, kReadBarrierOption>();
340   DCHECK(vtable != nullptr);
341   return vtable->GetElementPtrSize<ArtMethod*, kVerifyFlags>(i, pointer_size);
342 }
343 
344 template<VerifyObjectFlags kVerifyFlags>
GetEmbeddedVTableLength()345 inline int32_t Class::GetEmbeddedVTableLength() {
346   return GetField32<kVerifyFlags>(MemberOffset(EmbeddedVTableLengthOffset()));
347 }
348 
SetEmbeddedVTableLength(int32_t len)349 inline void Class::SetEmbeddedVTableLength(int32_t len) {
350   SetField32</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
351       MemberOffset(EmbeddedVTableLengthOffset()), len);
352 }
353 
GetImt(PointerSize pointer_size)354 inline ImTable* Class::GetImt(PointerSize pointer_size) {
355   return GetFieldPtrWithSize<ImTable*>(ImtPtrOffset(pointer_size), pointer_size);
356 }
357 
SetImt(ImTable * imt,PointerSize pointer_size)358 inline void Class::SetImt(ImTable* imt, PointerSize pointer_size) {
359   return SetFieldPtrWithSize</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
360       ImtPtrOffset(pointer_size), imt, pointer_size);
361 }
362 
EmbeddedVTableEntryOffset(uint32_t i,PointerSize pointer_size)363 inline MemberOffset Class::EmbeddedVTableEntryOffset(uint32_t i, PointerSize pointer_size) {
364   return MemberOffset(
365       EmbeddedVTableOffset(pointer_size).Uint32Value() + i * VTableEntrySize(pointer_size));
366 }
367 
GetEmbeddedVTableEntry(uint32_t i,PointerSize pointer_size)368 inline ArtMethod* Class::GetEmbeddedVTableEntry(uint32_t i, PointerSize pointer_size) {
369   return GetFieldPtrWithSize<ArtMethod*>(EmbeddedVTableEntryOffset(i, pointer_size), pointer_size);
370 }
371 
SetEmbeddedVTableEntryUnchecked(uint32_t i,ArtMethod * method,PointerSize pointer_size)372 inline void Class::SetEmbeddedVTableEntryUnchecked(
373     uint32_t i, ArtMethod* method, PointerSize pointer_size) {
374   SetFieldPtrWithSize</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
375       EmbeddedVTableEntryOffset(i, pointer_size), method, pointer_size);
376 }
377 
SetEmbeddedVTableEntry(uint32_t i,ArtMethod * method,PointerSize pointer_size)378 inline void Class::SetEmbeddedVTableEntry(uint32_t i, ArtMethod* method, PointerSize pointer_size) {
379   ObjPtr<PointerArray> vtable = GetVTableDuringLinking();
380   CHECK_EQ(method, vtable->GetElementPtrSize<ArtMethod*>(i, pointer_size));
381   SetEmbeddedVTableEntryUnchecked(i, method, pointer_size);
382 }
383 
Implements(ObjPtr<Class> klass)384 inline bool Class::Implements(ObjPtr<Class> klass) {
385   DCHECK(klass != nullptr);
386   DCHECK(klass->IsInterface()) << PrettyClass();
387   // All interfaces implemented directly and by our superclass, and
388   // recursively all super-interfaces of those interfaces, are listed
389   // in iftable_, so we can just do a linear scan through that.
390   int32_t iftable_count = GetIfTableCount();
391   ObjPtr<IfTable> iftable = GetIfTable();
392   for (int32_t i = 0; i < iftable_count; i++) {
393     if (iftable->GetInterface(i) == klass) {
394       return true;
395     }
396   }
397   return false;
398 }
399 
400 template<VerifyObjectFlags kVerifyFlags>
IsVariableSize()401 inline bool Class::IsVariableSize() {
402   // Classes, arrays, and strings vary in size, and so the object_size_ field cannot
403   // be used to Get their instance size
404   return IsClassClass<kVerifyFlags>() ||
405          IsArrayClass<kVerifyFlags>() ||
406          IsStringClass<kVerifyFlags>();
407 }
408 
SetObjectSize(uint32_t new_object_size)409 inline void Class::SetObjectSize(uint32_t new_object_size) {
410   DCHECK(!IsVariableSize());
411   // Not called within a transaction.
412   return SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, object_size_), new_object_size);
413 }
414 
415 // Determine whether "this" is assignable from "src", where both of these
416 // are array classes.
417 //
418 // Consider an array class, e.g. Y[][], where Y is a subclass of X.
419 //   Y[][]            = Y[][] --> true (identity)
420 //   X[][]            = Y[][] --> true (element superclass)
421 //   Y                = Y[][] --> false
422 //   Y[]              = Y[][] --> false
423 //   Object           = Y[][] --> true (everything is an object)
424 //   Object[]         = Y[][] --> true
425 //   Object[][]       = Y[][] --> true
426 //   Object[][][]     = Y[][] --> false (too many []s)
427 //   Serializable     = Y[][] --> true (all arrays are Serializable)
428 //   Serializable[]   = Y[][] --> true
429 //   Serializable[][] = Y[][] --> false (unless Y is Serializable)
430 //
431 // Don't forget about primitive types.
432 //   Object[]         = int[] --> false
433 //
IsArrayAssignableFromArray(ObjPtr<Class> src)434 inline bool Class::IsArrayAssignableFromArray(ObjPtr<Class> src) {
435   DCHECK(IsArrayClass()) << PrettyClass();
436   DCHECK(src->IsArrayClass()) << src->PrettyClass();
437   return GetComponentType()->IsAssignableFrom(src->GetComponentType());
438 }
439 
IsAssignableFromArray(ObjPtr<Class> src)440 inline bool Class::IsAssignableFromArray(ObjPtr<Class> src) {
441   DCHECK(!IsInterface()) << PrettyClass();  // handled first in IsAssignableFrom
442   DCHECK(src->IsArrayClass()) << src->PrettyClass();
443   if (!IsArrayClass()) {
444     // If "this" is not also an array, it must be Object.
445     // src's super should be java_lang_Object, since it is an array.
446     ObjPtr<Class> java_lang_Object = src->GetSuperClass();
447     DCHECK(java_lang_Object != nullptr) << src->PrettyClass();
448     DCHECK(java_lang_Object->GetSuperClass() == nullptr) << src->PrettyClass();
449     return this == java_lang_Object;
450   }
451   return IsArrayAssignableFromArray(src);
452 }
453 
454 template <bool throw_on_failure>
ResolvedFieldAccessTest(ObjPtr<Class> access_to,ArtField * field,ObjPtr<DexCache> dex_cache,uint32_t field_idx)455 inline bool Class::ResolvedFieldAccessTest(ObjPtr<Class> access_to,
456                                            ArtField* field,
457                                            ObjPtr<DexCache> dex_cache,
458                                            uint32_t field_idx) {
459   DCHECK(dex_cache != nullptr);
460   if (UNLIKELY(!this->CanAccess(access_to))) {
461     // The referrer class can't access the field's declaring class but may still be able
462     // to access the field if the FieldId specifies an accessible subclass of the declaring
463     // class rather than the declaring class itself.
464     dex::TypeIndex class_idx = dex_cache->GetDexFile()->GetFieldId(field_idx).class_idx_;
465     // The referenced class has already been resolved with the field, but may not be in the dex
466     // cache. Use LookupResolveType here to search the class table if it is not in the dex cache.
467     // should be no thread suspension due to the class being resolved.
468     ObjPtr<Class> dex_access_to = Runtime::Current()->GetClassLinker()->LookupResolvedType(
469         class_idx,
470         dex_cache,
471         access_to->GetClassLoader());
472     DCHECK(dex_access_to != nullptr);
473     if (UNLIKELY(!this->CanAccess(dex_access_to))) {
474       if (throw_on_failure) {
475         ThrowIllegalAccessErrorClass(this, dex_access_to);
476       }
477       return false;
478     }
479   }
480   if (LIKELY(this->CanAccessMember(access_to, field->GetAccessFlags()))) {
481     return true;
482   }
483   if (throw_on_failure) {
484     ThrowIllegalAccessErrorField(this, field);
485   }
486   return false;
487 }
488 
489 template <bool throw_on_failure>
ResolvedMethodAccessTest(ObjPtr<Class> access_to,ArtMethod * method,ObjPtr<DexCache> dex_cache,uint32_t method_idx,InvokeType throw_invoke_type)490 inline bool Class::ResolvedMethodAccessTest(ObjPtr<Class> access_to,
491                                             ArtMethod* method,
492                                             ObjPtr<DexCache> dex_cache,
493                                             uint32_t method_idx,
494                                             InvokeType throw_invoke_type) {
495   DCHECK(throw_on_failure || throw_invoke_type == kStatic);
496   DCHECK(dex_cache != nullptr);
497   if (UNLIKELY(!this->CanAccess(access_to))) {
498     // The referrer class can't access the method's declaring class but may still be able
499     // to access the method if the MethodId specifies an accessible subclass of the declaring
500     // class rather than the declaring class itself.
501     dex::TypeIndex class_idx = dex_cache->GetDexFile()->GetMethodId(method_idx).class_idx_;
502     // The referenced class has already been resolved with the method, but may not be in the dex
503     // cache.
504     ObjPtr<Class> dex_access_to = Runtime::Current()->GetClassLinker()->LookupResolvedType(
505         class_idx,
506         dex_cache,
507         access_to->GetClassLoader());
508     DCHECK(dex_access_to != nullptr);
509     if (UNLIKELY(!this->CanAccess(dex_access_to))) {
510       if (throw_on_failure) {
511         ThrowIllegalAccessErrorClassForMethodDispatch(this,
512                                                       dex_access_to,
513                                                       method,
514                                                       throw_invoke_type);
515       }
516       return false;
517     }
518   }
519   if (LIKELY(this->CanAccessMember(access_to, method->GetAccessFlags()))) {
520     return true;
521   }
522   if (throw_on_failure) {
523     ThrowIllegalAccessErrorMethod(this, method);
524   }
525   return false;
526 }
527 
CanAccessResolvedField(ObjPtr<Class> access_to,ArtField * field,ObjPtr<DexCache> dex_cache,uint32_t field_idx)528 inline bool Class::CanAccessResolvedField(ObjPtr<Class> access_to,
529                                           ArtField* field,
530                                           ObjPtr<DexCache> dex_cache,
531                                           uint32_t field_idx) {
532   return ResolvedFieldAccessTest<false>(access_to, field, dex_cache, field_idx);
533 }
534 
CheckResolvedFieldAccess(ObjPtr<Class> access_to,ArtField * field,ObjPtr<DexCache> dex_cache,uint32_t field_idx)535 inline bool Class::CheckResolvedFieldAccess(ObjPtr<Class> access_to,
536                                             ArtField* field,
537                                             ObjPtr<DexCache> dex_cache,
538                                             uint32_t field_idx) {
539   return ResolvedFieldAccessTest<true>(access_to, field, dex_cache, field_idx);
540 }
541 
CanAccessResolvedMethod(ObjPtr<Class> access_to,ArtMethod * method,ObjPtr<DexCache> dex_cache,uint32_t method_idx)542 inline bool Class::CanAccessResolvedMethod(ObjPtr<Class> access_to,
543                                            ArtMethod* method,
544                                            ObjPtr<DexCache> dex_cache,
545                                            uint32_t method_idx) {
546   return ResolvedMethodAccessTest<false>(access_to, method, dex_cache, method_idx, kStatic);
547 }
548 
CheckResolvedMethodAccess(ObjPtr<Class> access_to,ArtMethod * method,ObjPtr<DexCache> dex_cache,uint32_t method_idx,InvokeType throw_invoke_type)549 inline bool Class::CheckResolvedMethodAccess(ObjPtr<Class> access_to,
550                                              ArtMethod* method,
551                                              ObjPtr<DexCache> dex_cache,
552                                              uint32_t method_idx,
553                                              InvokeType throw_invoke_type) {
554   return ResolvedMethodAccessTest<true>(
555       access_to, method, dex_cache, method_idx, throw_invoke_type);
556 }
557 
IsObsoleteVersionOf(ObjPtr<Class> klass)558 inline bool Class::IsObsoleteVersionOf(ObjPtr<Class> klass) {
559   DCHECK(!klass->IsObsoleteObject()) << klass->PrettyClass() << " is obsolete!";
560   if (LIKELY(!IsObsoleteObject())) {
561     return false;
562   }
563   ObjPtr<Class> current(klass);
564   do {
565     if (UNLIKELY(current == this)) {
566       return true;
567     } else {
568       current = current->GetObsoleteClass();
569     }
570   } while (!current.IsNull());
571   return false;
572 }
573 
IsSubClass(ObjPtr<Class> klass)574 inline bool Class::IsSubClass(ObjPtr<Class> klass) {
575   // Since the SubtypeCheck::IsSubtypeOf needs to lookup the Depth,
576   // it is always O(Depth) in terms of speed to do the check.
577   //
578   // So always do the "slow" linear scan in normal release builds.
579   //
580   // Future note: If we could have the depth in O(1) we could use the 'fast'
581   // method instead as it avoids a loop and a read barrier.
582   bool result = false;
583   DCHECK(!IsInterface()) << PrettyClass();
584   DCHECK(!IsArrayClass()) << PrettyClass();
585   ObjPtr<Class> current = this;
586   do {
587     if (current == klass) {
588       result = true;
589       break;
590     }
591     current = current->GetSuperClass();
592   } while (current != nullptr);
593 
594   if (kIsDebugBuild && kBitstringSubtypeCheckEnabled) {
595     ObjPtr<mirror::Class> dis(this);
596 
597     SubtypeCheckInfo::Result sc_result = SubtypeCheck<ObjPtr<Class>>::IsSubtypeOf(dis, klass);
598     if (sc_result != SubtypeCheckInfo::kUnknownSubtypeOf) {
599       // Note: The "kUnknownSubTypeOf" can be avoided if and only if:
600       //   SubtypeCheck::EnsureInitialized(source)
601       //       happens-before source.IsSubClass(target)
602       //   SubtypeCheck::EnsureAssigned(target).GetState() == Assigned
603       //       happens-before source.IsSubClass(target)
604       //
605       // When code generated by optimizing compiler executes this operation, both
606       // happens-before are guaranteed, so there is no fallback code there.
607       SubtypeCheckInfo::Result expected_result =
608           result ? SubtypeCheckInfo::kSubtypeOf : SubtypeCheckInfo::kNotSubtypeOf;
609       DCHECK_EQ(expected_result, sc_result)
610           << "source: " << PrettyClass() << "target: " << klass->PrettyClass();
611     }
612   }
613 
614   return result;
615 }
616 
FindVirtualMethodForInterface(ArtMethod * method,PointerSize pointer_size)617 inline ArtMethod* Class::FindVirtualMethodForInterface(ArtMethod* method,
618                                                        PointerSize pointer_size) {
619   ObjPtr<Class> declaring_class = method->GetDeclaringClass();
620   DCHECK(declaring_class != nullptr) << PrettyClass();
621   if (UNLIKELY(!declaring_class->IsInterface())) {
622     DCHECK(declaring_class->IsObjectClass()) << method->PrettyMethod();
623     DCHECK(method->IsPublic() && !method->IsStatic());
624     return FindVirtualMethodForVirtual(method, pointer_size);
625   }
626   DCHECK(!method->IsCopied());
627   // TODO cache to improve lookup speed
628   const int32_t iftable_count = GetIfTableCount();
629   ObjPtr<IfTable> iftable = GetIfTable();
630   for (int32_t i = 0; i < iftable_count; i++) {
631     if (iftable->GetInterface(i) == declaring_class) {
632       return iftable->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
633           method->GetMethodIndex(), pointer_size);
634     }
635   }
636   return nullptr;
637 }
638 
FindVirtualMethodForVirtual(ArtMethod * method,PointerSize pointer_size)639 inline ArtMethod* Class::FindVirtualMethodForVirtual(ArtMethod* method, PointerSize pointer_size) {
640   // Only miranda or default methods may come from interfaces and be used as a virtual.
641   DCHECK(!method->GetDeclaringClass()->IsInterface() || method->IsDefault() || method->IsMiranda());
642   // The argument method may from a super class.
643   // Use the index to a potentially overridden one for this instance's class.
644   return GetVTableEntry(method->GetMethodIndex(), pointer_size);
645 }
646 
FindVirtualMethodForSuper(ArtMethod * method,PointerSize pointer_size)647 inline ArtMethod* Class::FindVirtualMethodForSuper(ArtMethod* method, PointerSize pointer_size) {
648   DCHECK(!method->GetDeclaringClass()->IsInterface());
649   return GetSuperClass()->GetVTableEntry(method->GetMethodIndex(), pointer_size);
650 }
651 
FindVirtualMethodForVirtualOrInterface(ArtMethod * method,PointerSize pointer_size)652 inline ArtMethod* Class::FindVirtualMethodForVirtualOrInterface(ArtMethod* method,
653                                                                 PointerSize pointer_size) {
654   if (method->IsDirect()) {
655     return method;
656   }
657   if (method->GetDeclaringClass()->IsInterface() && !method->IsCopied()) {
658     return FindVirtualMethodForInterface(method, pointer_size);
659   }
660   return FindVirtualMethodForVirtual(method, pointer_size);
661 }
662 
663 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetIfTable()664 inline ObjPtr<IfTable> Class::GetIfTable() {
665   ObjPtr<IfTable> ret = GetFieldObject<IfTable, kVerifyFlags, kReadBarrierOption>(IfTableOffset());
666   DCHECK(ret != nullptr) << PrettyClass(this);
667   return ret;
668 }
669 
670 template<VerifyObjectFlags kVerifyFlags>
GetIfTableCount()671 inline int32_t Class::GetIfTableCount() {
672   // We do not need a read barrier here as the length is constant,
673   // both from-space and to-space iftables shall yield the same result.
674   return GetIfTable<kVerifyFlags, kWithoutReadBarrier>()->Count();
675 }
676 
SetIfTable(ObjPtr<IfTable> new_iftable)677 inline void Class::SetIfTable(ObjPtr<IfTable> new_iftable) {
678   DCHECK(new_iftable != nullptr) << PrettyClass(this);
679   SetFieldObject</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
680       IfTableOffset(), new_iftable);
681 }
682 
GetIFieldsPtr()683 inline LengthPrefixedArray<ArtField>* Class::GetIFieldsPtr() {
684   DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
685   return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
686 }
687 
688 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetFirstReferenceInstanceFieldOffset()689 inline MemberOffset Class::GetFirstReferenceInstanceFieldOffset() {
690   ObjPtr<Class> super_class = GetSuperClass<kVerifyFlags, kReadBarrierOption>();
691   return (super_class != nullptr)
692       ? MemberOffset(RoundUp(super_class->GetObjectSize<kVerifyFlags>(), kHeapReferenceSize))
693       : ClassOffset();
694 }
695 
696 template <VerifyObjectFlags kVerifyFlags>
GetFirstReferenceStaticFieldOffset(PointerSize pointer_size)697 inline MemberOffset Class::GetFirstReferenceStaticFieldOffset(PointerSize pointer_size) {
698   DCHECK(IsResolved<kVerifyFlags>());
699   uint32_t base = sizeof(Class);  // Static fields come after the class.
700   if (ShouldHaveEmbeddedVTable<kVerifyFlags>()) {
701     // Static fields come after the embedded tables.
702     base = Class::ComputeClassSize(
703         true, GetEmbeddedVTableLength<kVerifyFlags>(), 0, 0, 0, 0, 0, pointer_size);
704   }
705   return MemberOffset(base);
706 }
707 
GetFirstReferenceStaticFieldOffsetDuringLinking(PointerSize pointer_size)708 inline MemberOffset Class::GetFirstReferenceStaticFieldOffsetDuringLinking(
709     PointerSize pointer_size) {
710   DCHECK(IsLoaded());
711   uint32_t base = sizeof(Class);  // Static fields come after the class.
712   if (ShouldHaveEmbeddedVTable()) {
713     // Static fields come after the embedded tables.
714     base = Class::ComputeClassSize(true, GetVTableDuringLinking()->GetLength(),
715                                            0, 0, 0, 0, 0, pointer_size);
716   }
717   return MemberOffset(base);
718 }
719 
SetIFieldsPtr(LengthPrefixedArray<ArtField> * new_ifields)720 inline void Class::SetIFieldsPtr(LengthPrefixedArray<ArtField>* new_ifields) {
721   DCHECK(GetIFieldsPtrUnchecked() == nullptr);
722   return SetFieldPtr<false>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
723 }
724 
SetIFieldsPtrUnchecked(LengthPrefixedArray<ArtField> * new_ifields)725 inline void Class::SetIFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_ifields) {
726   SetFieldPtr<false, true, kVerifyNone>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
727 }
728 
GetSFieldsPtrUnchecked()729 inline LengthPrefixedArray<ArtField>* Class::GetSFieldsPtrUnchecked() {
730   return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
731 }
732 
GetIFieldsPtrUnchecked()733 inline LengthPrefixedArray<ArtField>* Class::GetIFieldsPtrUnchecked() {
734   return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
735 }
736 
GetSFieldsPtr()737 inline LengthPrefixedArray<ArtField>* Class::GetSFieldsPtr() {
738   DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
739   return GetSFieldsPtrUnchecked();
740 }
741 
SetSFieldsPtr(LengthPrefixedArray<ArtField> * new_sfields)742 inline void Class::SetSFieldsPtr(LengthPrefixedArray<ArtField>* new_sfields) {
743   DCHECK((IsRetired() && new_sfields == nullptr) ||
744          GetFieldPtr<ArtField*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_)) == nullptr);
745   SetFieldPtr<false>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
746 }
747 
SetSFieldsPtrUnchecked(LengthPrefixedArray<ArtField> * new_sfields)748 inline void Class::SetSFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_sfields) {
749   SetFieldPtr<false, true, kVerifyNone>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
750 }
751 
GetStaticField(uint32_t i)752 inline ArtField* Class::GetStaticField(uint32_t i) {
753   return &GetSFieldsPtr()->At(i);
754 }
755 
GetInstanceField(uint32_t i)756 inline ArtField* Class::GetInstanceField(uint32_t i) {
757   return &GetIFieldsPtr()->At(i);
758 }
759 
760 template<VerifyObjectFlags kVerifyFlags>
GetReferenceInstanceOffsets()761 inline uint32_t Class::GetReferenceInstanceOffsets() {
762   DCHECK(IsResolved<kVerifyFlags>() || IsErroneous<kVerifyFlags>());
763   return GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_));
764 }
765 
SetClinitThreadId(pid_t new_clinit_thread_id)766 inline void Class::SetClinitThreadId(pid_t new_clinit_thread_id) {
767   SetField32Transaction(OFFSET_OF_OBJECT_MEMBER(Class, clinit_thread_id_), new_clinit_thread_id);
768 }
769 
770 template<VerifyObjectFlags kVerifyFlags,
771          ReadBarrierOption kReadBarrierOption>
GetName()772 inline ObjPtr<String> Class::GetName() {
773   return GetFieldObject<String, kVerifyFlags, kReadBarrierOption>(
774       OFFSET_OF_OBJECT_MEMBER(Class, name_));
775 }
776 
SetName(ObjPtr<String> name)777 inline void Class::SetName(ObjPtr<String> name) {
778   SetFieldObjectTransaction(OFFSET_OF_OBJECT_MEMBER(Class, name_), name);
779 }
780 
781 template<VerifyObjectFlags kVerifyFlags>
GetPrimitiveType()782 inline Primitive::Type Class::GetPrimitiveType() {
783   static_assert(sizeof(Primitive::Type) == sizeof(int32_t),
784                 "art::Primitive::Type and int32_t have different sizes.");
785   int32_t v32 = GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, primitive_type_));
786   Primitive::Type type = static_cast<Primitive::Type>(v32 & kPrimitiveTypeMask);
787   DCHECK_EQ(static_cast<size_t>(v32 >> kPrimitiveTypeSizeShiftShift),
788             Primitive::ComponentSizeShift(type));
789   return type;
790 }
791 
792 template<VerifyObjectFlags kVerifyFlags>
GetPrimitiveTypeSizeShift()793 inline size_t Class::GetPrimitiveTypeSizeShift() {
794   static_assert(sizeof(Primitive::Type) == sizeof(int32_t),
795                 "art::Primitive::Type and int32_t have different sizes.");
796   int32_t v32 = GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, primitive_type_));
797   size_t size_shift = static_cast<Primitive::Type>(v32 >> kPrimitiveTypeSizeShiftShift);
798   DCHECK_EQ(size_shift,
799             Primitive::ComponentSizeShift(static_cast<Primitive::Type>(v32 & kPrimitiveTypeMask)));
800   return size_shift;
801 }
802 
ComputeClassSize(bool has_embedded_vtable,uint32_t num_vtable_entries,uint32_t num_8bit_static_fields,uint32_t num_16bit_static_fields,uint32_t num_32bit_static_fields,uint32_t num_64bit_static_fields,uint32_t num_ref_static_fields,PointerSize pointer_size)803 inline uint32_t Class::ComputeClassSize(bool has_embedded_vtable,
804                                         uint32_t num_vtable_entries,
805                                         uint32_t num_8bit_static_fields,
806                                         uint32_t num_16bit_static_fields,
807                                         uint32_t num_32bit_static_fields,
808                                         uint32_t num_64bit_static_fields,
809                                         uint32_t num_ref_static_fields,
810                                         PointerSize pointer_size) {
811   // Space used by java.lang.Class and its instance fields.
812   uint32_t size = sizeof(Class);
813   // Space used by embedded tables.
814   if (has_embedded_vtable) {
815     size = RoundUp(size + sizeof(uint32_t), static_cast<size_t>(pointer_size));
816     size += static_cast<size_t>(pointer_size);  // size of pointer to IMT
817     size += num_vtable_entries * VTableEntrySize(pointer_size);
818   }
819 
820   // Space used by reference statics.
821   size += num_ref_static_fields * kHeapReferenceSize;
822   if (!IsAligned<8>(size) && num_64bit_static_fields > 0) {
823     uint32_t gap = 8 - (size & 0x7);
824     size += gap;  // will be padded
825     // Shuffle 4-byte fields forward.
826     while (gap >= sizeof(uint32_t) && num_32bit_static_fields != 0) {
827       --num_32bit_static_fields;
828       gap -= sizeof(uint32_t);
829     }
830     // Shuffle 2-byte fields forward.
831     while (gap >= sizeof(uint16_t) && num_16bit_static_fields != 0) {
832       --num_16bit_static_fields;
833       gap -= sizeof(uint16_t);
834     }
835     // Shuffle byte fields forward.
836     while (gap >= sizeof(uint8_t) && num_8bit_static_fields != 0) {
837       --num_8bit_static_fields;
838       gap -= sizeof(uint8_t);
839     }
840   }
841   // Guaranteed to be at least 4 byte aligned. No need for further alignments.
842   // Space used for primitive static fields.
843   size += num_8bit_static_fields * sizeof(uint8_t) + num_16bit_static_fields * sizeof(uint16_t) +
844       num_32bit_static_fields * sizeof(uint32_t) + num_64bit_static_fields * sizeof(uint64_t);
845   return size;
846 }
847 
848 template<VerifyObjectFlags kVerifyFlags>
IsClassClass()849 inline bool Class::IsClassClass() {
850   // OK to look at from-space copies since java.lang.Class.class is non-moveable
851   // (even when running without boot image, see ClassLinker::InitWithoutImage())
852   // and we're reading it for comparison only. See ReadBarrierOption.
853   ObjPtr<Class> java_lang_Class = GetClass<kVerifyFlags, kWithoutReadBarrier>();
854   return this == java_lang_Class;
855 }
856 
GetDexFile()857 inline const DexFile& Class::GetDexFile() {
858   // From-space version is the same as the to-space version since the dex file never changes.
859   // Avoiding the read barrier here is important to prevent recursive AssertToSpaceInvariant issues
860   // from PrettyTypeOf.
861   return *GetDexCache<kDefaultVerifyFlags, kWithoutReadBarrier>()->GetDexFile();
862 }
863 
DescriptorEquals(const char * match)864 inline bool Class::DescriptorEquals(const char* match) {
865   ObjPtr<mirror::Class> klass = this;
866   while (klass->IsArrayClass()) {
867     if (match[0] != '[') {
868       return false;
869     }
870     ++match;
871     // No read barrier needed, we're reading a chain of constant references for comparison
872     // with null. Then we follow up below with reading constant references to read constant
873     // primitive data in both proxy and non-proxy paths. See ReadBarrierOption.
874     klass = klass->GetComponentType<kDefaultVerifyFlags, kWithoutReadBarrier>();
875   }
876   if (klass->IsPrimitive()) {
877     return strcmp(Primitive::Descriptor(klass->GetPrimitiveType()), match) == 0;
878   } else if (klass->IsProxyClass()) {
879     return klass->ProxyDescriptorEquals(match);
880   } else {
881     const DexFile& dex_file = klass->GetDexFile();
882     const dex::TypeId& type_id = dex_file.GetTypeId(klass->GetDexTypeIndex());
883     return strcmp(dex_file.GetTypeDescriptor(type_id), match) == 0;
884   }
885 }
886 
AssertInitializedOrInitializingInThread(Thread * self)887 inline void Class::AssertInitializedOrInitializingInThread(Thread* self) {
888   if (kIsDebugBuild && !IsInitialized()) {
889     CHECK(IsInitializing()) << PrettyClass() << " is not initializing: " << GetStatus();
890     CHECK_EQ(GetClinitThreadId(), self->GetTid())
891         << PrettyClass() << " is initializing in a different thread";
892   }
893 }
894 
GetProxyInterfaces()895 inline ObjPtr<ObjectArray<Class>> Class::GetProxyInterfaces() {
896   CHECK(IsProxyClass());
897   // First static field.
898   ArtField* field = GetStaticField(0);
899   DCHECK_STREQ(field->GetName(), "interfaces");
900   MemberOffset field_offset = field->GetOffset();
901   return GetFieldObject<ObjectArray<Class>>(field_offset);
902 }
903 
GetProxyThrows()904 inline ObjPtr<ObjectArray<ObjectArray<Class>>> Class::GetProxyThrows() {
905   CHECK(IsProxyClass());
906   // Second static field.
907   ArtField* field = GetStaticField(1);
908   DCHECK_STREQ(field->GetName(), "throws");
909   MemberOffset field_offset = field->GetOffset();
910   return GetFieldObject<ObjectArray<ObjectArray<Class>>>(field_offset);
911 }
912 
IsBootStrapClassLoaded()913 inline bool Class::IsBootStrapClassLoaded() {
914   // No read barrier is needed for comparing with null. See ReadBarrierOption.
915   return GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() == nullptr;
916 }
917 
operator()918 inline void Class::InitializeClassVisitor::operator()(ObjPtr<Object> obj,
919                                                       size_t usable_size) const {
920   DCHECK_LE(class_size_, usable_size);
921   // Avoid AsClass as object is not yet in live bitmap or allocation stack.
922   ObjPtr<Class> klass = ObjPtr<Class>::DownCast(obj);
923   klass->SetClassSize(class_size_);
924   klass->SetPrimitiveType(Primitive::kPrimNot);  // Default to not being primitive.
925   klass->SetDexClassDefIndex(DexFile::kDexNoIndex16);  // Default to no valid class def index.
926   klass->SetDexTypeIndex(dex::TypeIndex(DexFile::kDexNoIndex16));  // Default to no valid type
927                                                                    // index.
928   // Default to force slow path until visibly initialized.
929   // There is no need for release store (volatile) in pre-fence visitor.
930   klass->SetField32</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
931       ObjectSizeAllocFastPathOffset(), std::numeric_limits<uint32_t>::max());
932 }
933 
SetAccessFlagsDuringLinking(uint32_t new_access_flags)934 inline void Class::SetAccessFlagsDuringLinking(uint32_t new_access_flags) {
935   SetField32</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
936       AccessFlagsOffset(), new_access_flags);
937 }
938 
SetAccessFlags(uint32_t new_access_flags)939 inline void Class::SetAccessFlags(uint32_t new_access_flags) {
940   if (kIsDebugBuild) {
941     SetAccessFlagsDCheck(new_access_flags);
942   }
943   // Called inside a transaction when setting pre-verified flag during boot image compilation.
944   if (Runtime::Current()->IsActiveTransaction()) {
945     SetField32<true>(AccessFlagsOffset(), new_access_flags);
946   } else {
947     SetField32<false>(AccessFlagsOffset(), new_access_flags);
948   }
949 }
950 
SetClassFlags(uint32_t new_flags)951 inline void Class::SetClassFlags(uint32_t new_flags) {
952   SetField32</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
953       OFFSET_OF_OBJECT_MEMBER(Class, class_flags_), new_flags);
954 }
955 
NumDirectInterfaces()956 inline uint32_t Class::NumDirectInterfaces() {
957   if (IsPrimitive()) {
958     return 0;
959   } else if (IsArrayClass()) {
960     return 2;
961   } else if (IsProxyClass()) {
962     ObjPtr<ObjectArray<Class>> interfaces = GetProxyInterfaces();
963     return interfaces != nullptr ? interfaces->GetLength() : 0;
964   } else {
965     const dex::TypeList* interfaces = GetInterfaceTypeList();
966     if (interfaces == nullptr) {
967       return 0;
968     } else {
969       return interfaces->Size();
970     }
971   }
972 }
973 
GetDirectMethods(PointerSize pointer_size)974 inline ArraySlice<ArtMethod> Class::GetDirectMethods(PointerSize pointer_size) {
975   CheckPointerSize(pointer_size);
976   return GetDirectMethodsSliceUnchecked(pointer_size);
977 }
978 
GetDeclaredMethods(PointerSize pointer_size)979 inline ArraySlice<ArtMethod> Class::GetDeclaredMethods(PointerSize pointer_size) {
980   return GetDeclaredMethodsSliceUnchecked(pointer_size);
981 }
982 
GetDeclaredVirtualMethods(PointerSize pointer_size)983 inline ArraySlice<ArtMethod> Class::GetDeclaredVirtualMethods(PointerSize pointer_size) {
984   return GetDeclaredVirtualMethodsSliceUnchecked(pointer_size);
985 }
986 
GetVirtualMethods(PointerSize pointer_size)987 inline ArraySlice<ArtMethod> Class::GetVirtualMethods(PointerSize pointer_size) {
988   CheckPointerSize(pointer_size);
989   return GetVirtualMethodsSliceUnchecked(pointer_size);
990 }
991 
GetCopiedMethods(PointerSize pointer_size)992 inline ArraySlice<ArtMethod> Class::GetCopiedMethods(PointerSize pointer_size) {
993   CheckPointerSize(pointer_size);
994   return GetCopiedMethodsSliceUnchecked(pointer_size);
995 }
996 
997 
GetMethods(PointerSize pointer_size)998 inline ArraySlice<ArtMethod> Class::GetMethods(PointerSize pointer_size) {
999   CheckPointerSize(pointer_size);
1000   LengthPrefixedArray<ArtMethod>* methods = GetMethodsPtr();
1001   return GetMethodsSliceRangeUnchecked(methods, pointer_size, 0u, NumMethods(methods));
1002 }
1003 
GetIFields()1004 inline IterationRange<StrideIterator<ArtField>> Class::GetIFields() {
1005   return MakeIterationRangeFromLengthPrefixedArray(GetIFieldsPtr());
1006 }
1007 
GetSFields()1008 inline IterationRange<StrideIterator<ArtField>> Class::GetSFields() {
1009   return MakeIterationRangeFromLengthPrefixedArray(GetSFieldsPtr());
1010 }
1011 
GetIFieldsUnchecked()1012 inline IterationRange<StrideIterator<ArtField>> Class::GetIFieldsUnchecked() {
1013   return MakeIterationRangeFromLengthPrefixedArray(GetIFieldsPtrUnchecked());
1014 }
1015 
GetSFieldsUnchecked()1016 inline IterationRange<StrideIterator<ArtField>> Class::GetSFieldsUnchecked() {
1017   return MakeIterationRangeFromLengthPrefixedArray(GetSFieldsPtrUnchecked());
1018 }
1019 
CheckPointerSize(PointerSize pointer_size)1020 inline void Class::CheckPointerSize(PointerSize pointer_size) {
1021   DCHECK_EQ(pointer_size, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
1022 }
1023 
1024 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetComponentType()1025 inline ObjPtr<Class> Class::GetComponentType() {
1026   return GetFieldObject<Class, kVerifyFlags, kReadBarrierOption>(ComponentTypeOffset());
1027 }
1028 
SetComponentType(ObjPtr<Class> new_component_type)1029 inline void Class::SetComponentType(ObjPtr<Class> new_component_type) {
1030   DCHECK(GetComponentType() == nullptr);
1031   DCHECK(new_component_type != nullptr);
1032   // Component type is invariant: use non-transactional mode without check.
1033   SetFieldObject</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
1034       ComponentTypeOffset(), new_component_type);
1035 }
1036 
GetComponentSize()1037 inline size_t Class::GetComponentSize() {
1038   return 1U << GetComponentSizeShift();
1039 }
1040 
GetComponentSizeShift()1041 inline size_t Class::GetComponentSizeShift() {
1042   // No read barrier is needed for reading a constant primitive field through
1043   // constant reference field. See ReadBarrierOption.
1044   return GetComponentType<kDefaultVerifyFlags, kWithoutReadBarrier>()->GetPrimitiveTypeSizeShift();
1045 }
1046 
IsObjectClass()1047 inline bool Class::IsObjectClass() {
1048   // No read barrier is needed for comparing with null. See ReadBarrierOption.
1049   return !IsPrimitive() && GetSuperClass<kDefaultVerifyFlags, kWithoutReadBarrier>() == nullptr;
1050 }
1051 
IsInstantiableNonArray()1052 inline bool Class::IsInstantiableNonArray() {
1053   return !IsPrimitive() && !IsInterface() && !IsAbstract() && !IsArrayClass();
1054 }
1055 
1056 template<VerifyObjectFlags kVerifyFlags>
IsInstantiable()1057 bool Class::IsInstantiable() {
1058   return (!IsPrimitive<kVerifyFlags>() &&
1059           !IsInterface<kVerifyFlags>() &&
1060           !IsAbstract<kVerifyFlags>()) ||
1061       (IsAbstract<kVerifyFlags>() && IsArrayClass<kVerifyFlags>());
1062 }
1063 
1064 template<VerifyObjectFlags kVerifyFlags>
IsArrayClass()1065 inline bool Class::IsArrayClass() {
1066   // We do not need a read barrier for comparing with null.
1067   return GetComponentType<kVerifyFlags, kWithoutReadBarrier>() != nullptr;
1068 }
1069 
1070 template<VerifyObjectFlags kVerifyFlags>
IsObjectArrayClass()1071 inline bool Class::IsObjectArrayClass() {
1072   // We do not need a read barrier here as the primitive type is constant,
1073   // both from-space and to-space component type classes shall yield the same result.
1074   const ObjPtr<Class> component_type = GetComponentType<kVerifyFlags, kWithoutReadBarrier>();
1075   constexpr VerifyObjectFlags kNewFlags = RemoveThisFlags(kVerifyFlags);
1076   return component_type != nullptr && !component_type->IsPrimitive<kNewFlags>();
1077 }
1078 
1079 template<VerifyObjectFlags kVerifyFlags>
IsPrimitiveArray()1080 bool Class::IsPrimitiveArray() {
1081   // We do not need a read barrier here as the primitive type is constant,
1082   // both from-space and to-space component type classes shall yield the same result.
1083   const ObjPtr<Class> component_type = GetComponentType<kVerifyFlags, kWithoutReadBarrier>();
1084   constexpr VerifyObjectFlags kNewFlags = RemoveThisFlags(kVerifyFlags);
1085   return component_type != nullptr && component_type->IsPrimitive<kNewFlags>();
1086 }
1087 
IsAssignableFrom(ObjPtr<Class> src)1088 inline bool Class::IsAssignableFrom(ObjPtr<Class> src) {
1089   DCHECK(src != nullptr);
1090   if (this == src) {
1091     // Can always assign to things of the same type.
1092     return true;
1093   } else if (IsObjectClass()) {
1094     // Can assign any reference to java.lang.Object.
1095     return !src->IsPrimitive();
1096   } else if (IsInterface()) {
1097     return src->Implements(this);
1098   } else if (src->IsArrayClass()) {
1099     return IsAssignableFromArray(src);
1100   } else {
1101     return !src->IsInterface() && src->IsSubClass(this);
1102   }
1103 }
1104 
NumDirectMethods()1105 inline uint32_t Class::NumDirectMethods() {
1106   return GetVirtualMethodsStartOffset();
1107 }
1108 
NumDeclaredVirtualMethods()1109 inline uint32_t Class::NumDeclaredVirtualMethods() {
1110   return GetCopiedMethodsStartOffset() - GetVirtualMethodsStartOffset();
1111 }
1112 
NumVirtualMethods()1113 inline uint32_t Class::NumVirtualMethods() {
1114   return NumMethods() - GetVirtualMethodsStartOffset();
1115 }
1116 
NumInstanceFields()1117 inline uint32_t Class::NumInstanceFields() {
1118   LengthPrefixedArray<ArtField>* arr = GetIFieldsPtrUnchecked();
1119   return arr != nullptr ? arr->size() : 0u;
1120 }
1121 
NumStaticFields()1122 inline uint32_t Class::NumStaticFields() {
1123   LengthPrefixedArray<ArtField>* arr = GetSFieldsPtrUnchecked();
1124   return arr != nullptr ? arr->size() : 0u;
1125 }
1126 
1127 template <typename T, VerifyObjectFlags kVerifyFlags, typename Visitor>
FixupNativePointer(Class * dest,PointerSize pointer_size,const Visitor & visitor,MemberOffset member_offset)1128 inline void Class::FixupNativePointer(
1129     Class* dest, PointerSize pointer_size, const Visitor& visitor, MemberOffset member_offset) {
1130   void** address =
1131       reinterpret_cast<void**>(reinterpret_cast<uintptr_t>(dest) + member_offset.Uint32Value());
1132   T old_value = GetFieldPtrWithSize<T, kVerifyFlags>(member_offset, pointer_size);
1133   T new_value = visitor(old_value, address);
1134   if (old_value != new_value) {
1135     dest->SetFieldPtrWithSize</* kTransactionActive= */ false,
1136                               /* kCheckTransaction= */ true,
1137                               kVerifyNone>(member_offset, new_value, pointer_size);
1138   }
1139 }
1140 
1141 template <VerifyObjectFlags kVerifyFlags, typename Visitor>
FixupNativePointers(Class * dest,PointerSize pointer_size,const Visitor & visitor)1142 inline void Class::FixupNativePointers(Class* dest,
1143                                        PointerSize pointer_size,
1144                                        const Visitor& visitor) {
1145   // Update the field arrays.
1146   FixupNativePointer<LengthPrefixedArray<ArtField>*, kVerifyFlags>(
1147       dest, pointer_size, visitor, OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
1148   FixupNativePointer<LengthPrefixedArray<ArtField>*, kVerifyFlags>(
1149       dest, pointer_size, visitor, OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
1150   // Update method array.
1151   FixupNativePointer<LengthPrefixedArray<ArtMethod>*, kVerifyFlags>(
1152       dest, pointer_size, visitor, OFFSET_OF_OBJECT_MEMBER(Class, methods_));
1153   // Fix up embedded tables.
1154   if (!IsTemp<kVerifyNone>() && ShouldHaveEmbeddedVTable<kVerifyNone>()) {
1155     for (int32_t i = 0, count = GetEmbeddedVTableLength<kVerifyFlags>(); i < count; ++i) {
1156       FixupNativePointer<ArtMethod*, kVerifyFlags>(
1157           dest, pointer_size, visitor, EmbeddedVTableEntryOffset(i, pointer_size));
1158     }
1159   }
1160   if (!IsTemp<kVerifyNone>() && ShouldHaveImt<kVerifyNone>()) {
1161     FixupNativePointer<ImTable*, kVerifyFlags>(
1162         dest, pointer_size, visitor, ImtPtrOffset(pointer_size));
1163   }
1164 }
1165 
CanAccess(ObjPtr<Class> that)1166 inline bool Class::CanAccess(ObjPtr<Class> that) {
1167   return that->IsPublic() || this->IsInSamePackage(that);
1168 }
1169 
1170 
CanAccessMember(ObjPtr<Class> access_to,uint32_t member_flags)1171 inline bool Class::CanAccessMember(ObjPtr<Class> access_to, uint32_t member_flags) {
1172   // Classes can access all of their own members
1173   if (this == access_to) {
1174     return true;
1175   }
1176   // Public members are trivially accessible
1177   if (member_flags & kAccPublic) {
1178     return true;
1179   }
1180   // Private members are trivially not accessible
1181   if (member_flags & kAccPrivate) {
1182     return false;
1183   }
1184   // Check for protected access from a sub-class, which may or may not be in the same package.
1185   if (member_flags & kAccProtected) {
1186     if (!this->IsInterface() && this->IsSubClass(access_to)) {
1187       return true;
1188     }
1189   }
1190   // Allow protected access from other classes in the same package.
1191   return this->IsInSamePackage(access_to);
1192 }
1193 
CannotBeAssignedFromOtherTypes()1194 inline bool Class::CannotBeAssignedFromOtherTypes() {
1195   if (!IsArrayClass()) {
1196     return IsFinal();
1197   }
1198   ObjPtr<Class> component = GetComponentType();
1199   return component->IsPrimitive() || component->CannotBeAssignedFromOtherTypes();
1200 }
1201 
SetClassLoader(ObjPtr<ClassLoader> new_class_loader)1202 inline void Class::SetClassLoader(ObjPtr<ClassLoader> new_class_loader) {
1203   SetFieldObject</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
1204       OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
1205 }
1206 
SetRecursivelyInitialized()1207 inline void Class::SetRecursivelyInitialized() {
1208   DCHECK_EQ(GetLockOwnerThreadId(), Thread::Current()->GetThreadId());
1209   uint32_t flags = GetField32(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_));
1210   SetAccessFlags(flags | kAccRecursivelyInitialized);
1211 }
1212 
SetHasDefaultMethods()1213 inline void Class::SetHasDefaultMethods() {
1214   DCHECK_EQ(GetLockOwnerThreadId(), Thread::Current()->GetThreadId());
1215   uint32_t flags = GetField32(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_));
1216   SetAccessFlagsDuringLinking(flags | kAccHasDefaultMethod);
1217 }
1218 
1219 }  // namespace mirror
1220 }  // namespace art
1221 
1222 #endif  // ART_RUNTIME_MIRROR_CLASS_INL_H_
1223