class-inl.h revision f4c15a18eb055735857a280856be5b142e0c1113
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ART_RUNTIME_MIRROR_CLASS_INL_H_
18#define ART_RUNTIME_MIRROR_CLASS_INL_H_
19
20#include "class.h"
21
22#include "art_field-inl.h"
23#include "art_method-inl.h"
24#include "class_linker-inl.h"
25#include "class_loader.h"
26#include "common_throws.h"
27#include "dex_cache.h"
28#include "dex_file.h"
29#include "gc/heap-inl.h"
30#include "iftable.h"
31#include "object_array-inl.h"
32#include "read_barrier-inl.h"
33#include "reference-inl.h"
34#include "runtime.h"
35#include "string.h"
36
37namespace art {
38namespace mirror {
39
40template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
41inline uint32_t Class::GetObjectSize() {
42  if (kIsDebugBuild) {
43    // Use a local variable as (D)CHECK can't handle the space between
44    // the two template params.
45    bool is_variable_size = IsVariableSize<kVerifyFlags, kReadBarrierOption>();
46    CHECK(!is_variable_size) << " class=" << PrettyTypeOf(this);
47  }
48  return GetField32(OFFSET_OF_OBJECT_MEMBER(Class, object_size_));
49}
50
51inline Class* Class::GetSuperClass() {
52  // Can only get super class for loaded classes (hack for when runtime is
53  // initializing)
54  DCHECK(IsLoaded() || IsErroneous() || !Runtime::Current()->IsStarted()) << IsLoaded();
55  return GetFieldObject<Class>(OFFSET_OF_OBJECT_MEMBER(Class, super_class_));
56}
57
58inline ClassLoader* Class::GetClassLoader() {
59  return GetFieldObject<ClassLoader>(OFFSET_OF_OBJECT_MEMBER(Class, class_loader_));
60}
61
62template<VerifyObjectFlags kVerifyFlags>
63inline DexCache* Class::GetDexCache() {
64  return GetFieldObject<DexCache, kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_));
65}
66
67inline ObjectArray<ArtMethod>* Class::GetDirectMethods() {
68  DCHECK(IsLoaded() || IsErroneous());
69  return GetFieldObject<ObjectArray<ArtMethod>>(OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_));
70}
71
72inline void Class::SetDirectMethods(ObjectArray<ArtMethod>* new_direct_methods)
73    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
74  DCHECK(NULL == GetFieldObject<ObjectArray<ArtMethod>>(
75      OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_)));
76  DCHECK_NE(0, new_direct_methods->GetLength());
77  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_), new_direct_methods);
78}
79
80inline ArtMethod* Class::GetDirectMethod(int32_t i) {
81  return GetDirectMethods()->Get(i);
82}
83
84inline void Class::SetDirectMethod(uint32_t i, ArtMethod* f)  // TODO: uint16_t
85    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
86  ObjectArray<ArtMethod>* direct_methods =
87      GetFieldObject<ObjectArray<ArtMethod>>(OFFSET_OF_OBJECT_MEMBER(Class, direct_methods_));
88  direct_methods->Set<false>(i, f);
89}
90
91// Returns the number of static, private, and constructor methods.
92inline uint32_t Class::NumDirectMethods() {
93  return (GetDirectMethods() != NULL) ? GetDirectMethods()->GetLength() : 0;
94}
95
96template<VerifyObjectFlags kVerifyFlags>
97inline ObjectArray<ArtMethod>* Class::GetVirtualMethods() {
98  DCHECK(IsLoaded() || IsErroneous());
99  return GetFieldObject<ObjectArray<ArtMethod>>(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_));
100}
101
102inline void Class::SetVirtualMethods(ObjectArray<ArtMethod>* new_virtual_methods) {
103  // TODO: we reassign virtual methods to grow the table for miranda
104  // methods.. they should really just be assigned once.
105  DCHECK_NE(0, new_virtual_methods->GetLength());
106  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_), new_virtual_methods);
107}
108
109inline uint32_t Class::NumVirtualMethods() {
110  return (GetVirtualMethods() != NULL) ? GetVirtualMethods()->GetLength() : 0;
111}
112
113template<VerifyObjectFlags kVerifyFlags>
114inline ArtMethod* Class::GetVirtualMethod(uint32_t i) {
115  DCHECK(IsResolved<kVerifyFlags>() || IsErroneous<kVerifyFlags>())
116      << PrettyClass(this) << " status=" << GetStatus();
117  return GetVirtualMethods()->Get(i);
118}
119
120inline ArtMethod* Class::GetVirtualMethodDuringLinking(uint32_t i) {
121  DCHECK(IsLoaded() || IsErroneous());
122  return GetVirtualMethods()->Get(i);
123}
124
125inline void Class::SetVirtualMethod(uint32_t i, ArtMethod* f)  // TODO: uint16_t
126    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
127  ObjectArray<ArtMethod>* virtual_methods =
128      GetFieldObject<ObjectArray<ArtMethod>>(OFFSET_OF_OBJECT_MEMBER(Class, virtual_methods_));
129  virtual_methods->Set<false>(i, f);
130}
131
132inline ObjectArray<ArtMethod>* Class::GetVTable() {
133  DCHECK(IsResolved() || IsErroneous());
134  return GetFieldObject<ObjectArray<ArtMethod>>(OFFSET_OF_OBJECT_MEMBER(Class, vtable_));
135}
136
137inline ObjectArray<ArtMethod>* Class::GetVTableDuringLinking() {
138  DCHECK(IsLoaded() || IsErroneous());
139  return GetFieldObject<ObjectArray<ArtMethod>>(OFFSET_OF_OBJECT_MEMBER(Class, vtable_));
140}
141
142inline void Class::SetVTable(ObjectArray<ArtMethod>* new_vtable) {
143  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, vtable_), new_vtable);
144}
145
146inline ObjectArray<ArtMethod>* Class::GetImTable() {
147  return GetFieldObject<ObjectArray<ArtMethod>>(OFFSET_OF_OBJECT_MEMBER(Class, imtable_));
148}
149
150inline void Class::SetImTable(ObjectArray<ArtMethod>* new_imtable) {
151  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, imtable_), new_imtable);
152}
153
154inline ArtMethod* Class::GetEmbeddedImTableEntry(uint32_t i) {
155  uint32_t offset = EmbeddedImTableOffset().Uint32Value() + i * sizeof(ImTableEntry);
156  return GetFieldObject<mirror::ArtMethod>(MemberOffset(offset));
157}
158
159inline void Class::SetEmbeddedImTableEntry(uint32_t i, ArtMethod* method) {
160  uint32_t offset = EmbeddedImTableOffset().Uint32Value() + i * sizeof(ImTableEntry);
161  SetFieldObject<false>(MemberOffset(offset), method);
162  CHECK(method == GetImTable()->Get(i));
163}
164
165inline bool Class::HasVTable() {
166  return (GetVTable() != nullptr) || ShouldHaveEmbeddedImtAndVTable();
167}
168
169inline int32_t Class::GetVTableLength() {
170  if (ShouldHaveEmbeddedImtAndVTable()) {
171    return GetEmbeddedVTableLength();
172  }
173  return (GetVTable() != nullptr) ? GetVTable()->GetLength() : 0;
174}
175
176inline ArtMethod* Class::GetVTableEntry(uint32_t i) {
177  if (ShouldHaveEmbeddedImtAndVTable()) {
178    return GetEmbeddedVTableEntry(i);
179  }
180  return (GetVTable() != nullptr) ? GetVTable()->Get(i) : nullptr;
181}
182
183inline int32_t Class::GetEmbeddedVTableLength() {
184  return GetField32(EmbeddedVTableLengthOffset());
185}
186
187inline void Class::SetEmbeddedVTableLength(int32_t len) {
188  SetField32<false>(EmbeddedVTableLengthOffset(), len);
189}
190
191inline ArtMethod* Class::GetEmbeddedVTableEntry(uint32_t i) {
192  uint32_t offset = EmbeddedVTableOffset().Uint32Value() + i * sizeof(VTableEntry);
193  return GetFieldObject<mirror::ArtMethod>(MemberOffset(offset));
194}
195
196inline void Class::SetEmbeddedVTableEntry(uint32_t i, ArtMethod* method) {
197  uint32_t offset = EmbeddedVTableOffset().Uint32Value() + i * sizeof(VTableEntry);
198  SetFieldObject<false>(MemberOffset(offset), method);
199  CHECK(method == GetVTableDuringLinking()->Get(i));
200}
201
202inline bool Class::Implements(Class* klass) {
203  DCHECK(klass != NULL);
204  DCHECK(klass->IsInterface()) << PrettyClass(this);
205  // All interfaces implemented directly and by our superclass, and
206  // recursively all super-interfaces of those interfaces, are listed
207  // in iftable_, so we can just do a linear scan through that.
208  int32_t iftable_count = GetIfTableCount();
209  IfTable* iftable = GetIfTable();
210  for (int32_t i = 0; i < iftable_count; i++) {
211    if (iftable->GetInterface(i) == klass) {
212      return true;
213    }
214  }
215  return false;
216}
217
218// Determine whether "this" is assignable from "src", where both of these
219// are array classes.
220//
221// Consider an array class, e.g. Y[][], where Y is a subclass of X.
222//   Y[][]            = Y[][] --> true (identity)
223//   X[][]            = Y[][] --> true (element superclass)
224//   Y                = Y[][] --> false
225//   Y[]              = Y[][] --> false
226//   Object           = Y[][] --> true (everything is an object)
227//   Object[]         = Y[][] --> true
228//   Object[][]       = Y[][] --> true
229//   Object[][][]     = Y[][] --> false (too many []s)
230//   Serializable     = Y[][] --> true (all arrays are Serializable)
231//   Serializable[]   = Y[][] --> true
232//   Serializable[][] = Y[][] --> false (unless Y is Serializable)
233//
234// Don't forget about primitive types.
235//   Object[]         = int[] --> false
236//
237inline bool Class::IsArrayAssignableFromArray(Class* src) {
238  DCHECK(IsArrayClass())  << PrettyClass(this);
239  DCHECK(src->IsArrayClass()) << PrettyClass(src);
240  return GetComponentType()->IsAssignableFrom(src->GetComponentType());
241}
242
243inline bool Class::IsAssignableFromArray(Class* src) {
244  DCHECK(!IsInterface()) << PrettyClass(this);  // handled first in IsAssignableFrom
245  DCHECK(src->IsArrayClass()) << PrettyClass(src);
246  if (!IsArrayClass()) {
247    // If "this" is not also an array, it must be Object.
248    // src's super should be java_lang_Object, since it is an array.
249    Class* java_lang_Object = src->GetSuperClass();
250    DCHECK(java_lang_Object != NULL) << PrettyClass(src);
251    DCHECK(java_lang_Object->GetSuperClass() == NULL) << PrettyClass(src);
252    return this == java_lang_Object;
253  }
254  return IsArrayAssignableFromArray(src);
255}
256
257template <bool throw_on_failure, bool use_referrers_cache>
258inline bool Class::ResolvedFieldAccessTest(Class* access_to, ArtField* field,
259                                           uint32_t field_idx, DexCache* dex_cache) {
260  DCHECK_EQ(use_referrers_cache, dex_cache == nullptr);
261  if (UNLIKELY(!this->CanAccess(access_to))) {
262    // The referrer class can't access the field's declaring class but may still be able
263    // to access the field if the FieldId specifies an accessible subclass of the declaring
264    // class rather than the declaring class itself.
265    DexCache* referrer_dex_cache = use_referrers_cache ? this->GetDexCache() : dex_cache;
266    uint32_t class_idx = referrer_dex_cache->GetDexFile()->GetFieldId(field_idx).class_idx_;
267    // The referenced class has already been resolved with the field, get it from the dex cache.
268    Class* dex_access_to = referrer_dex_cache->GetResolvedType(class_idx);
269    DCHECK(dex_access_to != nullptr);
270    if (UNLIKELY(!this->CanAccess(dex_access_to))) {
271      if (throw_on_failure) {
272        ThrowIllegalAccessErrorClass(this, dex_access_to);
273      }
274      return false;
275    }
276    DCHECK_EQ(this->CanAccessMember(access_to, field->GetAccessFlags()),
277              this->CanAccessMember(dex_access_to, field->GetAccessFlags()));
278  }
279  if (LIKELY(this->CanAccessMember(access_to, field->GetAccessFlags()))) {
280    return true;
281  }
282  if (throw_on_failure) {
283    ThrowIllegalAccessErrorField(this, field);
284  }
285  return false;
286}
287
288template <bool throw_on_failure, bool use_referrers_cache, InvokeType throw_invoke_type>
289inline bool Class::ResolvedMethodAccessTest(Class* access_to, ArtMethod* method,
290                                            uint32_t method_idx, DexCache* dex_cache) {
291  COMPILE_ASSERT(throw_on_failure || throw_invoke_type == kStatic, non_default_throw_invoke_type);
292  DCHECK_EQ(use_referrers_cache, dex_cache == nullptr);
293  if (UNLIKELY(!this->CanAccess(access_to))) {
294    // The referrer class can't access the method's declaring class but may still be able
295    // to access the method if the MethodId specifies an accessible subclass of the declaring
296    // class rather than the declaring class itself.
297    DexCache* referrer_dex_cache = use_referrers_cache ? this->GetDexCache() : dex_cache;
298    uint32_t class_idx = referrer_dex_cache->GetDexFile()->GetMethodId(method_idx).class_idx_;
299    // The referenced class has already been resolved with the method, get it from the dex cache.
300    Class* dex_access_to = referrer_dex_cache->GetResolvedType(class_idx);
301    DCHECK(dex_access_to != nullptr);
302    if (UNLIKELY(!this->CanAccess(dex_access_to))) {
303      if (throw_on_failure) {
304        ThrowIllegalAccessErrorClassForMethodDispatch(this, dex_access_to,
305                                                      method, throw_invoke_type);
306      }
307      return false;
308    }
309    DCHECK_EQ(this->CanAccessMember(access_to, method->GetAccessFlags()),
310              this->CanAccessMember(dex_access_to, method->GetAccessFlags()));
311  }
312  if (LIKELY(this->CanAccessMember(access_to, method->GetAccessFlags()))) {
313    return true;
314  }
315  if (throw_on_failure) {
316    ThrowIllegalAccessErrorMethod(this, method);
317  }
318  return false;
319}
320
321inline bool Class::CanAccessResolvedField(Class* access_to, ArtField* field,
322                                          DexCache* dex_cache, uint32_t field_idx) {
323  return ResolvedFieldAccessTest<false, false>(access_to, field, field_idx, dex_cache);
324}
325
326inline bool Class::CheckResolvedFieldAccess(Class* access_to, ArtField* field,
327                                            uint32_t field_idx) {
328  return ResolvedFieldAccessTest<true, true>(access_to, field, field_idx, nullptr);
329}
330
331inline bool Class::CanAccessResolvedMethod(Class* access_to, ArtMethod* method,
332                                           DexCache* dex_cache, uint32_t method_idx) {
333  return ResolvedMethodAccessTest<false, false, kStatic>(access_to, method, method_idx, dex_cache);
334}
335
336template <InvokeType throw_invoke_type>
337inline bool Class::CheckResolvedMethodAccess(Class* access_to, ArtMethod* method,
338                                             uint32_t method_idx) {
339  return ResolvedMethodAccessTest<true, true, throw_invoke_type>(access_to, method, method_idx,
340                                                                 nullptr);
341}
342
343inline bool Class::IsSubClass(Class* klass) {
344  DCHECK(!IsInterface()) << PrettyClass(this);
345  DCHECK(!IsArrayClass()) << PrettyClass(this);
346  Class* current = this;
347  do {
348    if (current == klass) {
349      return true;
350    }
351    current = current->GetSuperClass();
352  } while (current != NULL);
353  return false;
354}
355
356inline ArtMethod* Class::FindVirtualMethodForInterface(ArtMethod* method) {
357  Class* declaring_class = method->GetDeclaringClass();
358  DCHECK(declaring_class != NULL) << PrettyClass(this);
359  DCHECK(declaring_class->IsInterface()) << PrettyMethod(method);
360  // TODO cache to improve lookup speed
361  int32_t iftable_count = GetIfTableCount();
362  IfTable* iftable = GetIfTable();
363  for (int32_t i = 0; i < iftable_count; i++) {
364    if (iftable->GetInterface(i) == declaring_class) {
365      return iftable->GetMethodArray(i)->Get(method->GetMethodIndex());
366    }
367  }
368  return NULL;
369}
370
371inline ArtMethod* Class::FindVirtualMethodForVirtual(ArtMethod* method) {
372  DCHECK(!method->GetDeclaringClass()->IsInterface() || method->IsMiranda());
373  // The argument method may from a super class.
374  // Use the index to a potentially overridden one for this instance's class.
375  return GetVTableEntry(method->GetMethodIndex());
376}
377
378inline ArtMethod* Class::FindVirtualMethodForSuper(ArtMethod* method) {
379  DCHECK(!method->GetDeclaringClass()->IsInterface());
380  return GetSuperClass()->GetVTableEntry(method->GetMethodIndex());
381}
382
383inline ArtMethod* Class::FindVirtualMethodForVirtualOrInterface(ArtMethod* method) {
384  if (method->IsDirect()) {
385    return method;
386  }
387  if (method->GetDeclaringClass()->IsInterface() && !method->IsMiranda()) {
388    return FindVirtualMethodForInterface(method);
389  }
390  return FindVirtualMethodForVirtual(method);
391}
392
393inline IfTable* Class::GetIfTable() {
394  return GetFieldObject<IfTable>(OFFSET_OF_OBJECT_MEMBER(Class, iftable_));
395}
396
397inline int32_t Class::GetIfTableCount() {
398  IfTable* iftable = GetIfTable();
399  if (iftable == NULL) {
400    return 0;
401  }
402  return iftable->Count();
403}
404
405inline void Class::SetIfTable(IfTable* new_iftable) {
406  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, iftable_), new_iftable);
407}
408
409inline ObjectArray<ArtField>* Class::GetIFields() {
410  DCHECK(IsLoaded() || IsErroneous());
411  return GetFieldObject<ObjectArray<ArtField>>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
412}
413
414inline void Class::SetIFields(ObjectArray<ArtField>* new_ifields)
415    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
416  DCHECK(NULL == GetFieldObject<ObjectArray<ArtField>>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_)));
417  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, ifields_), new_ifields);
418}
419
420inline ObjectArray<ArtField>* Class::GetSFields() {
421  DCHECK(IsLoaded() || IsErroneous());
422  return GetFieldObject<ObjectArray<ArtField>>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
423}
424
425inline void Class::SetSFields(ObjectArray<ArtField>* new_sfields)
426    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
427  DCHECK((IsRetired() && new_sfields == nullptr) ||
428         (NULL == GetFieldObject<ObjectArray<ArtField>>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_))));
429  SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, sfields_), new_sfields);
430}
431
432inline uint32_t Class::NumStaticFields() {
433  return (GetSFields() != NULL) ? GetSFields()->GetLength() : 0;
434}
435
436
437inline ArtField* Class::GetStaticField(uint32_t i)  // TODO: uint16_t
438    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
439  return GetSFields()->GetWithoutChecks(i);
440}
441
442inline void Class::SetStaticField(uint32_t i, ArtField* f)  // TODO: uint16_t
443    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
444  ObjectArray<ArtField>* sfields= GetFieldObject<ObjectArray<ArtField>>(
445      OFFSET_OF_OBJECT_MEMBER(Class, sfields_));
446  sfields->Set<false>(i, f);
447}
448
449inline uint32_t Class::NumInstanceFields() {
450  return (GetIFields() != NULL) ? GetIFields()->GetLength() : 0;
451}
452
453inline ArtField* Class::GetInstanceField(uint32_t i) {  // TODO: uint16_t
454  DCHECK_NE(NumInstanceFields(), 0U);
455  return GetIFields()->GetWithoutChecks(i);
456}
457
458inline void Class::SetInstanceField(uint32_t i, ArtField* f)  // TODO: uint16_t
459    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
460  ObjectArray<ArtField>* ifields= GetFieldObject<ObjectArray<ArtField>>(
461      OFFSET_OF_OBJECT_MEMBER(Class, ifields_));
462  ifields->Set<false>(i, f);
463}
464
465template<VerifyObjectFlags kVerifyFlags>
466inline uint32_t Class::GetReferenceInstanceOffsets() {
467  DCHECK(IsResolved<kVerifyFlags>() || IsErroneous<kVerifyFlags>());
468  return GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_));
469}
470
471inline void Class::SetClinitThreadId(pid_t new_clinit_thread_id) {
472  if (Runtime::Current()->IsActiveTransaction()) {
473    SetField32<true>(OFFSET_OF_OBJECT_MEMBER(Class, clinit_thread_id_), new_clinit_thread_id);
474  } else {
475    SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, clinit_thread_id_), new_clinit_thread_id);
476  }
477}
478
479inline void Class::SetVerifyErrorClass(Class* klass) {
480  CHECK(klass != NULL) << PrettyClass(this);
481  if (Runtime::Current()->IsActiveTransaction()) {
482    SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, verify_error_class_), klass);
483  } else {
484    SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, verify_error_class_), klass);
485  }
486}
487
488template<VerifyObjectFlags kVerifyFlags>
489inline uint32_t Class::GetAccessFlags() {
490  // Check class is loaded/retired or this is java.lang.String that has a
491  // circularity issue during loading the names of its members
492  DCHECK(IsIdxLoaded<kVerifyFlags>() || IsRetired<kVerifyFlags>() ||
493         IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>() ||
494         this == String::GetJavaLangString() ||
495         this == ArtField::GetJavaLangReflectArtField() ||
496         this == ArtMethod::GetJavaLangReflectArtMethod());
497  return GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_));
498}
499
500inline String* Class::GetName() {
501  return GetFieldObject<String>(OFFSET_OF_OBJECT_MEMBER(Class, name_));
502}
503inline void Class::SetName(String* name) {
504  if (Runtime::Current()->IsActiveTransaction()) {
505    SetFieldObject<true>(OFFSET_OF_OBJECT_MEMBER(Class, name_), name);
506  } else {
507    SetFieldObject<false>(OFFSET_OF_OBJECT_MEMBER(Class, name_), name);
508  }
509}
510
511template<VerifyObjectFlags kVerifyFlags>
512inline Primitive::Type Class::GetPrimitiveType() {
513  DCHECK_EQ(sizeof(Primitive::Type), sizeof(int32_t));
514  int32_t v32 = GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, primitive_type_));
515  Primitive::Type type = static_cast<Primitive::Type>(v32 & 0xFFFF);
516  DCHECK_EQ(static_cast<size_t>(v32 >> 16), Primitive::ComponentSizeShift(type));
517  return type;
518}
519
520template<VerifyObjectFlags kVerifyFlags>
521inline size_t Class::GetPrimitiveTypeSizeShift() {
522  DCHECK_EQ(sizeof(Primitive::Type), sizeof(int32_t));
523  int32_t v32 = GetField32<kVerifyFlags>(OFFSET_OF_OBJECT_MEMBER(Class, primitive_type_));
524  size_t size_shift = static_cast<Primitive::Type>(v32 >> 16);
525  DCHECK_EQ(size_shift, Primitive::ComponentSizeShift(static_cast<Primitive::Type>(v32 & 0xFFFF)));
526  return size_shift;
527}
528
529inline void Class::CheckObjectAlloc() {
530  DCHECK(!IsArrayClass())
531      << PrettyClass(this)
532      << "A array shouldn't be allocated through this "
533      << "as it requires a pre-fence visitor that sets the class size.";
534  DCHECK(!IsClassClass())
535      << PrettyClass(this)
536      << "A class object shouldn't be allocated through this "
537      << "as it requires a pre-fence visitor that sets the class size.";
538  DCHECK(IsInstantiable()) << PrettyClass(this);
539  // TODO: decide whether we want this check. It currently fails during bootstrap.
540  // DCHECK(!Runtime::Current()->IsStarted() || IsInitializing()) << PrettyClass(this);
541  DCHECK_GE(this->object_size_, sizeof(Object));
542}
543
544template<bool kIsInstrumented, bool kCheckAddFinalizer>
545inline Object* Class::Alloc(Thread* self, gc::AllocatorType allocator_type) {
546  CheckObjectAlloc();
547  gc::Heap* heap = Runtime::Current()->GetHeap();
548  const bool add_finalizer = kCheckAddFinalizer && IsFinalizable();
549  if (!kCheckAddFinalizer) {
550    DCHECK(!IsFinalizable());
551  }
552  mirror::Object* obj =
553      heap->AllocObjectWithAllocator<kIsInstrumented, false>(self, this, this->object_size_,
554                                                             allocator_type, VoidFunctor());
555  if (add_finalizer && LIKELY(obj != nullptr)) {
556    heap->AddFinalizerReference(self, &obj);
557  }
558  return obj;
559}
560
561inline Object* Class::AllocObject(Thread* self) {
562  return Alloc<true>(self, Runtime::Current()->GetHeap()->GetCurrentAllocator());
563}
564
565inline Object* Class::AllocNonMovableObject(Thread* self) {
566  return Alloc<true>(self, Runtime::Current()->GetHeap()->GetCurrentNonMovingAllocator());
567}
568
569inline uint32_t Class::ComputeClassSize(bool has_embedded_tables,
570                                        uint32_t num_vtable_entries,
571                                        uint32_t num_8bit_static_fields,
572                                        uint32_t num_16bit_static_fields,
573                                        uint32_t num_32bit_static_fields,
574                                        uint32_t num_64bit_static_fields,
575                                        uint32_t num_ref_static_fields) {
576  // Space used by java.lang.Class and its instance fields.
577  uint32_t size = sizeof(Class);
578  // Space used by embedded tables.
579  if (has_embedded_tables) {
580    uint32_t embedded_imt_size = kImtSize * sizeof(ImTableEntry);
581    uint32_t embedded_vtable_size = num_vtable_entries * sizeof(VTableEntry);
582    size += embedded_imt_size +
583            sizeof(int32_t) /* vtable len */ +
584            embedded_vtable_size;
585  }
586
587  // Space used by reference statics.
588  size +=  num_ref_static_fields * sizeof(HeapReference<Object>);
589  if (!IsAligned<8>(size) && num_64bit_static_fields > 0) {
590    uint32_t gap = 8 - (size & 0x7);
591    size += gap;  // will be padded
592    // Shuffle 4-byte fields forward.
593    while (gap >= sizeof(uint32_t) && num_32bit_static_fields != 0) {
594      --num_32bit_static_fields;
595      gap -= sizeof(uint32_t);
596    }
597    // Shuffle 2-byte fields forward.
598    while (gap >= sizeof(uint16_t) && num_16bit_static_fields != 0) {
599      --num_16bit_static_fields;
600      gap -= sizeof(uint16_t);
601    }
602    // Shuffle byte fields forward.
603    while (gap >= sizeof(uint8_t) && num_8bit_static_fields != 0) {
604      --num_8bit_static_fields;
605      gap -= sizeof(uint8_t);
606    }
607  }
608  // Guaranteed to be at least 4 byte aligned. No need for further alignments.
609  // Space used for primitive static fields.
610  size += (num_8bit_static_fields * sizeof(uint8_t)) +
611      (num_16bit_static_fields * sizeof(uint16_t)) +
612      (num_32bit_static_fields * sizeof(uint32_t)) +
613      (num_64bit_static_fields * sizeof(uint64_t));
614  return size;
615}
616
617template <bool kVisitClass, typename Visitor>
618inline void Class::VisitReferences(mirror::Class* klass, const Visitor& visitor) {
619  VisitInstanceFieldsReferences<kVisitClass>(klass, visitor);
620  if (!IsTemp() && IsResolved()) {
621    // Temp classes don't ever populate imt/vtable or static fields and they are not even
622    // allocated with the right size for those. Also, unresolved classes don't have fields
623    // linked yet.
624    VisitStaticFieldsReferences<kVisitClass>(this, visitor);
625    if (ShouldHaveEmbeddedImtAndVTable()) {
626      VisitEmbeddedImtAndVTable(visitor);
627    }
628  }
629}
630
631template<typename Visitor>
632inline void Class::VisitEmbeddedImtAndVTable(const Visitor& visitor) {
633  uint32_t pos = sizeof(mirror::Class);
634
635  size_t count = kImtSize;
636  for (size_t i = 0; i < count; ++i) {
637    MemberOffset offset = MemberOffset(pos);
638    visitor(this, offset, true);
639    pos += sizeof(ImTableEntry);
640  }
641
642  // Skip vtable length.
643  pos += sizeof(int32_t);
644
645  count = GetEmbeddedVTableLength();
646  for (size_t i = 0; i < count; ++i) {
647    MemberOffset offset = MemberOffset(pos);
648    visitor(this, offset, true);
649    pos += sizeof(VTableEntry);
650  }
651}
652
653template<ReadBarrierOption kReadBarrierOption>
654inline bool Class::IsArtFieldClass() const {
655  return this == ArtField::GetJavaLangReflectArtField<kReadBarrierOption>();
656}
657
658template<ReadBarrierOption kReadBarrierOption>
659inline bool Class::IsArtMethodClass() const {
660  return this == ArtMethod::GetJavaLangReflectArtMethod<kReadBarrierOption>();
661}
662
663template<ReadBarrierOption kReadBarrierOption>
664inline bool Class::IsReferenceClass() const {
665  return this == Reference::GetJavaLangRefReference<kReadBarrierOption>();
666}
667
668template<VerifyObjectFlags kVerifyFlags, ReadBarrierOption kReadBarrierOption>
669inline bool Class::IsClassClass() {
670  Class* java_lang_Class = GetClass<kVerifyFlags, kReadBarrierOption>()->
671      template GetClass<kVerifyFlags, kReadBarrierOption>();
672  return this == java_lang_Class;
673}
674
675inline const DexFile& Class::GetDexFile() {
676  return *GetDexCache()->GetDexFile();
677}
678
679inline bool Class::DescriptorEquals(const char* match) {
680  if (IsArrayClass()) {
681    return match[0] == '[' && GetComponentType()->DescriptorEquals(match + 1);
682  } else if (IsPrimitive()) {
683    return strcmp(Primitive::Descriptor(GetPrimitiveType()), match) == 0;
684  } else if (IsProxyClass()) {
685    return Runtime::Current()->GetClassLinker()->GetDescriptorForProxy(this) == match;
686  } else {
687    const DexFile& dex_file = GetDexFile();
688    const DexFile::TypeId& type_id = dex_file.GetTypeId(GetClassDef()->class_idx_);
689    return strcmp(dex_file.GetTypeDescriptor(type_id), match) == 0;
690  }
691}
692
693inline void Class::AssertInitializedOrInitializingInThread(Thread* self) {
694  if (kIsDebugBuild && !IsInitialized()) {
695    CHECK(IsInitializing()) << PrettyClass(this) << " is not initializing: " << GetStatus();
696    CHECK_EQ(GetClinitThreadId(), self->GetTid()) << PrettyClass(this)
697                                                  << " is initializing in a different thread";
698  }
699}
700
701inline ObjectArray<Class>* Class::GetInterfaces() {
702  CHECK(IsProxyClass());
703  // First static field.
704  DCHECK(GetSFields()->Get(0)->IsArtField());
705  DCHECK_STREQ(GetSFields()->Get(0)->GetName(), "interfaces");
706  MemberOffset field_offset = GetSFields()->Get(0)->GetOffset();
707  return GetFieldObject<ObjectArray<Class>>(field_offset);
708}
709
710inline ObjectArray<ObjectArray<Class>>* Class::GetThrows() {
711  CHECK(IsProxyClass());
712  // Second static field.
713  DCHECK(GetSFields()->Get(1)->IsArtField());
714  DCHECK_STREQ(GetSFields()->Get(1)->GetName(), "throws");
715  MemberOffset field_offset = GetSFields()->Get(1)->GetOffset();
716  return GetFieldObject<ObjectArray<ObjectArray<Class>>>(field_offset);
717}
718
719inline MemberOffset Class::GetDisableIntrinsicFlagOffset() {
720  CHECK(IsReferenceClass());
721  // First static field
722  DCHECK(GetSFields()->Get(0)->IsArtField());
723  DCHECK_STREQ(GetSFields()->Get(0)->GetName(), "disableIntrinsic");
724  return GetSFields()->Get(0)->GetOffset();
725}
726
727inline MemberOffset Class::GetSlowPathFlagOffset() {
728  CHECK(IsReferenceClass());
729  // Second static field
730  DCHECK(GetSFields()->Get(1)->IsArtField());
731  DCHECK_STREQ(GetSFields()->Get(1)->GetName(), "slowPathEnabled");
732  return GetSFields()->Get(1)->GetOffset();
733}
734
735inline bool Class::GetSlowPathEnabled() {
736  return GetFieldBoolean(GetSlowPathFlagOffset());
737}
738
739inline void Class::SetSlowPath(bool enabled) {
740  SetFieldBoolean<false>(GetSlowPathFlagOffset(), enabled);
741}
742
743inline void Class::InitializeClassVisitor::operator()(
744    mirror::Object* obj, size_t usable_size) const {
745  DCHECK_LE(class_size_, usable_size);
746  // Avoid AsClass as object is not yet in live bitmap or allocation stack.
747  mirror::Class* klass = down_cast<mirror::Class*>(obj);
748  // DCHECK(klass->IsClass());
749  klass->SetClassSize(class_size_);
750  klass->SetPrimitiveType(Primitive::kPrimNot);  // Default to not being primitive.
751  klass->SetDexClassDefIndex(DexFile::kDexNoIndex16);  // Default to no valid class def index.
752  klass->SetDexTypeIndex(DexFile::kDexNoIndex16);  // Default to no valid type index.
753}
754
755inline void Class::SetAccessFlags(uint32_t new_access_flags) {
756  // Called inside a transaction when setting pre-verified flag during boot image compilation.
757  if (Runtime::Current()->IsActiveTransaction()) {
758    SetField32<true>(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_), new_access_flags);
759  } else {
760    SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, access_flags_), new_access_flags);
761  }
762}
763
764}  // namespace mirror
765}  // namespace art
766
767#endif  // ART_RUNTIME_MIRROR_CLASS_INL_H_
768