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 "hidden_api.h"
36 #include "iftable-inl.h"
37 #include "imtable.h"
38 #include "object-inl.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 template<typename T>
IsDiscoverable(bool public_only,const hiddenapi::AccessContext & access_context,T * member)416 inline bool Class::IsDiscoverable(bool public_only,
417 const hiddenapi::AccessContext& access_context,
418 T* member) {
419 if (public_only && ((member->GetAccessFlags() & kAccPublic) == 0)) {
420 return false;
421 }
422
423 return !hiddenapi::ShouldDenyAccessToMember(
424 member, access_context, hiddenapi::AccessMethod::kNone);
425 }
426
427 // Determine whether "this" is assignable from "src", where both of these
428 // are array classes.
429 //
430 // Consider an array class, e.g. Y[][], where Y is a subclass of X.
431 // Y[][] = Y[][] --> true (identity)
432 // X[][] = Y[][] --> true (element superclass)
433 // Y = Y[][] --> false
434 // Y[] = Y[][] --> false
435 // Object = Y[][] --> true (everything is an object)
436 // Object[] = Y[][] --> true
437 // Object[][] = Y[][] --> true
438 // Object[][][] = Y[][] --> false (too many []s)
439 // Serializable = Y[][] --> true (all arrays are Serializable)
440 // Serializable[] = Y[][] --> true
441 // Serializable[][] = Y[][] --> false (unless Y is Serializable)
442 //
443 // Don't forget about primitive types.
444 // Object[] = int[] --> false
445 //
IsArrayAssignableFromArray(ObjPtr<Class> src)446 inline bool Class::IsArrayAssignableFromArray(ObjPtr<Class> src) {
447 DCHECK(IsArrayClass()) << PrettyClass();
448 DCHECK(src->IsArrayClass()) << src->PrettyClass();
449 return GetComponentType()->IsAssignableFrom(src->GetComponentType());
450 }
451
IsAssignableFromArray(ObjPtr<Class> src)452 inline bool Class::IsAssignableFromArray(ObjPtr<Class> src) {
453 DCHECK(!IsInterface()) << PrettyClass(); // handled first in IsAssignableFrom
454 DCHECK(src->IsArrayClass()) << src->PrettyClass();
455 if (!IsArrayClass()) {
456 // If "this" is not also an array, it must be Object.
457 // src's super should be java_lang_Object, since it is an array.
458 ObjPtr<Class> java_lang_Object = src->GetSuperClass();
459 DCHECK(java_lang_Object != nullptr) << src->PrettyClass();
460 DCHECK(java_lang_Object->GetSuperClass() == nullptr) << src->PrettyClass();
461 return this == java_lang_Object;
462 }
463 return IsArrayAssignableFromArray(src);
464 }
465
466 template <bool throw_on_failure>
ResolvedFieldAccessTest(ObjPtr<Class> access_to,ArtField * field,ObjPtr<DexCache> dex_cache,uint32_t field_idx)467 inline bool Class::ResolvedFieldAccessTest(ObjPtr<Class> access_to,
468 ArtField* field,
469 ObjPtr<DexCache> dex_cache,
470 uint32_t field_idx) {
471 DCHECK(dex_cache != nullptr);
472 if (UNLIKELY(!this->CanAccess(access_to))) {
473 // The referrer class can't access the field's declaring class but may still be able
474 // to access the field if the FieldId specifies an accessible subclass of the declaring
475 // class rather than the declaring class itself.
476 dex::TypeIndex class_idx = dex_cache->GetDexFile()->GetFieldId(field_idx).class_idx_;
477 // The referenced class has already been resolved with the field, but may not be in the dex
478 // cache. Use LookupResolveType here to search the class table if it is not in the dex cache.
479 // should be no thread suspension due to the class being resolved.
480 ObjPtr<Class> dex_access_to = Runtime::Current()->GetClassLinker()->LookupResolvedType(
481 class_idx,
482 dex_cache,
483 GetClassLoader());
484 DCHECK(dex_access_to != nullptr);
485 if (UNLIKELY(!this->CanAccess(dex_access_to))) {
486 if (throw_on_failure) {
487 ThrowIllegalAccessErrorClass(this, dex_access_to);
488 }
489 return false;
490 }
491 }
492 if (LIKELY(this->CanAccessMember(access_to, field->GetAccessFlags()))) {
493 return true;
494 }
495 if (throw_on_failure) {
496 ThrowIllegalAccessErrorField(this, field);
497 }
498 return false;
499 }
500
501 template <bool throw_on_failure>
ResolvedMethodAccessTest(ObjPtr<Class> access_to,ArtMethod * method,ObjPtr<DexCache> dex_cache,uint32_t method_idx,InvokeType throw_invoke_type)502 inline bool Class::ResolvedMethodAccessTest(ObjPtr<Class> access_to,
503 ArtMethod* method,
504 ObjPtr<DexCache> dex_cache,
505 uint32_t method_idx,
506 InvokeType throw_invoke_type) {
507 DCHECK(throw_on_failure || throw_invoke_type == kStatic);
508 DCHECK(dex_cache != nullptr);
509 if (UNLIKELY(!this->CanAccess(access_to))) {
510 // The referrer class can't access the method's declaring class but may still be able
511 // to access the method if the MethodId specifies an accessible subclass of the declaring
512 // class rather than the declaring class itself.
513 dex::TypeIndex class_idx = dex_cache->GetDexFile()->GetMethodId(method_idx).class_idx_;
514 // The referenced class has already been resolved with the method, but may not be in the dex
515 // cache.
516 ObjPtr<Class> dex_access_to = Runtime::Current()->GetClassLinker()->LookupResolvedType(
517 class_idx,
518 dex_cache,
519 GetClassLoader());
520 DCHECK(dex_access_to != nullptr)
521 << " Could not resolve " << dex_cache->GetDexFile()->StringByTypeIdx(class_idx)
522 << " when checking access to " << method->PrettyMethod() << " from " << PrettyDescriptor();
523 if (UNLIKELY(!this->CanAccess(dex_access_to))) {
524 if (throw_on_failure) {
525 ThrowIllegalAccessErrorClassForMethodDispatch(this,
526 dex_access_to,
527 method,
528 throw_invoke_type);
529 }
530 return false;
531 }
532 }
533 if (LIKELY(this->CanAccessMember(access_to, method->GetAccessFlags()))) {
534 return true;
535 }
536 if (throw_on_failure) {
537 ThrowIllegalAccessErrorMethod(this, method);
538 }
539 return false;
540 }
541
CanAccessResolvedField(ObjPtr<Class> access_to,ArtField * field,ObjPtr<DexCache> dex_cache,uint32_t field_idx)542 inline bool Class::CanAccessResolvedField(ObjPtr<Class> access_to,
543 ArtField* field,
544 ObjPtr<DexCache> dex_cache,
545 uint32_t field_idx) {
546 return ResolvedFieldAccessTest<false>(access_to, field, dex_cache, field_idx);
547 }
548
CheckResolvedFieldAccess(ObjPtr<Class> access_to,ArtField * field,ObjPtr<DexCache> dex_cache,uint32_t field_idx)549 inline bool Class::CheckResolvedFieldAccess(ObjPtr<Class> access_to,
550 ArtField* field,
551 ObjPtr<DexCache> dex_cache,
552 uint32_t field_idx) {
553 return ResolvedFieldAccessTest<true>(access_to, field, dex_cache, field_idx);
554 }
555
CanAccessResolvedMethod(ObjPtr<Class> access_to,ArtMethod * method,ObjPtr<DexCache> dex_cache,uint32_t method_idx)556 inline bool Class::CanAccessResolvedMethod(ObjPtr<Class> access_to,
557 ArtMethod* method,
558 ObjPtr<DexCache> dex_cache,
559 uint32_t method_idx) {
560 return ResolvedMethodAccessTest<false>(access_to, method, dex_cache, method_idx, kStatic);
561 }
562
CheckResolvedMethodAccess(ObjPtr<Class> access_to,ArtMethod * method,ObjPtr<DexCache> dex_cache,uint32_t method_idx,InvokeType throw_invoke_type)563 inline bool Class::CheckResolvedMethodAccess(ObjPtr<Class> access_to,
564 ArtMethod* method,
565 ObjPtr<DexCache> dex_cache,
566 uint32_t method_idx,
567 InvokeType throw_invoke_type) {
568 return ResolvedMethodAccessTest<true>(
569 access_to, method, dex_cache, method_idx, throw_invoke_type);
570 }
571
IsObsoleteVersionOf(ObjPtr<Class> klass)572 inline bool Class::IsObsoleteVersionOf(ObjPtr<Class> klass) {
573 DCHECK(!klass->IsObsoleteObject()) << klass->PrettyClass() << " is obsolete!";
574 if (LIKELY(!IsObsoleteObject())) {
575 return false;
576 }
577 ObjPtr<Class> current(klass);
578 do {
579 if (UNLIKELY(current == this)) {
580 return true;
581 } else {
582 current = current->GetObsoleteClass();
583 }
584 } while (!current.IsNull());
585 return false;
586 }
587
IsSubClass(ObjPtr<Class> klass)588 inline bool Class::IsSubClass(ObjPtr<Class> klass) {
589 // Since the SubtypeCheck::IsSubtypeOf needs to lookup the Depth,
590 // it is always O(Depth) in terms of speed to do the check.
591 //
592 // So always do the "slow" linear scan in normal release builds.
593 //
594 // Future note: If we could have the depth in O(1) we could use the 'fast'
595 // method instead as it avoids a loop and a read barrier.
596 bool result = false;
597 DCHECK(!IsInterface()) << PrettyClass();
598 DCHECK(!IsArrayClass()) << PrettyClass();
599 ObjPtr<Class> current = this;
600 do {
601 if (current == klass) {
602 result = true;
603 break;
604 }
605 current = current->GetSuperClass();
606 } while (current != nullptr);
607
608 if (kIsDebugBuild && kBitstringSubtypeCheckEnabled) {
609 ObjPtr<mirror::Class> dis(this);
610
611 SubtypeCheckInfo::Result sc_result = SubtypeCheck<ObjPtr<Class>>::IsSubtypeOf(dis, klass);
612 if (sc_result != SubtypeCheckInfo::kUnknownSubtypeOf) {
613 // Note: The "kUnknownSubTypeOf" can be avoided if and only if:
614 // SubtypeCheck::EnsureInitialized(source)
615 // happens-before source.IsSubClass(target)
616 // SubtypeCheck::EnsureAssigned(target).GetState() == Assigned
617 // happens-before source.IsSubClass(target)
618 //
619 // When code generated by optimizing compiler executes this operation, both
620 // happens-before are guaranteed, so there is no fallback code there.
621 SubtypeCheckInfo::Result expected_result =
622 result ? SubtypeCheckInfo::kSubtypeOf : SubtypeCheckInfo::kNotSubtypeOf;
623 DCHECK_EQ(expected_result, sc_result)
624 << "source: " << PrettyClass() << "target: " << klass->PrettyClass();
625 }
626 }
627
628 return result;
629 }
630
FindVirtualMethodForInterface(ArtMethod * method,PointerSize pointer_size)631 inline ArtMethod* Class::FindVirtualMethodForInterface(ArtMethod* method,
632 PointerSize pointer_size) {
633 ObjPtr<Class> declaring_class = method->GetDeclaringClass();
634 DCHECK(declaring_class != nullptr) << PrettyClass();
635 if (UNLIKELY(!declaring_class->IsInterface())) {
636 DCHECK(declaring_class->IsObjectClass()) << method->PrettyMethod();
637 DCHECK(method->IsPublic() && !method->IsStatic());
638 return FindVirtualMethodForVirtual(method, pointer_size);
639 }
640 DCHECK(!method->IsCopied());
641 // TODO cache to improve lookup speed
642 const int32_t iftable_count = GetIfTableCount();
643 ObjPtr<IfTable> iftable = GetIfTable();
644 for (int32_t i = 0; i < iftable_count; i++) {
645 if (iftable->GetInterface(i) == declaring_class) {
646 return iftable->GetMethodArray(i)->GetElementPtrSize<ArtMethod*>(
647 method->GetMethodIndex(), pointer_size);
648 }
649 }
650 return nullptr;
651 }
652
FindVirtualMethodForVirtual(ArtMethod * method,PointerSize pointer_size)653 inline ArtMethod* Class::FindVirtualMethodForVirtual(ArtMethod* method, PointerSize pointer_size) {
654 // Only miranda or default methods may come from interfaces and be used as a virtual.
655 DCHECK(!method->GetDeclaringClass()->IsInterface() || method->IsDefault() || method->IsMiranda());
656 // The argument method may from a super class.
657 // Use the index to a potentially overridden one for this instance's class.
658 return GetVTableEntry(method->GetMethodIndex(), pointer_size);
659 }
660
FindVirtualMethodForSuper(ArtMethod * method,PointerSize pointer_size)661 inline ArtMethod* Class::FindVirtualMethodForSuper(ArtMethod* method, PointerSize pointer_size) {
662 DCHECK(!method->GetDeclaringClass()->IsInterface());
663 return GetSuperClass()->GetVTableEntry(method->GetMethodIndex(), pointer_size);
664 }
665
FindVirtualMethodForVirtualOrInterface(ArtMethod * method,PointerSize pointer_size)666 inline ArtMethod* Class::FindVirtualMethodForVirtualOrInterface(ArtMethod* method,
667 PointerSize pointer_size) {
668 if (method->IsDirect()) {
669 return method;
670 }
671 if (method->GetDeclaringClass()->IsInterface() && !method->IsCopied()) {
672 return FindVirtualMethodForInterface(method, pointer_size);
673 }
674 return FindVirtualMethodForVirtual(method, pointer_size);
675 }
676
677 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetIfTable()678 inline ObjPtr<IfTable> Class::GetIfTable() {
679 ObjPtr<IfTable> ret = GetFieldObject<IfTable, kVerifyFlags, kReadBarrierOption>(IfTableOffset());
680 DCHECK(ret != nullptr) << PrettyClass(this);
681 return ret;
682 }
683
684 template<VerifyObjectFlags kVerifyFlags>
GetIfTableCount()685 inline int32_t Class::GetIfTableCount() {
686 // We do not need a read barrier here as the length is constant,
687 // both from-space and to-space iftables shall yield the same result.
688 return GetIfTable<kVerifyFlags, kWithoutReadBarrier>()->Count();
689 }
690
SetIfTable(ObjPtr<IfTable> new_iftable)691 inline void Class::SetIfTable(ObjPtr<IfTable> new_iftable) {
692 DCHECK(new_iftable != nullptr) << PrettyClass(this);
693 SetFieldObject</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
694 IfTableOffset(), new_iftable);
695 }
696
GetIFieldsPtr()697 inline LengthPrefixedArray<ArtField>* Class::GetIFieldsPtr() {
698 DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
699 return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
700 }
701
702 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetFirstReferenceInstanceFieldOffset()703 inline MemberOffset Class::GetFirstReferenceInstanceFieldOffset() {
704 ObjPtr<Class> super_class = GetSuperClass<kVerifyFlags, kReadBarrierOption>();
705 return (super_class != nullptr)
706 ? MemberOffset(RoundUp(super_class->GetObjectSize<kVerifyFlags>(), kHeapReferenceSize))
707 : ClassOffset();
708 }
709
710 template <VerifyObjectFlags kVerifyFlags>
GetFirstReferenceStaticFieldOffset(PointerSize pointer_size)711 inline MemberOffset Class::GetFirstReferenceStaticFieldOffset(PointerSize pointer_size) {
712 DCHECK(IsResolved<kVerifyFlags>());
713 uint32_t base = sizeof(Class); // Static fields come after the class.
714 if (ShouldHaveEmbeddedVTable<kVerifyFlags>()) {
715 // Static fields come after the embedded tables.
716 base = Class::ComputeClassSize(
717 true, GetEmbeddedVTableLength<kVerifyFlags>(), 0, 0, 0, 0, 0, pointer_size);
718 }
719 return MemberOffset(base);
720 }
721
GetFirstReferenceStaticFieldOffsetDuringLinking(PointerSize pointer_size)722 inline MemberOffset Class::GetFirstReferenceStaticFieldOffsetDuringLinking(
723 PointerSize pointer_size) {
724 DCHECK(IsLoaded());
725 uint32_t base = sizeof(Class); // Static fields come after the class.
726 if (ShouldHaveEmbeddedVTable()) {
727 // Static fields come after the embedded tables.
728 base = Class::ComputeClassSize(true, GetVTableDuringLinking()->GetLength(),
729 0, 0, 0, 0, 0, pointer_size);
730 }
731 return MemberOffset(base);
732 }
733
SetIFieldsPtr(LengthPrefixedArray<ArtField> * new_ifields)734 inline void Class::SetIFieldsPtr(LengthPrefixedArray<ArtField>* new_ifields) {
735 DCHECK(GetIFieldsPtrUnchecked() == nullptr);
736 return SetFieldPtr<false>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
737 }
738
SetIFieldsPtrUnchecked(LengthPrefixedArray<ArtField> * new_ifields)739 inline void Class::SetIFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_ifields) {
740 SetFieldPtr<false, true, kVerifyNone>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
741 }
742
GetSFieldsPtrUnchecked()743 inline LengthPrefixedArray<ArtField>* Class::GetSFieldsPtrUnchecked() {
744 return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
745 }
746
GetIFieldsPtrUnchecked()747 inline LengthPrefixedArray<ArtField>* Class::GetIFieldsPtrUnchecked() {
748 return GetFieldPtr<LengthPrefixedArray<ArtField>*>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
749 }
750
GetSFieldsPtr()751 inline LengthPrefixedArray<ArtField>* Class::GetSFieldsPtr() {
752 DCHECK(IsLoaded() || IsErroneous()) << GetStatus();
753 return GetSFieldsPtrUnchecked();
754 }
755
SetSFieldsPtr(LengthPrefixedArray<ArtField> * new_sfields)756 inline void Class::SetSFieldsPtr(LengthPrefixedArray<ArtField>* new_sfields) {
757 DCHECK((IsRetired() && new_sfields == nullptr) ||
758 GetFieldPtr<ArtField*>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_)) == nullptr);
759 SetFieldPtr<false>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
760 }
761
SetSFieldsPtrUnchecked(LengthPrefixedArray<ArtField> * new_sfields)762 inline void Class::SetSFieldsPtrUnchecked(LengthPrefixedArray<ArtField>* new_sfields) {
763 SetFieldPtr<false, true, kVerifyNone>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
764 }
765
GetStaticField(uint32_t i)766 inline ArtField* Class::GetStaticField(uint32_t i) {
767 return &GetSFieldsPtr()->At(i);
768 }
769
GetInstanceField(uint32_t i)770 inline ArtField* Class::GetInstanceField(uint32_t i) {
771 return &GetIFieldsPtr()->At(i);
772 }
773
774 template<VerifyObjectFlags kVerifyFlags>
GetReferenceInstanceOffsets()775 inline uint32_t Class::GetReferenceInstanceOffsets() {
776 DCHECK(IsResolved<kVerifyFlags>() || IsErroneous<kVerifyFlags>());
777 return GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_));
778 }
779
SetClinitThreadId(pid_t new_clinit_thread_id)780 inline void Class::SetClinitThreadId(pid_t new_clinit_thread_id) {
781 SetField32Transaction(OFFSET_OF_OBJECT_MEMBER(Class, clinit_thread_id_), new_clinit_thread_id);
782 }
783
784 template<VerifyObjectFlags kVerifyFlags,
785 ReadBarrierOption kReadBarrierOption>
GetName()786 inline ObjPtr<String> Class::GetName() {
787 return GetFieldObject<String, kVerifyFlags, kReadBarrierOption>(
788 OFFSET_OF_OBJECT_MEMBER(Class, name_));
789 }
790
SetName(ObjPtr<String> name)791 inline void Class::SetName(ObjPtr<String> name) {
792 SetFieldObjectTransaction(OFFSET_OF_OBJECT_MEMBER(Class, name_), name);
793 }
794
795 template<VerifyObjectFlags kVerifyFlags>
GetPrimitiveType()796 inline Primitive::Type Class::GetPrimitiveType() {
797 static_assert(sizeof(Primitive::Type) == sizeof(int32_t),
798 "art::Primitive::Type and int32_t have different sizes.");
799 int32_t v32 = GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, primitive_type_));
800 Primitive::Type type = static_cast<Primitive::Type>(v32 & kPrimitiveTypeMask);
801 DCHECK_EQ(static_cast<size_t>(v32 >> kPrimitiveTypeSizeShiftShift),
802 Primitive::ComponentSizeShift(type));
803 return type;
804 }
805
806 template<VerifyObjectFlags kVerifyFlags>
GetPrimitiveTypeSizeShift()807 inline size_t Class::GetPrimitiveTypeSizeShift() {
808 static_assert(sizeof(Primitive::Type) == sizeof(int32_t),
809 "art::Primitive::Type and int32_t have different sizes.");
810 int32_t v32 = GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, primitive_type_));
811 size_t size_shift = static_cast<Primitive::Type>(v32 >> kPrimitiveTypeSizeShiftShift);
812 DCHECK_EQ(size_shift,
813 Primitive::ComponentSizeShift(static_cast<Primitive::Type>(v32 & kPrimitiveTypeMask)));
814 return size_shift;
815 }
816
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)817 inline uint32_t Class::ComputeClassSize(bool has_embedded_vtable,
818 uint32_t num_vtable_entries,
819 uint32_t num_8bit_static_fields,
820 uint32_t num_16bit_static_fields,
821 uint32_t num_32bit_static_fields,
822 uint32_t num_64bit_static_fields,
823 uint32_t num_ref_static_fields,
824 PointerSize pointer_size) {
825 // Space used by java.lang.Class and its instance fields.
826 uint32_t size = sizeof(Class);
827 // Space used by embedded tables.
828 if (has_embedded_vtable) {
829 size = RoundUp(size + sizeof(uint32_t), static_cast<size_t>(pointer_size));
830 size += static_cast<size_t>(pointer_size); // size of pointer to IMT
831 size += num_vtable_entries * VTableEntrySize(pointer_size);
832 }
833
834 // Space used by reference statics.
835 size += num_ref_static_fields * kHeapReferenceSize;
836 if (!IsAligned<8>(size) && num_64bit_static_fields > 0) {
837 uint32_t gap = 8 - (size & 0x7);
838 size += gap; // will be padded
839 // Shuffle 4-byte fields forward.
840 while (gap >= sizeof(uint32_t) && num_32bit_static_fields != 0) {
841 --num_32bit_static_fields;
842 gap -= sizeof(uint32_t);
843 }
844 // Shuffle 2-byte fields forward.
845 while (gap >= sizeof(uint16_t) && num_16bit_static_fields != 0) {
846 --num_16bit_static_fields;
847 gap -= sizeof(uint16_t);
848 }
849 // Shuffle byte fields forward.
850 while (gap >= sizeof(uint8_t) && num_8bit_static_fields != 0) {
851 --num_8bit_static_fields;
852 gap -= sizeof(uint8_t);
853 }
854 }
855 // Guaranteed to be at least 4 byte aligned. No need for further alignments.
856 // Space used for primitive static fields.
857 size += num_8bit_static_fields * sizeof(uint8_t) + num_16bit_static_fields * sizeof(uint16_t) +
858 num_32bit_static_fields * sizeof(uint32_t) + num_64bit_static_fields * sizeof(uint64_t);
859 return size;
860 }
861
862 template<VerifyObjectFlags kVerifyFlags>
IsClassClass()863 inline bool Class::IsClassClass() {
864 // OK to look at from-space copies since java.lang.Class.class is non-moveable
865 // (even when running without boot image, see ClassLinker::InitWithoutImage())
866 // and we're reading it for comparison only. See ReadBarrierOption.
867 ObjPtr<Class> java_lang_Class = GetClass<kVerifyFlags, kWithoutReadBarrier>();
868 return this == java_lang_Class;
869 }
870
GetDexFile()871 inline const DexFile& Class::GetDexFile() {
872 // From-space version is the same as the to-space version since the dex file never changes.
873 // Avoiding the read barrier here is important to prevent recursive AssertToSpaceInvariant issues
874 // from PrettyTypeOf.
875 return *GetDexCache<kDefaultVerifyFlags, kWithoutReadBarrier>()->GetDexFile();
876 }
877
DescriptorEquals(const char * match)878 inline bool Class::DescriptorEquals(const char* match) {
879 ObjPtr<mirror::Class> klass = this;
880 while (klass->IsArrayClass()) {
881 if (match[0] != '[') {
882 return false;
883 }
884 ++match;
885 // No read barrier needed, we're reading a chain of constant references for comparison
886 // with null. Then we follow up below with reading constant references to read constant
887 // primitive data in both proxy and non-proxy paths. See ReadBarrierOption.
888 klass = klass->GetComponentType<kDefaultVerifyFlags, kWithoutReadBarrier>();
889 }
890 if (klass->IsPrimitive()) {
891 return strcmp(Primitive::Descriptor(klass->GetPrimitiveType()), match) == 0;
892 } else if (klass->IsProxyClass()) {
893 return klass->ProxyDescriptorEquals(match);
894 } else {
895 const DexFile& dex_file = klass->GetDexFile();
896 const dex::TypeId& type_id = dex_file.GetTypeId(klass->GetDexTypeIndex());
897 return strcmp(dex_file.GetTypeDescriptor(type_id), match) == 0;
898 }
899 }
900
DescriptorHash()901 inline uint32_t Class::DescriptorHash() {
902 // No read barriers needed, we're reading a chain of constant references for comparison with null
903 // and retrieval of constant primitive data. See `ReadBarrierOption` and `Class::GetDescriptor()`.
904 ObjPtr<mirror::Class> klass = this;
905 uint32_t hash = StartModifiedUtf8Hash();
906 while (klass->IsArrayClass()) {
907 klass = klass->GetComponentType<kDefaultVerifyFlags, kWithoutReadBarrier>();
908 hash = UpdateModifiedUtf8Hash(hash, '[');
909 }
910 if (UNLIKELY(klass->IsProxyClass())) {
911 hash = UpdateHashForProxyClass(hash, klass);
912 } else if (klass->IsPrimitive()) {
913 hash = UpdateModifiedUtf8Hash(hash, Primitive::Descriptor(klass->GetPrimitiveType())[0]);
914 } else {
915 const DexFile& dex_file = klass->GetDexFile();
916 const dex::TypeId& type_id = dex_file.GetTypeId(klass->GetDexTypeIndex());
917 std::string_view descriptor = dex_file.GetTypeDescriptorView(type_id);
918 hash = UpdateModifiedUtf8Hash(hash, descriptor);
919 }
920
921 if (kIsDebugBuild) {
922 std::string temp;
923 CHECK_EQ(hash, ComputeModifiedUtf8Hash(GetDescriptor(&temp)));
924 }
925
926 return hash;
927 }
928
AssertInitializedOrInitializingInThread(Thread * self)929 inline void Class::AssertInitializedOrInitializingInThread(Thread* self) {
930 if (kIsDebugBuild && !IsInitialized()) {
931 CHECK(IsInitializing()) << PrettyClass() << " is not initializing: " << GetStatus();
932 CHECK_EQ(GetClinitThreadId(), self->GetTid())
933 << PrettyClass() << " is initializing in a different thread";
934 }
935 }
936
GetProxyInterfaces()937 inline ObjPtr<ObjectArray<Class>> Class::GetProxyInterfaces() {
938 CHECK(IsProxyClass());
939 // First static field.
940 ArtField* field = GetStaticField(0);
941 DCHECK_STREQ(field->GetName(), "interfaces");
942 MemberOffset field_offset = field->GetOffset();
943 return GetFieldObject<ObjectArray<Class>>(field_offset);
944 }
945
GetProxyThrows()946 inline ObjPtr<ObjectArray<ObjectArray<Class>>> Class::GetProxyThrows() {
947 CHECK(IsProxyClass());
948 // Second static field.
949 ArtField* field = GetStaticField(1);
950 DCHECK_STREQ(field->GetName(), "throws");
951 MemberOffset field_offset = field->GetOffset();
952 return GetFieldObject<ObjectArray<ObjectArray<Class>>>(field_offset);
953 }
954
IsBootStrapClassLoaded()955 inline bool Class::IsBootStrapClassLoaded() {
956 // No read barrier is needed for comparing with null. See ReadBarrierOption.
957 return GetClassLoader<kDefaultVerifyFlags, kWithoutReadBarrier>() == nullptr;
958 }
959
operator()960 inline void Class::InitializeClassVisitor::operator()(ObjPtr<Object> obj,
961 size_t usable_size) const {
962 DCHECK_LE(class_size_, usable_size);
963 // Avoid AsClass as object is not yet in live bitmap or allocation stack.
964 ObjPtr<Class> klass = ObjPtr<Class>::DownCast(obj);
965 klass->SetClassSize(class_size_);
966 klass->SetPrimitiveType(Primitive::kPrimNot); // Default to not being primitive.
967 klass->SetDexClassDefIndex(DexFile::kDexNoIndex16); // Default to no valid class def index.
968 klass->SetDexTypeIndex(dex::TypeIndex(DexFile::kDexNoIndex16)); // Default to no valid type
969 // index.
970 // Default to force slow path until visibly initialized.
971 // There is no need for release store (volatile) in pre-fence visitor.
972 klass->SetField32</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
973 ObjectSizeAllocFastPathOffset(), std::numeric_limits<uint32_t>::max());
974 }
975
SetAccessFlagsDuringLinking(uint32_t new_access_flags)976 inline void Class::SetAccessFlagsDuringLinking(uint32_t new_access_flags) {
977 SetField32</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
978 AccessFlagsOffset(), new_access_flags);
979 }
980
SetAccessFlags(uint32_t new_access_flags)981 inline void Class::SetAccessFlags(uint32_t new_access_flags) {
982 // Called inside a transaction when setting pre-verified flag during boot image compilation.
983 if (Runtime::Current()->IsActiveTransaction()) {
984 SetField32<true>(AccessFlagsOffset(), new_access_flags);
985 } else {
986 SetField32<false>(AccessFlagsOffset(), new_access_flags);
987 }
988 }
989
SetClassFlags(uint32_t new_flags)990 inline void Class::SetClassFlags(uint32_t new_flags) {
991 SetField32</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
992 OFFSET_OF_OBJECT_MEMBER(Class, class_flags_), new_flags);
993 }
994
NumDirectInterfaces()995 inline uint32_t Class::NumDirectInterfaces() {
996 if (IsPrimitive()) {
997 return 0;
998 } else if (IsArrayClass()) {
999 return 2;
1000 } else if (IsProxyClass()) {
1001 ObjPtr<ObjectArray<Class>> interfaces = GetProxyInterfaces();
1002 return interfaces != nullptr ? interfaces->GetLength() : 0;
1003 } else {
1004 const dex::TypeList* interfaces = GetInterfaceTypeList();
1005 if (interfaces == nullptr) {
1006 return 0;
1007 } else {
1008 return interfaces->Size();
1009 }
1010 }
1011 }
1012
GetDirectMethods(PointerSize pointer_size)1013 inline ArraySlice<ArtMethod> Class::GetDirectMethods(PointerSize pointer_size) {
1014 CheckPointerSize(pointer_size);
1015 return GetDirectMethodsSliceUnchecked(pointer_size);
1016 }
1017
GetDeclaredMethods(PointerSize pointer_size)1018 inline ArraySlice<ArtMethod> Class::GetDeclaredMethods(PointerSize pointer_size) {
1019 return GetDeclaredMethodsSliceUnchecked(pointer_size);
1020 }
1021
GetDeclaredVirtualMethods(PointerSize pointer_size)1022 inline ArraySlice<ArtMethod> Class::GetDeclaredVirtualMethods(PointerSize pointer_size) {
1023 return GetDeclaredVirtualMethodsSliceUnchecked(pointer_size);
1024 }
1025
GetVirtualMethods(PointerSize pointer_size)1026 inline ArraySlice<ArtMethod> Class::GetVirtualMethods(PointerSize pointer_size) {
1027 CheckPointerSize(pointer_size);
1028 return GetVirtualMethodsSliceUnchecked(pointer_size);
1029 }
1030
GetCopiedMethods(PointerSize pointer_size)1031 inline ArraySlice<ArtMethod> Class::GetCopiedMethods(PointerSize pointer_size) {
1032 CheckPointerSize(pointer_size);
1033 return GetCopiedMethodsSliceUnchecked(pointer_size);
1034 }
1035
1036
GetMethods(PointerSize pointer_size)1037 inline ArraySlice<ArtMethod> Class::GetMethods(PointerSize pointer_size) {
1038 CheckPointerSize(pointer_size);
1039 LengthPrefixedArray<ArtMethod>* methods = GetMethodsPtr();
1040 return GetMethodsSliceRangeUnchecked(methods, pointer_size, 0u, NumMethods(methods));
1041 }
1042
GetIFields()1043 inline IterationRange<StrideIterator<ArtField>> Class::GetIFields() {
1044 return MakeIterationRangeFromLengthPrefixedArray(GetIFieldsPtr());
1045 }
1046
GetSFields()1047 inline IterationRange<StrideIterator<ArtField>> Class::GetSFields() {
1048 return MakeIterationRangeFromLengthPrefixedArray(GetSFieldsPtr());
1049 }
1050
GetIFieldsUnchecked()1051 inline IterationRange<StrideIterator<ArtField>> Class::GetIFieldsUnchecked() {
1052 return MakeIterationRangeFromLengthPrefixedArray(GetIFieldsPtrUnchecked());
1053 }
1054
GetSFieldsUnchecked()1055 inline IterationRange<StrideIterator<ArtField>> Class::GetSFieldsUnchecked() {
1056 return MakeIterationRangeFromLengthPrefixedArray(GetSFieldsPtrUnchecked());
1057 }
1058
CheckPointerSize(PointerSize pointer_size)1059 inline void Class::CheckPointerSize(PointerSize pointer_size) {
1060 DCHECK_EQ(pointer_size, Runtime::Current()->GetClassLinker()->GetImagePointerSize());
1061 }
1062
1063 template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
GetComponentType()1064 inline ObjPtr<Class> Class::GetComponentType() {
1065 return GetFieldObject<Class, kVerifyFlags, kReadBarrierOption>(ComponentTypeOffset());
1066 }
1067
SetComponentType(ObjPtr<Class> new_component_type)1068 inline void Class::SetComponentType(ObjPtr<Class> new_component_type) {
1069 DCHECK(GetComponentType() == nullptr);
1070 DCHECK(new_component_type != nullptr);
1071 // Component type is invariant: use non-transactional mode without check.
1072 SetFieldObject</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
1073 ComponentTypeOffset(), new_component_type);
1074 }
1075
GetComponentSize()1076 inline size_t Class::GetComponentSize() {
1077 return 1U << GetComponentSizeShift();
1078 }
1079
GetComponentSizeShift()1080 inline size_t Class::GetComponentSizeShift() {
1081 // No read barrier is needed for reading a constant primitive field through
1082 // constant reference field. See ReadBarrierOption.
1083 return GetComponentType<kDefaultVerifyFlags, kWithoutReadBarrier>()->GetPrimitiveTypeSizeShift();
1084 }
1085
IsObjectClass()1086 inline bool Class::IsObjectClass() {
1087 // No read barrier is needed for comparing with null. See ReadBarrierOption.
1088 return !IsPrimitive() && GetSuperClass<kDefaultVerifyFlags, kWithoutReadBarrier>() == nullptr;
1089 }
1090
IsInstantiableNonArray()1091 inline bool Class::IsInstantiableNonArray() {
1092 return !IsPrimitive() && !IsInterface() && !IsAbstract() && !IsArrayClass();
1093 }
1094
1095 template<VerifyObjectFlags kVerifyFlags>
IsInstantiable()1096 bool Class::IsInstantiable() {
1097 return (!IsPrimitive<kVerifyFlags>() &&
1098 !IsInterface<kVerifyFlags>() &&
1099 !IsAbstract<kVerifyFlags>()) ||
1100 (IsAbstract<kVerifyFlags>() && IsArrayClass<kVerifyFlags>());
1101 }
1102
1103 template<VerifyObjectFlags kVerifyFlags>
IsArrayClass()1104 inline bool Class::IsArrayClass() {
1105 // We do not need a read barrier for comparing with null.
1106 return GetComponentType<kVerifyFlags, kWithoutReadBarrier>() != nullptr;
1107 }
1108
1109 template<VerifyObjectFlags kVerifyFlags>
IsObjectArrayClass()1110 inline bool Class::IsObjectArrayClass() {
1111 // We do not need a read barrier here as the primitive type is constant,
1112 // both from-space and to-space component type classes shall yield the same result.
1113 const ObjPtr<Class> component_type = GetComponentType<kVerifyFlags, kWithoutReadBarrier>();
1114 constexpr VerifyObjectFlags kNewFlags = RemoveThisFlags(kVerifyFlags);
1115 return component_type != nullptr && !component_type->IsPrimitive<kNewFlags>();
1116 }
1117
1118 template<VerifyObjectFlags kVerifyFlags>
IsPrimitiveArray()1119 bool Class::IsPrimitiveArray() {
1120 // We do not need a read barrier here as the primitive type is constant,
1121 // both from-space and to-space component type classes shall yield the same result.
1122 const ObjPtr<Class> component_type = GetComponentType<kVerifyFlags, kWithoutReadBarrier>();
1123 constexpr VerifyObjectFlags kNewFlags = RemoveThisFlags(kVerifyFlags);
1124 return component_type != nullptr && component_type->IsPrimitive<kNewFlags>();
1125 }
1126
IsAssignableFrom(ObjPtr<Class> src)1127 inline bool Class::IsAssignableFrom(ObjPtr<Class> src) {
1128 DCHECK(src != nullptr);
1129 if (this == src) {
1130 // Can always assign to things of the same type.
1131 return true;
1132 } else if (IsObjectClass()) {
1133 // Can assign any reference to java.lang.Object.
1134 return !src->IsPrimitive();
1135 } else if (IsInterface()) {
1136 return src->Implements(this);
1137 } else if (src->IsArrayClass()) {
1138 return IsAssignableFromArray(src);
1139 } else {
1140 return !src->IsInterface() && src->IsSubClass(this);
1141 }
1142 }
1143
NumDirectMethods()1144 inline uint32_t Class::NumDirectMethods() {
1145 return GetVirtualMethodsStartOffset();
1146 }
1147
NumDeclaredVirtualMethods()1148 inline uint32_t Class::NumDeclaredVirtualMethods() {
1149 return GetCopiedMethodsStartOffset() - GetVirtualMethodsStartOffset();
1150 }
1151
NumVirtualMethods()1152 inline uint32_t Class::NumVirtualMethods() {
1153 return NumMethods() - GetVirtualMethodsStartOffset();
1154 }
1155
NumInstanceFields()1156 inline uint32_t Class::NumInstanceFields() {
1157 LengthPrefixedArray<ArtField>* arr = GetIFieldsPtrUnchecked();
1158 return arr != nullptr ? arr->size() : 0u;
1159 }
1160
NumStaticFields()1161 inline uint32_t Class::NumStaticFields() {
1162 LengthPrefixedArray<ArtField>* arr = GetSFieldsPtrUnchecked();
1163 return arr != nullptr ? arr->size() : 0u;
1164 }
1165
1166 template <typename T, VerifyObjectFlags kVerifyFlags, typename Visitor>
FixupNativePointer(Class * dest,PointerSize pointer_size,const Visitor & visitor,MemberOffset member_offset)1167 inline void Class::FixupNativePointer(
1168 Class* dest, PointerSize pointer_size, const Visitor& visitor, MemberOffset member_offset) {
1169 void** address =
1170 reinterpret_cast<void**>(reinterpret_cast<uintptr_t>(dest) + member_offset.Uint32Value());
1171 T old_value = GetFieldPtrWithSize<T, kVerifyFlags>(member_offset, pointer_size);
1172 T new_value = visitor(old_value, address);
1173 if (old_value != new_value) {
1174 dest->SetFieldPtrWithSize</* kTransactionActive= */ false,
1175 /* kCheckTransaction= */ true,
1176 kVerifyNone>(member_offset, new_value, pointer_size);
1177 }
1178 }
1179
1180 template <VerifyObjectFlags kVerifyFlags, typename Visitor>
FixupNativePointers(Class * dest,PointerSize pointer_size,const Visitor & visitor)1181 inline void Class::FixupNativePointers(Class* dest,
1182 PointerSize pointer_size,
1183 const Visitor& visitor) {
1184 // Update the field arrays.
1185 FixupNativePointer<LengthPrefixedArray<ArtField>*, kVerifyFlags>(
1186 dest, pointer_size, visitor, OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
1187 FixupNativePointer<LengthPrefixedArray<ArtField>*, kVerifyFlags>(
1188 dest, pointer_size, visitor, OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
1189 // Update method array.
1190 FixupNativePointer<LengthPrefixedArray<ArtMethod>*, kVerifyFlags>(
1191 dest, pointer_size, visitor, OFFSET_OF_OBJECT_MEMBER(Class, methods_));
1192 // Fix up embedded tables.
1193 if (!IsTemp<kVerifyNone>() && ShouldHaveEmbeddedVTable<kVerifyNone>()) {
1194 for (int32_t i = 0, count = GetEmbeddedVTableLength<kVerifyFlags>(); i < count; ++i) {
1195 FixupNativePointer<ArtMethod*, kVerifyFlags>(
1196 dest, pointer_size, visitor, EmbeddedVTableEntryOffset(i, pointer_size));
1197 }
1198 }
1199 if (!IsTemp<kVerifyNone>() && ShouldHaveImt<kVerifyNone>()) {
1200 FixupNativePointer<ImTable*, kVerifyFlags>(
1201 dest, pointer_size, visitor, ImtPtrOffset(pointer_size));
1202 }
1203 }
1204
CanAccess(ObjPtr<Class> that)1205 inline bool Class::CanAccess(ObjPtr<Class> that) {
1206 return that->IsPublic() || this->IsInSamePackage(that);
1207 }
1208
1209
CanAccessMember(ObjPtr<Class> access_to,uint32_t member_flags)1210 inline bool Class::CanAccessMember(ObjPtr<Class> access_to, uint32_t member_flags) {
1211 // Classes can access all of their own members
1212 if (this == access_to) {
1213 return true;
1214 }
1215 // Public members are trivially accessible
1216 if (member_flags & kAccPublic) {
1217 return true;
1218 }
1219 // Private members are trivially not accessible
1220 if (member_flags & kAccPrivate) {
1221 return false;
1222 }
1223 // Check for protected access from a sub-class, which may or may not be in the same package.
1224 if (member_flags & kAccProtected) {
1225 if (!this->IsInterface() && this->IsSubClass(access_to)) {
1226 return true;
1227 }
1228 }
1229 // Allow protected access from other classes in the same package.
1230 return this->IsInSamePackage(access_to);
1231 }
1232
CannotBeAssignedFromOtherTypes()1233 inline bool Class::CannotBeAssignedFromOtherTypes() {
1234 if (!IsArrayClass()) {
1235 return IsFinal();
1236 }
1237 ObjPtr<Class> component = GetComponentType();
1238 return component->IsPrimitive() || component->CannotBeAssignedFromOtherTypes();
1239 }
1240
SetClassLoader(ObjPtr<ClassLoader> new_class_loader)1241 inline void Class::SetClassLoader(ObjPtr<ClassLoader> new_class_loader) {
1242 SetFieldObject</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
1243 OFFSET_OF_OBJECT_MEMBER(Class, class_loader_), new_class_loader);
1244 }
1245
SetRecursivelyInitialized()1246 inline void Class::SetRecursivelyInitialized() {
1247 DCHECK_EQ(GetLockOwnerThreadId(), Thread::Current()->GetThreadId());
1248 uint32_t flags = GetField32(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_));
1249 SetAccessFlags(flags | kAccRecursivelyInitialized);
1250 }
1251
SetHasDefaultMethods()1252 inline void Class::SetHasDefaultMethods() {
1253 DCHECK_EQ(GetLockOwnerThreadId(), Thread::Current()->GetThreadId());
1254 uint32_t flags = GetField32(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_));
1255 SetAccessFlagsDuringLinking(flags | kAccHasDefaultMethod);
1256 }
1257
1258 } // namespace mirror
1259 } // namespace art
1260
1261 #endif // ART_RUNTIME_MIRROR_CLASS_INL_H_
1262