1 /*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "class.h"
18
19 #include <unordered_set>
20 #include <string_view>
21
22 #include "android-base/macros.h"
23 #include "android-base/stringprintf.h"
24
25 #include "array-inl.h"
26 #include "art_field-inl.h"
27 #include "art_method-inl.h"
28 #include "base/enums.h"
29 #include "base/logging.h" // For VLOG.
30 #include "base/utils.h"
31 #include "class-inl.h"
32 #include "class_ext-inl.h"
33 #include "class_linker-inl.h"
34 #include "class_loader.h"
35 #include "class_root-inl.h"
36 #include "dex/descriptors_names.h"
37 #include "dex/dex_file-inl.h"
38 #include "dex/dex_file_annotations.h"
39 #include "dex/signature-inl.h"
40 #include "dex_cache-inl.h"
41 #include "gc/accounting/card_table-inl.h"
42 #include "gc/heap-inl.h"
43 #include "handle_scope-inl.h"
44 #include "hidden_api.h"
45 #include "jni_id_type.h"
46 #include "subtype_check.h"
47 #include "method.h"
48 #include "object-inl.h"
49 #include "object-refvisitor-inl.h"
50 #include "object_array-inl.h"
51 #include "object_lock.h"
52 #include "string-inl.h"
53 #include "runtime.h"
54 #include "thread.h"
55 #include "throwable.h"
56 #include "well_known_classes.h"
57
58 namespace art {
59
60 // TODO: move to own CC file?
61 constexpr size_t BitString::kBitSizeAtPosition[BitString::kCapacity];
62 constexpr size_t BitString::kCapacity;
63
64 namespace mirror {
65
66 using android::base::StringPrintf;
67
IsMirrored()68 bool Class::IsMirrored() {
69 if (LIKELY(!IsBootStrapClassLoaded())) {
70 return false;
71 }
72 if (IsPrimitive() || IsArrayClass() || IsProxyClass()) {
73 return true;
74 }
75 // TODO Have this list automatically populated.
76 std::unordered_set<std::string_view> mirror_types = {
77 "Ljava/lang/Class;",
78 "Ljava/lang/ClassLoader;",
79 "Ljava/lang/ClassNotFoundException;",
80 "Ljava/lang/DexCache;",
81 "Ljava/lang/Object;",
82 "Ljava/lang/StackTraceElement;",
83 "Ljava/lang/String;",
84 "Ljava/lang/Throwable;",
85 "Ljava/lang/invoke/ArrayElementVarHandle;",
86 "Ljava/lang/invoke/ByteArrayViewVarHandle;",
87 "Ljava/lang/invoke/ByteBufferViewVarHandle;",
88 "Ljava/lang/invoke/CallSite;",
89 "Ljava/lang/invoke/FieldVarHandle;",
90 "Ljava/lang/invoke/MethodHandle;",
91 "Ljava/lang/invoke/MethodHandleImpl;",
92 "Ljava/lang/invoke/MethodHandles$Lookup;",
93 "Ljava/lang/invoke/MethodType;",
94 "Ljava/lang/invoke/VarHandle;",
95 "Ljava/lang/ref/FinalizerReference;",
96 "Ljava/lang/ref/Reference;",
97 "Ljava/lang/reflect/AccessibleObject;",
98 "Ljava/lang/reflect/Constructor;",
99 "Ljava/lang/reflect/Executable;",
100 "Ljava/lang/reflect/Field;",
101 "Ljava/lang/reflect/Method;",
102 "Ljava/lang/reflect/Proxy;",
103 "Ldalvik/system/ClassExt;",
104 "Ldalvik/system/EmulatedStackFrame;",
105 };
106 std::string name_storage;
107 const std::string name(this->GetDescriptor(&name_storage));
108 return mirror_types.find(name) != mirror_types.end();
109 }
110
GetPrimitiveClass(ObjPtr<mirror::String> name)111 ObjPtr<mirror::Class> Class::GetPrimitiveClass(ObjPtr<mirror::String> name) {
112 const char* expected_name = nullptr;
113 ClassRoot class_root = ClassRoot::kJavaLangObject; // Invalid.
114 if (name != nullptr && name->GetLength() >= 2) {
115 // Perfect hash for the expected values: from the second letters of the primitive types,
116 // only 'y' has the bit 0x10 set, so use it to change 'b' to 'B'.
117 char hash = name->CharAt(0) ^ ((name->CharAt(1) & 0x10) << 1);
118 switch (hash) {
119 case 'b': expected_name = "boolean"; class_root = ClassRoot::kPrimitiveBoolean; break;
120 case 'B': expected_name = "byte"; class_root = ClassRoot::kPrimitiveByte; break;
121 case 'c': expected_name = "char"; class_root = ClassRoot::kPrimitiveChar; break;
122 case 'd': expected_name = "double"; class_root = ClassRoot::kPrimitiveDouble; break;
123 case 'f': expected_name = "float"; class_root = ClassRoot::kPrimitiveFloat; break;
124 case 'i': expected_name = "int"; class_root = ClassRoot::kPrimitiveInt; break;
125 case 'l': expected_name = "long"; class_root = ClassRoot::kPrimitiveLong; break;
126 case 's': expected_name = "short"; class_root = ClassRoot::kPrimitiveShort; break;
127 case 'v': expected_name = "void"; class_root = ClassRoot::kPrimitiveVoid; break;
128 default: break;
129 }
130 }
131 if (expected_name != nullptr && name->Equals(expected_name)) {
132 ObjPtr<mirror::Class> klass = GetClassRoot(class_root);
133 DCHECK(klass != nullptr);
134 return klass;
135 } else {
136 Thread* self = Thread::Current();
137 if (name == nullptr) {
138 // Note: ThrowNullPointerException() requires a message which we deliberately want to omit.
139 self->ThrowNewException("Ljava/lang/NullPointerException;", /* msg= */ nullptr);
140 } else {
141 self->ThrowNewException("Ljava/lang/ClassNotFoundException;", name->ToModifiedUtf8().c_str());
142 }
143 return nullptr;
144 }
145 }
146
EnsureExtDataPresent(Handle<Class> h_this,Thread * self)147 ObjPtr<ClassExt> Class::EnsureExtDataPresent(Handle<Class> h_this, Thread* self) {
148 ObjPtr<ClassExt> existing(h_this->GetExtData());
149 if (!existing.IsNull()) {
150 return existing;
151 }
152 StackHandleScope<2> hs(self);
153 // Clear exception so we can allocate.
154 Handle<Throwable> throwable(hs.NewHandle(self->GetException()));
155 self->ClearException();
156 // Allocate the ClassExt
157 Handle<ClassExt> new_ext(hs.NewHandle(ClassExt::Alloc(self)));
158 if (new_ext == nullptr) {
159 // OOM allocating the classExt.
160 // TODO Should we restore the suppressed exception?
161 self->AssertPendingOOMException();
162 return nullptr;
163 } else {
164 MemberOffset ext_offset(OFFSET_OF_OBJECT_MEMBER(Class, ext_data_));
165 bool set;
166 // Set the ext_data_ field using CAS semantics.
167 if (Runtime::Current()->IsActiveTransaction()) {
168 set = h_this->CasFieldObject<true>(ext_offset,
169 nullptr,
170 new_ext.Get(),
171 CASMode::kStrong,
172 std::memory_order_seq_cst);
173 } else {
174 set = h_this->CasFieldObject<false>(ext_offset,
175 nullptr,
176 new_ext.Get(),
177 CASMode::kStrong,
178 std::memory_order_seq_cst);
179 }
180 ObjPtr<ClassExt> ret(set ? new_ext.Get() : h_this->GetExtData());
181 DCHECK(!set || h_this->GetExtData() == new_ext.Get());
182 CHECK(!ret.IsNull());
183 // Restore the exception if there was one.
184 if (throwable != nullptr) {
185 self->SetException(throwable.Get());
186 }
187 return ret;
188 }
189 }
190
191 template <typename T>
CheckSetStatus(Thread * self,T thiz,ClassStatus new_status,ClassStatus old_status)192 static void CheckSetStatus(Thread* self, T thiz, ClassStatus new_status, ClassStatus old_status)
193 REQUIRES_SHARED(Locks::mutator_lock_) {
194 if (UNLIKELY(new_status <= old_status && new_status != ClassStatus::kErrorUnresolved &&
195 new_status != ClassStatus::kErrorResolved && new_status != ClassStatus::kRetired)) {
196 LOG(FATAL) << "Unexpected change back of class status for " << thiz->PrettyClass() << " "
197 << old_status << " -> " << new_status;
198 }
199 if (old_status == ClassStatus::kInitialized) {
200 // We do not hold the lock for making the class visibly initialized
201 // as this is unnecessary and could lead to deadlocks.
202 CHECK_EQ(new_status, ClassStatus::kVisiblyInitialized);
203 } else if ((new_status >= ClassStatus::kResolved || old_status >= ClassStatus::kResolved) &&
204 !Locks::mutator_lock_->IsExclusiveHeld(self)) {
205 // When classes are being resolved the resolution code should hold the
206 // lock or have everything else suspended
207 CHECK_EQ(thiz->GetLockOwnerThreadId(), self->GetThreadId())
208 << "Attempt to change status of class while not holding its lock: " << thiz->PrettyClass()
209 << " " << old_status << " -> " << new_status;
210 }
211 if (UNLIKELY(Locks::mutator_lock_->IsExclusiveHeld(self))) {
212 CHECK(!Class::IsErroneous(new_status))
213 << "status " << new_status
214 << " cannot be set while suspend-all is active. Would require allocations.";
215 CHECK(thiz->IsResolved())
216 << thiz->PrettyClass()
217 << " not resolved during suspend-all status change. Waiters might be missed!";
218 }
219 }
220
SetStatusInternal(ClassStatus new_status)221 void Class::SetStatusInternal(ClassStatus new_status) {
222 if (kBitstringSubtypeCheckEnabled) {
223 // FIXME: This looks broken with respect to aborted transactions.
224 SubtypeCheck<ObjPtr<mirror::Class>>::WriteStatus(this, new_status);
225 } else {
226 // The ClassStatus is always in the 4 most-significant bits of status_.
227 static_assert(sizeof(status_) == sizeof(uint32_t), "Size of status_ not equal to uint32");
228 uint32_t new_status_value = static_cast<uint32_t>(new_status) << (32 - kClassStatusBitSize);
229 if (Runtime::Current()->IsActiveTransaction()) {
230 SetField32Volatile<true>(StatusOffset(), new_status_value);
231 } else {
232 SetField32Volatile<false>(StatusOffset(), new_status_value);
233 }
234 }
235 }
236
SetStatusLocked(ClassStatus new_status)237 void Class::SetStatusLocked(ClassStatus new_status) {
238 ClassStatus old_status = GetStatus();
239 CheckSetStatus(Thread::Current(), this, new_status, old_status);
240 SetStatusInternal(new_status);
241 }
242
SetStatus(Handle<Class> h_this,ClassStatus new_status,Thread * self)243 void Class::SetStatus(Handle<Class> h_this, ClassStatus new_status, Thread* self) {
244 ClassStatus old_status = h_this->GetStatus();
245 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
246 bool class_linker_initialized = class_linker != nullptr && class_linker->IsInitialized();
247 if (LIKELY(class_linker_initialized)) {
248 CheckSetStatus(self, h_this, new_status, old_status);
249 }
250 if (UNLIKELY(IsErroneous(new_status))) {
251 CHECK(!h_this->IsErroneous())
252 << "Attempt to set as erroneous an already erroneous class "
253 << h_this->PrettyClass()
254 << " old_status: " << old_status << " new_status: " << new_status;
255 CHECK_EQ(new_status == ClassStatus::kErrorResolved, old_status >= ClassStatus::kResolved);
256 if (VLOG_IS_ON(class_linker)) {
257 LOG(ERROR) << "Setting " << h_this->PrettyDescriptor() << " to erroneous.";
258 if (self->IsExceptionPending()) {
259 LOG(ERROR) << "Exception: " << self->GetException()->Dump();
260 }
261 }
262
263 ObjPtr<ClassExt> ext(EnsureExtDataPresent(h_this, self));
264 if (!ext.IsNull()) {
265 self->AssertPendingException();
266 ext->SetVerifyError(self->GetException());
267 } else {
268 self->AssertPendingOOMException();
269 }
270 self->AssertPendingException();
271 }
272
273 h_this->SetStatusInternal(new_status);
274
275 // Setting the object size alloc fast path needs to be after the status write so that if the
276 // alloc path sees a valid object size, we would know that it's initialized as long as it has a
277 // load-acquire/fake dependency.
278 if (new_status == ClassStatus::kVisiblyInitialized && !h_this->IsVariableSize()) {
279 DCHECK_EQ(h_this->GetObjectSizeAllocFastPath(), std::numeric_limits<uint32_t>::max());
280 // Finalizable objects must always go slow path.
281 if (!h_this->IsFinalizable()) {
282 h_this->SetObjectSizeAllocFastPath(RoundUp(h_this->GetObjectSize(), kObjectAlignment));
283 }
284 }
285
286 if (kIsDebugBuild && new_status >= ClassStatus::kInitialized) {
287 CHECK(h_this->WasVerificationAttempted()) << h_this->PrettyClassAndClassLoader();
288 }
289
290 if (!class_linker_initialized) {
291 // When the class linker is being initialized its single threaded and by definition there can be
292 // no waiters. During initialization classes may appear temporary but won't be retired as their
293 // size was statically computed.
294 } else {
295 // Classes that are being resolved or initialized need to notify waiters that the class status
296 // changed. See ClassLinker::EnsureResolved and ClassLinker::WaitForInitializeClass.
297 if (h_this->IsTemp()) {
298 // Class is a temporary one, ensure that waiters for resolution get notified of retirement
299 // so that they can grab the new version of the class from the class linker's table.
300 CHECK_LT(new_status, ClassStatus::kResolved) << h_this->PrettyDescriptor();
301 if (new_status == ClassStatus::kRetired || new_status == ClassStatus::kErrorUnresolved) {
302 h_this->NotifyAll(self);
303 }
304 } else if (old_status == ClassStatus::kInitialized) {
305 // Do not notify for transition from kInitialized to ClassStatus::kVisiblyInitialized.
306 // This is a hidden transition, not observable by bytecode.
307 DCHECK_EQ(new_status, ClassStatus::kVisiblyInitialized); // Already CHECK()ed above.
308 } else {
309 CHECK_NE(new_status, ClassStatus::kRetired);
310 if (old_status >= ClassStatus::kResolved || new_status >= ClassStatus::kResolved) {
311 h_this->NotifyAll(self);
312 }
313 }
314 }
315 }
316
SetStatusForPrimitiveOrArray(ClassStatus new_status)317 void Class::SetStatusForPrimitiveOrArray(ClassStatus new_status) {
318 DCHECK(IsPrimitive<kVerifyNone>() || IsArrayClass<kVerifyNone>());
319 DCHECK(!IsErroneous(new_status));
320 DCHECK(!IsErroneous(GetStatus<kVerifyNone>()));
321 DCHECK_GT(new_status, GetStatus<kVerifyNone>());
322
323 if (kBitstringSubtypeCheckEnabled) {
324 LOG(FATAL) << "Unimplemented";
325 }
326 // The ClassStatus is always in the 4 most-significant bits of status_.
327 static_assert(sizeof(status_) == sizeof(uint32_t), "Size of status_ not equal to uint32");
328 uint32_t new_status_value = static_cast<uint32_t>(new_status) << (32 - kClassStatusBitSize);
329 // Use normal store. For primitives and core arrays classes (Object[],
330 // Class[], String[] and primitive arrays), the status is set while the
331 // process is still single threaded. For other arrays classes, it is set
332 // in a pre-fence visitor which initializes all fields and the subsequent
333 // fence together with address dependency shall ensure memory visibility.
334 SetField32</*kTransactionActive=*/ false,
335 /*kCheckTransaction=*/ false,
336 kVerifyNone>(StatusOffset(), new_status_value);
337
338 // Do not update `object_alloc_fast_path_`. Arrays are variable size and
339 // instances of primitive classes cannot be created at all.
340
341 if (kIsDebugBuild && new_status >= ClassStatus::kInitialized) {
342 CHECK(WasVerificationAttempted()) << PrettyClassAndClassLoader();
343 }
344
345 // There can be no waiters to notify as these classes are initialized
346 // before another thread can see them.
347 }
348
SetDexCache(ObjPtr<DexCache> new_dex_cache)349 void Class::SetDexCache(ObjPtr<DexCache> new_dex_cache) {
350 SetFieldObjectTransaction(OFFSET_OF_OBJECT_MEMBER(Class, dex_cache_), new_dex_cache);
351 }
352
SetClassSize(uint32_t new_class_size)353 void Class::SetClassSize(uint32_t new_class_size) {
354 if (kIsDebugBuild && new_class_size < GetClassSize()) {
355 DumpClass(LOG_STREAM(FATAL_WITHOUT_ABORT), kDumpClassFullDetail);
356 LOG(FATAL_WITHOUT_ABORT) << new_class_size << " vs " << GetClassSize();
357 LOG(FATAL) << "class=" << PrettyTypeOf();
358 }
359 SetField32</*kTransactionActive=*/ false, /*kCheckTransaction=*/ false>(
360 OFFSET_OF_OBJECT_MEMBER(Class, class_size_), new_class_size);
361 }
362
GetObsoleteClass()363 ObjPtr<Class> Class::GetObsoleteClass() {
364 ObjPtr<ClassExt> ext(GetExtData());
365 if (ext.IsNull()) {
366 return nullptr;
367 } else {
368 return ext->GetObsoleteClass();
369 }
370 }
371
372 // Return the class' name. The exact format is bizarre, but it's the specified behavior for
373 // Class.getName: keywords for primitive types, regular "[I" form for primitive arrays (so "int"
374 // but "[I"), and arrays of reference types written between "L" and ";" but with dots rather than
375 // slashes (so "java.lang.String" but "[Ljava.lang.String;"). Madness.
ComputeName(Handle<Class> h_this)376 ObjPtr<String> Class::ComputeName(Handle<Class> h_this) {
377 ObjPtr<String> name = h_this->GetName();
378 if (name != nullptr) {
379 return name;
380 }
381 std::string temp;
382 const char* descriptor = h_this->GetDescriptor(&temp);
383 Thread* self = Thread::Current();
384 if ((descriptor[0] != 'L') && (descriptor[0] != '[')) {
385 // The descriptor indicates that this is the class for
386 // a primitive type; special-case the return value.
387 const char* c_name = nullptr;
388 switch (descriptor[0]) {
389 case 'Z': c_name = "boolean"; break;
390 case 'B': c_name = "byte"; break;
391 case 'C': c_name = "char"; break;
392 case 'S': c_name = "short"; break;
393 case 'I': c_name = "int"; break;
394 case 'J': c_name = "long"; break;
395 case 'F': c_name = "float"; break;
396 case 'D': c_name = "double"; break;
397 case 'V': c_name = "void"; break;
398 default:
399 LOG(FATAL) << "Unknown primitive type: " << PrintableChar(descriptor[0]);
400 }
401 name = String::AllocFromModifiedUtf8(self, c_name);
402 } else {
403 // Convert the UTF-8 name to a java.lang.String. The name must use '.' to separate package
404 // components.
405 name = String::AllocFromModifiedUtf8(self, DescriptorToDot(descriptor).c_str());
406 }
407 h_this->SetName(name);
408 return name;
409 }
410
DumpClass(std::ostream & os,int flags)411 void Class::DumpClass(std::ostream& os, int flags) {
412 if ((flags & kDumpClassFullDetail) == 0) {
413 os << PrettyClass();
414 if ((flags & kDumpClassClassLoader) != 0) {
415 os << ' ' << GetClassLoader();
416 }
417 if ((flags & kDumpClassInitialized) != 0) {
418 os << ' ' << GetStatus();
419 }
420 os << "\n";
421 return;
422 }
423
424 Thread* const self = Thread::Current();
425 StackHandleScope<2> hs(self);
426 Handle<Class> h_this(hs.NewHandle(this));
427 Handle<Class> h_super(hs.NewHandle(GetSuperClass()));
428 auto image_pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize();
429
430 std::string temp;
431 os << "----- " << (IsInterface() ? "interface" : "class") << " "
432 << "'" << GetDescriptor(&temp) << "' cl=" << GetClassLoader() << " -----\n",
433 os << " objectSize=" << SizeOf() << " "
434 << "(" << (h_super != nullptr ? h_super->SizeOf() : -1) << " from super)\n",
435 os << StringPrintf(" access=0x%04x.%04x\n",
436 GetAccessFlags() >> 16, GetAccessFlags() & kAccJavaFlagsMask);
437 if (h_super != nullptr) {
438 os << " super='" << h_super->PrettyClass() << "' (cl=" << h_super->GetClassLoader()
439 << ")\n";
440 }
441 if (IsArrayClass()) {
442 os << " componentType=" << PrettyClass(GetComponentType()) << "\n";
443 }
444 const size_t num_direct_interfaces = NumDirectInterfaces();
445 if (num_direct_interfaces > 0) {
446 os << " interfaces (" << num_direct_interfaces << "):\n";
447 for (size_t i = 0; i < num_direct_interfaces; ++i) {
448 ObjPtr<Class> interface = GetDirectInterface(self, h_this.Get(), i);
449 if (interface == nullptr) {
450 os << StringPrintf(" %2zd: nullptr!\n", i);
451 } else {
452 ObjPtr<ClassLoader> cl = interface->GetClassLoader();
453 os << StringPrintf(" %2zd: %s (cl=%p)\n", i, PrettyClass(interface).c_str(), cl.Ptr());
454 }
455 }
456 }
457 if (!IsLoaded()) {
458 os << " class not yet loaded";
459 } else {
460 // After this point, this may have moved due to GetDirectInterface.
461 os << " vtable (" << h_this->NumVirtualMethods() << " entries, "
462 << (h_super != nullptr ? h_super->NumVirtualMethods() : 0) << " in super):\n";
463 for (size_t i = 0; i < NumVirtualMethods(); ++i) {
464 os << StringPrintf(" %2zd: %s\n", i, ArtMethod::PrettyMethod(
465 h_this->GetVirtualMethodDuringLinking(i, image_pointer_size)).c_str());
466 }
467 os << " direct methods (" << h_this->NumDirectMethods() << " entries):\n";
468 for (size_t i = 0; i < h_this->NumDirectMethods(); ++i) {
469 os << StringPrintf(" %2zd: %s\n", i, ArtMethod::PrettyMethod(
470 h_this->GetDirectMethod(i, image_pointer_size)).c_str());
471 }
472 if (h_this->NumStaticFields() > 0) {
473 os << " static fields (" << h_this->NumStaticFields() << " entries):\n";
474 if (h_this->IsResolved()) {
475 for (size_t i = 0; i < h_this->NumStaticFields(); ++i) {
476 os << StringPrintf(" %2zd: %s\n", i,
477 ArtField::PrettyField(h_this->GetStaticField(i)).c_str());
478 }
479 } else {
480 os << " <not yet available>";
481 }
482 }
483 if (h_this->NumInstanceFields() > 0) {
484 os << " instance fields (" << h_this->NumInstanceFields() << " entries):\n";
485 if (h_this->IsResolved()) {
486 for (size_t i = 0; i < h_this->NumInstanceFields(); ++i) {
487 os << StringPrintf(" %2zd: %s\n", i,
488 ArtField::PrettyField(h_this->GetInstanceField(i)).c_str());
489 }
490 } else {
491 os << " <not yet available>";
492 }
493 }
494 }
495 }
496
SetReferenceInstanceOffsets(uint32_t new_reference_offsets)497 void Class::SetReferenceInstanceOffsets(uint32_t new_reference_offsets) {
498 if (kIsDebugBuild && new_reference_offsets != kClassWalkSuper) {
499 // Check that the number of bits set in the reference offset bitmap
500 // agrees with the number of references.
501 uint32_t count = 0;
502 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
503 count += c->NumReferenceInstanceFieldsDuringLinking();
504 }
505 // +1 for the Class in Object.
506 CHECK_EQ(static_cast<uint32_t>(POPCOUNT(new_reference_offsets)) + 1, count);
507 }
508 // Not called within a transaction.
509 SetField32<false>(OFFSET_OF_OBJECT_MEMBER(Class, reference_instance_offsets_),
510 new_reference_offsets);
511 }
512
IsInSamePackage(std::string_view descriptor1,std::string_view descriptor2)513 bool Class::IsInSamePackage(std::string_view descriptor1, std::string_view descriptor2) {
514 size_t i = 0;
515 size_t min_length = std::min(descriptor1.size(), descriptor2.size());
516 while (i < min_length && descriptor1[i] == descriptor2[i]) {
517 ++i;
518 }
519 if (descriptor1.find('/', i) != std::string_view::npos ||
520 descriptor2.find('/', i) != std::string_view::npos) {
521 return false;
522 } else {
523 return true;
524 }
525 }
526
IsInSamePackage(ObjPtr<Class> that)527 bool Class::IsInSamePackage(ObjPtr<Class> that) {
528 ObjPtr<Class> klass1 = this;
529 ObjPtr<Class> klass2 = that;
530 if (klass1 == klass2) {
531 return true;
532 }
533 // Class loaders must match.
534 if (klass1->GetClassLoader() != klass2->GetClassLoader()) {
535 return false;
536 }
537 // Arrays are in the same package when their element classes are.
538 while (klass1->IsArrayClass()) {
539 klass1 = klass1->GetComponentType();
540 }
541 while (klass2->IsArrayClass()) {
542 klass2 = klass2->GetComponentType();
543 }
544 // trivial check again for array types
545 if (klass1 == klass2) {
546 return true;
547 }
548 // Compare the package part of the descriptor string.
549 std::string temp1, temp2;
550 return IsInSamePackage(klass1->GetDescriptor(&temp1), klass2->GetDescriptor(&temp2));
551 }
552
IsThrowableClass()553 bool Class::IsThrowableClass() {
554 return GetClassRoot<mirror::Throwable>()->IsAssignableFrom(this);
555 }
556
557 template <typename SignatureType>
FindInterfaceMethodWithSignature(ObjPtr<Class> klass,std::string_view name,const SignatureType & signature,PointerSize pointer_size)558 static inline ArtMethod* FindInterfaceMethodWithSignature(ObjPtr<Class> klass,
559 std::string_view name,
560 const SignatureType& signature,
561 PointerSize pointer_size)
562 REQUIRES_SHARED(Locks::mutator_lock_) {
563 // If the current class is not an interface, skip the search of its declared methods;
564 // such lookup is used only to distinguish between IncompatibleClassChangeError and
565 // NoSuchMethodError and the caller has already tried to search methods in the class.
566 if (LIKELY(klass->IsInterface())) {
567 // Search declared methods, both direct and virtual.
568 // (This lookup is used also for invoke-static on interface classes.)
569 for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
570 if (method.GetNameView() == name && method.GetSignature() == signature) {
571 return &method;
572 }
573 }
574 }
575
576 // TODO: If there is a unique maximally-specific non-abstract superinterface method,
577 // we should return it, otherwise an arbitrary one can be returned.
578 ObjPtr<IfTable> iftable = klass->GetIfTable();
579 for (int32_t i = 0, iftable_count = iftable->Count(); i < iftable_count; ++i) {
580 ObjPtr<Class> iface = iftable->GetInterface(i);
581 for (ArtMethod& method : iface->GetVirtualMethodsSlice(pointer_size)) {
582 if (method.GetNameView() == name && method.GetSignature() == signature) {
583 return &method;
584 }
585 }
586 }
587
588 // Then search for public non-static methods in the java.lang.Object.
589 if (LIKELY(klass->IsInterface())) {
590 ObjPtr<Class> object_class = klass->GetSuperClass();
591 DCHECK(object_class->IsObjectClass());
592 for (ArtMethod& method : object_class->GetDeclaredMethodsSlice(pointer_size)) {
593 if (method.IsPublic() && !method.IsStatic() &&
594 method.GetNameView() == name && method.GetSignature() == signature) {
595 return &method;
596 }
597 }
598 }
599 return nullptr;
600 }
601
FindInterfaceMethod(std::string_view name,std::string_view signature,PointerSize pointer_size)602 ArtMethod* Class::FindInterfaceMethod(std::string_view name,
603 std::string_view signature,
604 PointerSize pointer_size) {
605 return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
606 }
607
FindInterfaceMethod(std::string_view name,const Signature & signature,PointerSize pointer_size)608 ArtMethod* Class::FindInterfaceMethod(std::string_view name,
609 const Signature& signature,
610 PointerSize pointer_size) {
611 return FindInterfaceMethodWithSignature(this, name, signature, pointer_size);
612 }
613
FindInterfaceMethod(ObjPtr<DexCache> dex_cache,uint32_t dex_method_idx,PointerSize pointer_size)614 ArtMethod* Class::FindInterfaceMethod(ObjPtr<DexCache> dex_cache,
615 uint32_t dex_method_idx,
616 PointerSize pointer_size) {
617 // We always search by name and signature, ignoring the type index in the MethodId.
618 const DexFile& dex_file = *dex_cache->GetDexFile();
619 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
620 std::string_view name = dex_file.StringViewByIdx(method_id.name_idx_);
621 const Signature signature = dex_file.GetMethodSignature(method_id);
622 return FindInterfaceMethod(name, signature, pointer_size);
623 }
624
IsValidInheritanceCheck(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Class> declaring_class)625 static inline bool IsValidInheritanceCheck(ObjPtr<mirror::Class> klass,
626 ObjPtr<mirror::Class> declaring_class)
627 REQUIRES_SHARED(Locks::mutator_lock_) {
628 if (klass->IsArrayClass()) {
629 return declaring_class->IsObjectClass();
630 } else if (klass->IsInterface()) {
631 return declaring_class->IsObjectClass() || declaring_class == klass;
632 } else {
633 return klass->IsSubClass(declaring_class);
634 }
635 }
636
IsInheritedMethod(ObjPtr<mirror::Class> klass,ObjPtr<mirror::Class> declaring_class,ArtMethod & method)637 static inline bool IsInheritedMethod(ObjPtr<mirror::Class> klass,
638 ObjPtr<mirror::Class> declaring_class,
639 ArtMethod& method)
640 REQUIRES_SHARED(Locks::mutator_lock_) {
641 DCHECK_EQ(declaring_class, method.GetDeclaringClass());
642 DCHECK_NE(klass, declaring_class);
643 DCHECK(IsValidInheritanceCheck(klass, declaring_class));
644 uint32_t access_flags = method.GetAccessFlags();
645 if ((access_flags & (kAccPublic | kAccProtected)) != 0) {
646 return true;
647 }
648 if ((access_flags & kAccPrivate) != 0) {
649 return false;
650 }
651 for (; klass != declaring_class; klass = klass->GetSuperClass()) {
652 if (!klass->IsInSamePackage(declaring_class)) {
653 return false;
654 }
655 }
656 return true;
657 }
658
659 template <typename SignatureType>
FindClassMethodWithSignature(ObjPtr<Class> this_klass,std::string_view name,const SignatureType & signature,PointerSize pointer_size)660 static inline ArtMethod* FindClassMethodWithSignature(ObjPtr<Class> this_klass,
661 std::string_view name,
662 const SignatureType& signature,
663 PointerSize pointer_size)
664 REQUIRES_SHARED(Locks::mutator_lock_) {
665 // Search declared methods first.
666 for (ArtMethod& method : this_klass->GetDeclaredMethodsSlice(pointer_size)) {
667 ArtMethod* np_method = method.GetInterfaceMethodIfProxy(pointer_size);
668 if (np_method->GetName() == name && np_method->GetSignature() == signature) {
669 return &method;
670 }
671 }
672
673 // Then search the superclass chain. If we find an inherited method, return it.
674 // If we find a method that's not inherited because of access restrictions,
675 // try to find a method inherited from an interface in copied methods.
676 ObjPtr<Class> klass = this_klass->GetSuperClass();
677 ArtMethod* uninherited_method = nullptr;
678 for (; klass != nullptr; klass = klass->GetSuperClass()) {
679 DCHECK(!klass->IsProxyClass());
680 for (ArtMethod& method : klass->GetDeclaredMethodsSlice(pointer_size)) {
681 if (method.GetName() == name && method.GetSignature() == signature) {
682 if (IsInheritedMethod(this_klass, klass, method)) {
683 return &method;
684 }
685 uninherited_method = &method;
686 break;
687 }
688 }
689 if (uninherited_method != nullptr) {
690 break;
691 }
692 }
693
694 // Then search copied methods.
695 // If we found a method that's not inherited, stop the search in its declaring class.
696 ObjPtr<Class> end_klass = klass;
697 DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
698 klass = this_klass;
699 if (UNLIKELY(klass->IsProxyClass())) {
700 DCHECK(klass->GetCopiedMethodsSlice(pointer_size).empty());
701 klass = klass->GetSuperClass();
702 }
703 for (; klass != end_klass; klass = klass->GetSuperClass()) {
704 DCHECK(!klass->IsProxyClass());
705 for (ArtMethod& method : klass->GetCopiedMethodsSlice(pointer_size)) {
706 if (method.GetName() == name && method.GetSignature() == signature) {
707 return &method; // No further check needed, copied methods are inherited by definition.
708 }
709 }
710 }
711 return uninherited_method; // Return the `uninherited_method` if any.
712 }
713
714
FindClassMethod(std::string_view name,std::string_view signature,PointerSize pointer_size)715 ArtMethod* Class::FindClassMethod(std::string_view name,
716 std::string_view signature,
717 PointerSize pointer_size) {
718 return FindClassMethodWithSignature(this, name, signature, pointer_size);
719 }
720
FindClassMethod(std::string_view name,const Signature & signature,PointerSize pointer_size)721 ArtMethod* Class::FindClassMethod(std::string_view name,
722 const Signature& signature,
723 PointerSize pointer_size) {
724 return FindClassMethodWithSignature(this, name, signature, pointer_size);
725 }
726
FindClassMethod(ObjPtr<DexCache> dex_cache,uint32_t dex_method_idx,PointerSize pointer_size)727 ArtMethod* Class::FindClassMethod(ObjPtr<DexCache> dex_cache,
728 uint32_t dex_method_idx,
729 PointerSize pointer_size) {
730 // FIXME: Hijacking a proxy class by a custom class loader can break this assumption.
731 DCHECK(!IsProxyClass());
732
733 // First try to find a declared method by dex_method_idx if we have a dex_cache match.
734 ObjPtr<DexCache> this_dex_cache = GetDexCache();
735 if (this_dex_cache == dex_cache) {
736 // Lookup is always performed in the class referenced by the MethodId.
737 DCHECK_EQ(dex_type_idx_, GetDexFile().GetMethodId(dex_method_idx).class_idx_.index_);
738 for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
739 if (method.GetDexMethodIndex() == dex_method_idx) {
740 return &method;
741 }
742 }
743 }
744 // If not found, we need to search by name and signature.
745 const DexFile& dex_file = *dex_cache->GetDexFile();
746 const dex::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
747 const Signature signature = dex_file.GetMethodSignature(method_id);
748 std::string_view name; // Delay strlen() until actually needed.
749 // If we do not have a dex_cache match, try to find the declared method in this class now.
750 if (this_dex_cache != dex_cache && !GetDeclaredMethodsSlice(pointer_size).empty()) {
751 DCHECK(name.empty());
752 // Avoid string comparisons by comparing the respective unicode lengths first.
753 uint32_t length, other_length; // UTF16 length.
754 name = dex_file.GetMethodName(method_id, &length);
755 for (ArtMethod& method : GetDeclaredMethodsSlice(pointer_size)) {
756 DCHECK_NE(method.GetDexMethodIndex(), dex::kDexNoIndex);
757 const char* other_name = method.GetDexFile()->GetMethodName(
758 method.GetDexMethodIndex(), &other_length);
759 if (length == other_length && name == other_name && signature == method.GetSignature()) {
760 return &method;
761 }
762 }
763 }
764
765 // Then search the superclass chain. If we find an inherited method, return it.
766 // If we find a method that's not inherited because of access restrictions,
767 // try to find a method inherited from an interface in copied methods.
768 ArtMethod* uninherited_method = nullptr;
769 ObjPtr<Class> klass = GetSuperClass();
770 for (; klass != nullptr; klass = klass->GetSuperClass()) {
771 ArtMethod* candidate_method = nullptr;
772 ArraySlice<ArtMethod> declared_methods = klass->GetDeclaredMethodsSlice(pointer_size);
773 if (klass->GetDexCache() == dex_cache) {
774 // Matching dex_cache. We cannot compare the `dex_method_idx` anymore because
775 // the type index differs, so compare the name index and proto index.
776 for (ArtMethod& method : declared_methods) {
777 const dex::MethodId& cmp_method_id = dex_file.GetMethodId(method.GetDexMethodIndex());
778 if (cmp_method_id.name_idx_ == method_id.name_idx_ &&
779 cmp_method_id.proto_idx_ == method_id.proto_idx_) {
780 candidate_method = &method;
781 break;
782 }
783 }
784 } else {
785 if (!declared_methods.empty() && name.empty()) {
786 name = dex_file.StringDataByIdx(method_id.name_idx_);
787 }
788 for (ArtMethod& method : declared_methods) {
789 if (method.GetName() == name && method.GetSignature() == signature) {
790 candidate_method = &method;
791 break;
792 }
793 }
794 }
795 if (candidate_method != nullptr) {
796 if (IsInheritedMethod(this, klass, *candidate_method)) {
797 return candidate_method;
798 } else {
799 uninherited_method = candidate_method;
800 break;
801 }
802 }
803 }
804
805 // Then search copied methods.
806 // If we found a method that's not inherited, stop the search in its declaring class.
807 ObjPtr<Class> end_klass = klass;
808 DCHECK_EQ(uninherited_method != nullptr, end_klass != nullptr);
809 // After we have searched the declared methods of the super-class chain,
810 // search copied methods which can contain methods from interfaces.
811 for (klass = this; klass != end_klass; klass = klass->GetSuperClass()) {
812 ArraySlice<ArtMethod> copied_methods = klass->GetCopiedMethodsSlice(pointer_size);
813 if (!copied_methods.empty() && name.empty()) {
814 name = dex_file.StringDataByIdx(method_id.name_idx_);
815 }
816 for (ArtMethod& method : copied_methods) {
817 if (method.GetName() == name && method.GetSignature() == signature) {
818 return &method; // No further check needed, copied methods are inherited by definition.
819 }
820 }
821 }
822 return uninherited_method; // Return the `uninherited_method` if any.
823 }
824
FindConstructor(std::string_view signature,PointerSize pointer_size)825 ArtMethod* Class::FindConstructor(std::string_view signature, PointerSize pointer_size) {
826 // Internal helper, never called on proxy classes. We can skip GetInterfaceMethodIfProxy().
827 DCHECK(!IsProxyClass());
828 std::string_view name("<init>");
829 for (ArtMethod& method : GetDirectMethodsSliceUnchecked(pointer_size)) {
830 if (method.GetName() == name && method.GetSignature() == signature) {
831 return &method;
832 }
833 }
834 return nullptr;
835 }
836
FindDeclaredDirectMethodByName(std::string_view name,PointerSize pointer_size)837 ArtMethod* Class::FindDeclaredDirectMethodByName(std::string_view name, PointerSize pointer_size) {
838 for (auto& method : GetDirectMethods(pointer_size)) {
839 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
840 if (name == np_method->GetName()) {
841 return &method;
842 }
843 }
844 return nullptr;
845 }
846
FindDeclaredVirtualMethodByName(std::string_view name,PointerSize pointer_size)847 ArtMethod* Class::FindDeclaredVirtualMethodByName(std::string_view name, PointerSize pointer_size) {
848 for (auto& method : GetVirtualMethods(pointer_size)) {
849 ArtMethod* const np_method = method.GetInterfaceMethodIfProxy(pointer_size);
850 if (name == np_method->GetName()) {
851 return &method;
852 }
853 }
854 return nullptr;
855 }
856
FindVirtualMethodForInterfaceSuper(ArtMethod * method,PointerSize pointer_size)857 ArtMethod* Class::FindVirtualMethodForInterfaceSuper(ArtMethod* method, PointerSize pointer_size) {
858 DCHECK(method->GetDeclaringClass()->IsInterface());
859 DCHECK(IsInterface()) << "Should only be called on a interface class";
860 // Check if we have one defined on this interface first. This includes searching copied ones to
861 // get any conflict methods. Conflict methods are copied into each subtype from the supertype. We
862 // don't do any indirect method checks here.
863 for (ArtMethod& iface_method : GetVirtualMethods(pointer_size)) {
864 if (method->HasSameNameAndSignature(&iface_method)) {
865 return &iface_method;
866 }
867 }
868
869 std::vector<ArtMethod*> abstract_methods;
870 // Search through the IFTable for a working version. We don't need to check for conflicts
871 // because if there was one it would appear in this classes virtual_methods_ above.
872
873 Thread* self = Thread::Current();
874 StackHandleScope<2> hs(self);
875 MutableHandle<IfTable> iftable(hs.NewHandle(GetIfTable()));
876 MutableHandle<Class> iface(hs.NewHandle<Class>(nullptr));
877 size_t iftable_count = GetIfTableCount();
878 // Find the method. We don't need to check for conflicts because they would have been in the
879 // copied virtuals of this interface. Order matters, traverse in reverse topological order; most
880 // subtypiest interfaces get visited first.
881 for (size_t k = iftable_count; k != 0;) {
882 k--;
883 DCHECK_LT(k, iftable->Count());
884 iface.Assign(iftable->GetInterface(k));
885 // Iterate through every declared method on this interface. Each direct method's name/signature
886 // is unique so the order of the inner loop doesn't matter.
887 for (auto& method_iter : iface->GetDeclaredVirtualMethods(pointer_size)) {
888 ArtMethod* current_method = &method_iter;
889 if (current_method->HasSameNameAndSignature(method)) {
890 if (current_method->IsDefault()) {
891 // Handle JLS soft errors, a default method from another superinterface tree can
892 // "override" an abstract method(s) from another superinterface tree(s). To do this,
893 // ignore any [default] method which are dominated by the abstract methods we've seen so
894 // far. Check if overridden by any in abstract_methods. We do not need to check for
895 // default_conflicts because we would hit those before we get to this loop.
896 bool overridden = false;
897 for (ArtMethod* possible_override : abstract_methods) {
898 DCHECK(possible_override->HasSameNameAndSignature(current_method));
899 if (iface->IsAssignableFrom(possible_override->GetDeclaringClass())) {
900 overridden = true;
901 break;
902 }
903 }
904 if (!overridden) {
905 return current_method;
906 }
907 } else {
908 // Is not default.
909 // This might override another default method. Just stash it for now.
910 abstract_methods.push_back(current_method);
911 }
912 }
913 }
914 }
915 // If we reach here we either never found any declaration of the method (in which case
916 // 'abstract_methods' is empty or we found no non-overriden default methods in which case
917 // 'abstract_methods' contains a number of abstract implementations of the methods. We choose one
918 // of these arbitrarily.
919 return abstract_methods.empty() ? nullptr : abstract_methods[0];
920 }
921
FindClassInitializer(PointerSize pointer_size)922 ArtMethod* Class::FindClassInitializer(PointerSize pointer_size) {
923 for (ArtMethod& method : GetDirectMethods(pointer_size)) {
924 if (method.IsClassInitializer()) {
925 DCHECK_STREQ(method.GetName(), "<clinit>");
926 DCHECK_STREQ(method.GetSignature().ToString().c_str(), "()V");
927 return &method;
928 }
929 }
930 return nullptr;
931 }
932
933 // Custom binary search to avoid double comparisons from std::binary_search.
FindFieldByNameAndType(LengthPrefixedArray<ArtField> * fields,std::string_view name,std::string_view type)934 static ArtField* FindFieldByNameAndType(LengthPrefixedArray<ArtField>* fields,
935 std::string_view name,
936 std::string_view type)
937 REQUIRES_SHARED(Locks::mutator_lock_) {
938 if (fields == nullptr) {
939 return nullptr;
940 }
941 size_t low = 0;
942 size_t high = fields->size();
943 ArtField* ret = nullptr;
944 while (low < high) {
945 size_t mid = (low + high) / 2;
946 ArtField& field = fields->At(mid);
947 // Fields are sorted by class, then name, then type descriptor. This is verified in dex file
948 // verifier. There can be multiple fields with the same in the same class name due to proguard.
949 // Note: std::string_view::compare() uses lexicographical comparison and treats the `char` as
950 // unsigned; for modified-UTF-8 without embedded nulls this is consistent with the
951 // CompareModifiedUtf8ToModifiedUtf8AsUtf16CodePointValues() ordering.
952 int result = std::string_view(field.GetName()).compare(name);
953 if (result == 0) {
954 result = std::string_view(field.GetTypeDescriptor()).compare(type);
955 }
956 if (result < 0) {
957 low = mid + 1;
958 } else if (result > 0) {
959 high = mid;
960 } else {
961 ret = &field;
962 break;
963 }
964 }
965 if (kIsDebugBuild) {
966 ArtField* found = nullptr;
967 for (ArtField& field : MakeIterationRangeFromLengthPrefixedArray(fields)) {
968 if (name == field.GetName() && type == field.GetTypeDescriptor()) {
969 found = &field;
970 break;
971 }
972 }
973 CHECK_EQ(found, ret) << "Found " << found->PrettyField() << " vs " << ret->PrettyField();
974 }
975 return ret;
976 }
977
FindDeclaredInstanceField(std::string_view name,std::string_view type)978 ArtField* Class::FindDeclaredInstanceField(std::string_view name, std::string_view type) {
979 // Binary search by name. Interfaces are not relevant because they can't contain instance fields.
980 return FindFieldByNameAndType(GetIFieldsPtr(), name, type);
981 }
982
FindDeclaredInstanceField(ObjPtr<DexCache> dex_cache,uint32_t dex_field_idx)983 ArtField* Class::FindDeclaredInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
984 if (GetDexCache() == dex_cache) {
985 for (ArtField& field : GetIFields()) {
986 if (field.GetDexFieldIndex() == dex_field_idx) {
987 return &field;
988 }
989 }
990 }
991 return nullptr;
992 }
993
FindInstanceField(std::string_view name,std::string_view type)994 ArtField* Class::FindInstanceField(std::string_view name, std::string_view type) {
995 // Is the field in this class, or any of its superclasses?
996 // Interfaces are not relevant because they can't contain instance fields.
997 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
998 ArtField* f = c->FindDeclaredInstanceField(name, type);
999 if (f != nullptr) {
1000 return f;
1001 }
1002 }
1003 return nullptr;
1004 }
1005
FindInstanceField(ObjPtr<DexCache> dex_cache,uint32_t dex_field_idx)1006 ArtField* Class::FindInstanceField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
1007 // Is the field in this class, or any of its superclasses?
1008 // Interfaces are not relevant because they can't contain instance fields.
1009 for (ObjPtr<Class> c = this; c != nullptr; c = c->GetSuperClass()) {
1010 ArtField* f = c->FindDeclaredInstanceField(dex_cache, dex_field_idx);
1011 if (f != nullptr) {
1012 return f;
1013 }
1014 }
1015 return nullptr;
1016 }
1017
FindDeclaredStaticField(std::string_view name,std::string_view type)1018 ArtField* Class::FindDeclaredStaticField(std::string_view name, std::string_view type) {
1019 DCHECK(!type.empty());
1020 return FindFieldByNameAndType(GetSFieldsPtr(), name, type);
1021 }
1022
FindDeclaredStaticField(ObjPtr<DexCache> dex_cache,uint32_t dex_field_idx)1023 ArtField* Class::FindDeclaredStaticField(ObjPtr<DexCache> dex_cache, uint32_t dex_field_idx) {
1024 if (dex_cache == GetDexCache()) {
1025 for (ArtField& field : GetSFields()) {
1026 if (field.GetDexFieldIndex() == dex_field_idx) {
1027 return &field;
1028 }
1029 }
1030 }
1031 return nullptr;
1032 }
1033
FindStaticField(Thread * self,ObjPtr<Class> klass,std::string_view name,std::string_view type)1034 ArtField* Class::FindStaticField(Thread* self,
1035 ObjPtr<Class> klass,
1036 std::string_view name,
1037 std::string_view type) {
1038 // Is the field in this class (or its interfaces), or any of its
1039 // superclasses (or their interfaces)?
1040 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
1041 // Is the field in this class?
1042 ArtField* f = k->FindDeclaredStaticField(name, type);
1043 if (f != nullptr) {
1044 return f;
1045 }
1046 // Is this field in any of this class' interfaces?
1047 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
1048 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
1049 DCHECK(interface != nullptr);
1050 f = FindStaticField(self, interface, name, type);
1051 if (f != nullptr) {
1052 return f;
1053 }
1054 }
1055 }
1056 return nullptr;
1057 }
1058
FindStaticField(Thread * self,ObjPtr<Class> klass,ObjPtr<DexCache> dex_cache,uint32_t dex_field_idx)1059 ArtField* Class::FindStaticField(Thread* self,
1060 ObjPtr<Class> klass,
1061 ObjPtr<DexCache> dex_cache,
1062 uint32_t dex_field_idx) {
1063 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
1064 // Is the field in this class?
1065 ArtField* f = k->FindDeclaredStaticField(dex_cache, dex_field_idx);
1066 if (f != nullptr) {
1067 return f;
1068 }
1069 // Though GetDirectInterface() should not cause thread suspension when called
1070 // from here, it takes a Handle as an argument, so we need to wrap `k`.
1071 ScopedAssertNoThreadSuspension ants(__FUNCTION__);
1072 // Is this field in any of this class' interfaces?
1073 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
1074 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
1075 DCHECK(interface != nullptr);
1076 f = FindStaticField(self, interface, dex_cache, dex_field_idx);
1077 if (f != nullptr) {
1078 return f;
1079 }
1080 }
1081 }
1082 return nullptr;
1083 }
1084
FindField(Thread * self,ObjPtr<Class> klass,std::string_view name,std::string_view type)1085 ArtField* Class::FindField(Thread* self,
1086 ObjPtr<Class> klass,
1087 std::string_view name,
1088 std::string_view type) {
1089 // Find a field using the JLS field resolution order
1090 for (ObjPtr<Class> k = klass; k != nullptr; k = k->GetSuperClass()) {
1091 // Is the field in this class?
1092 ArtField* f = k->FindDeclaredInstanceField(name, type);
1093 if (f != nullptr) {
1094 return f;
1095 }
1096 f = k->FindDeclaredStaticField(name, type);
1097 if (f != nullptr) {
1098 return f;
1099 }
1100 // Is this field in any of this class' interfaces?
1101 for (uint32_t i = 0, num_interfaces = k->NumDirectInterfaces(); i != num_interfaces; ++i) {
1102 ObjPtr<Class> interface = GetDirectInterface(self, k, i);
1103 DCHECK(interface != nullptr);
1104 f = FindStaticField(self, interface, name, type);
1105 if (f != nullptr) {
1106 return f;
1107 }
1108 }
1109 }
1110 return nullptr;
1111 }
1112
ClearSkipAccessChecksFlagOnAllMethods(PointerSize pointer_size)1113 void Class::ClearSkipAccessChecksFlagOnAllMethods(PointerSize pointer_size) {
1114 DCHECK(IsVerified());
1115 for (auto& m : GetMethods(pointer_size)) {
1116 if (!m.IsNative() && m.IsInvokable()) {
1117 m.ClearSkipAccessChecks();
1118 }
1119 }
1120 }
1121
ClearMustCountLocksFlagOnAllMethods(PointerSize pointer_size)1122 void Class::ClearMustCountLocksFlagOnAllMethods(PointerSize pointer_size) {
1123 DCHECK(IsVerified());
1124 for (auto& m : GetMethods(pointer_size)) {
1125 if (!m.IsNative() && m.IsInvokable()) {
1126 m.ClearMustCountLocks();
1127 }
1128 }
1129 }
1130
ClearDontCompileFlagOnAllMethods(PointerSize pointer_size)1131 void Class::ClearDontCompileFlagOnAllMethods(PointerSize pointer_size) {
1132 DCHECK(IsVerified());
1133 for (auto& m : GetMethods(pointer_size)) {
1134 if (!m.IsNative() && m.IsInvokable()) {
1135 m.ClearDontCompile();
1136 }
1137 }
1138 }
1139
SetSkipAccessChecksFlagOnAllMethods(PointerSize pointer_size)1140 void Class::SetSkipAccessChecksFlagOnAllMethods(PointerSize pointer_size) {
1141 DCHECK(IsVerified());
1142 for (auto& m : GetMethods(pointer_size)) {
1143 if (!m.IsNative() && m.IsInvokable()) {
1144 m.SetSkipAccessChecks();
1145 }
1146 }
1147 }
1148
GetDescriptor(std::string * storage)1149 const char* Class::GetDescriptor(std::string* storage) {
1150 size_t dim = 0u;
1151 ObjPtr<mirror::Class> klass = this;
1152 while (klass->IsArrayClass()) {
1153 ++dim;
1154 // No read barrier needed, we're reading a chain of constant references for comparison
1155 // with null. Then we follow up below with reading constant references to read constant
1156 // primitive data in both proxy and non-proxy paths. See ReadBarrierOption.
1157 klass = klass->GetComponentType<kDefaultVerifyFlags, kWithoutReadBarrier>();
1158 }
1159 if (klass->IsProxyClass()) {
1160 // No read barrier needed, the `name` field is constant for proxy classes and
1161 // the contents of the String are also constant. See ReadBarrierOption.
1162 ObjPtr<mirror::String> name = klass->GetName<kVerifyNone, kWithoutReadBarrier>();
1163 DCHECK(name != nullptr);
1164 *storage = DotToDescriptor(name->ToModifiedUtf8().c_str());
1165 } else {
1166 const char* descriptor;
1167 if (klass->IsPrimitive()) {
1168 descriptor = Primitive::Descriptor(klass->GetPrimitiveType());
1169 } else {
1170 const DexFile& dex_file = klass->GetDexFile();
1171 const dex::TypeId& type_id = dex_file.GetTypeId(klass->GetDexTypeIndex());
1172 descriptor = dex_file.GetTypeDescriptor(type_id);
1173 }
1174 if (dim == 0) {
1175 return descriptor;
1176 }
1177 *storage = descriptor;
1178 }
1179 storage->insert(0u, dim, '[');
1180 return storage->c_str();
1181 }
1182
GetClassDef()1183 const dex::ClassDef* Class::GetClassDef() {
1184 uint16_t class_def_idx = GetDexClassDefIndex();
1185 if (class_def_idx == DexFile::kDexNoIndex16) {
1186 return nullptr;
1187 }
1188 return &GetDexFile().GetClassDef(class_def_idx);
1189 }
1190
GetDirectInterfaceTypeIdx(uint32_t idx)1191 dex::TypeIndex Class::GetDirectInterfaceTypeIdx(uint32_t idx) {
1192 DCHECK(!IsPrimitive());
1193 DCHECK(!IsArrayClass());
1194 return GetInterfaceTypeList()->GetTypeItem(idx).type_idx_;
1195 }
1196
GetDirectInterface(Thread * self,ObjPtr<Class> klass,uint32_t idx)1197 ObjPtr<Class> Class::GetDirectInterface(Thread* self, ObjPtr<Class> klass, uint32_t idx) {
1198 DCHECK(klass != nullptr);
1199 DCHECK(!klass->IsPrimitive());
1200 if (klass->IsArrayClass()) {
1201 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1202 // Use ClassLinker::LookupClass(); avoid poisoning ObjPtr<>s by ClassLinker::FindSystemClass().
1203 ObjPtr<Class> interface;
1204 if (idx == 0) {
1205 interface = class_linker->LookupClass(self, "Ljava/lang/Cloneable;", nullptr);
1206 } else {
1207 DCHECK_EQ(1U, idx);
1208 interface = class_linker->LookupClass(self, "Ljava/io/Serializable;", nullptr);
1209 }
1210 DCHECK(interface != nullptr);
1211 return interface;
1212 } else if (klass->IsProxyClass()) {
1213 ObjPtr<ObjectArray<Class>> interfaces = klass->GetProxyInterfaces();
1214 DCHECK(interfaces != nullptr);
1215 return interfaces->Get(idx);
1216 } else {
1217 dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
1218 ObjPtr<Class> interface = Runtime::Current()->GetClassLinker()->LookupResolvedType(
1219 type_idx, klass->GetDexCache(), klass->GetClassLoader());
1220 return interface;
1221 }
1222 }
1223
ResolveDirectInterface(Thread * self,Handle<Class> klass,uint32_t idx)1224 ObjPtr<Class> Class::ResolveDirectInterface(Thread* self, Handle<Class> klass, uint32_t idx) {
1225 ObjPtr<Class> interface = GetDirectInterface(self, klass.Get(), idx);
1226 if (interface == nullptr) {
1227 DCHECK(!klass->IsArrayClass());
1228 DCHECK(!klass->IsProxyClass());
1229 dex::TypeIndex type_idx = klass->GetDirectInterfaceTypeIdx(idx);
1230 interface = Runtime::Current()->GetClassLinker()->ResolveType(type_idx, klass.Get());
1231 CHECK(interface != nullptr || self->IsExceptionPending());
1232 }
1233 return interface;
1234 }
1235
GetCommonSuperClass(Handle<Class> klass)1236 ObjPtr<Class> Class::GetCommonSuperClass(Handle<Class> klass) {
1237 DCHECK(klass != nullptr);
1238 DCHECK(!klass->IsInterface());
1239 DCHECK(!IsInterface());
1240 ObjPtr<Class> common_super_class = this;
1241 while (!common_super_class->IsAssignableFrom(klass.Get())) {
1242 ObjPtr<Class> old_common = common_super_class;
1243 common_super_class = old_common->GetSuperClass();
1244 DCHECK(common_super_class != nullptr) << old_common->PrettyClass();
1245 }
1246 return common_super_class;
1247 }
1248
GetSourceFile()1249 const char* Class::GetSourceFile() {
1250 const DexFile& dex_file = GetDexFile();
1251 const dex::ClassDef* dex_class_def = GetClassDef();
1252 if (dex_class_def == nullptr) {
1253 // Generated classes have no class def.
1254 return nullptr;
1255 }
1256 return dex_file.GetSourceFile(*dex_class_def);
1257 }
1258
GetLocation()1259 std::string Class::GetLocation() {
1260 ObjPtr<DexCache> dex_cache = GetDexCache();
1261 if (dex_cache != nullptr && !IsProxyClass()) {
1262 return dex_cache->GetLocation()->ToModifiedUtf8();
1263 }
1264 // Arrays and proxies are generated and have no corresponding dex file location.
1265 return "generated class";
1266 }
1267
GetInterfaceTypeList()1268 const dex::TypeList* Class::GetInterfaceTypeList() {
1269 const dex::ClassDef* class_def = GetClassDef();
1270 if (class_def == nullptr) {
1271 return nullptr;
1272 }
1273 return GetDexFile().GetInterfacesList(*class_def);
1274 }
1275
PopulateEmbeddedVTable(PointerSize pointer_size)1276 void Class::PopulateEmbeddedVTable(PointerSize pointer_size) {
1277 ObjPtr<PointerArray> table = GetVTableDuringLinking();
1278 CHECK(table != nullptr) << PrettyClass();
1279 const size_t table_length = table->GetLength();
1280 SetEmbeddedVTableLength(table_length);
1281 for (size_t i = 0; i < table_length; i++) {
1282 SetEmbeddedVTableEntry(i, table->GetElementPtrSize<ArtMethod*>(i, pointer_size), pointer_size);
1283 }
1284 // Keep java.lang.Object class's vtable around for since it's easier
1285 // to be reused by array classes during their linking.
1286 if (!IsObjectClass()) {
1287 SetVTable(nullptr);
1288 }
1289 }
1290
1291 class ReadBarrierOnNativeRootsVisitor {
1292 public:
operator ()(ObjPtr<Object> obj ATTRIBUTE_UNUSED,MemberOffset offset ATTRIBUTE_UNUSED,bool is_static ATTRIBUTE_UNUSED) const1293 void operator()(ObjPtr<Object> obj ATTRIBUTE_UNUSED,
1294 MemberOffset offset ATTRIBUTE_UNUSED,
1295 bool is_static ATTRIBUTE_UNUSED) const {}
1296
VisitRootIfNonNull(CompressedReference<Object> * root) const1297 void VisitRootIfNonNull(CompressedReference<Object>* root) const
1298 REQUIRES_SHARED(Locks::mutator_lock_) {
1299 if (!root->IsNull()) {
1300 VisitRoot(root);
1301 }
1302 }
1303
VisitRoot(CompressedReference<Object> * root) const1304 void VisitRoot(CompressedReference<Object>* root) const
1305 REQUIRES_SHARED(Locks::mutator_lock_) {
1306 ObjPtr<Object> old_ref = root->AsMirrorPtr();
1307 ObjPtr<Object> new_ref = ReadBarrier::BarrierForRoot(root);
1308 if (old_ref != new_ref) {
1309 // Update the field atomically. This may fail if mutator updates before us, but it's ok.
1310 auto* atomic_root =
1311 reinterpret_cast<Atomic<CompressedReference<Object>>*>(root);
1312 atomic_root->CompareAndSetStrongSequentiallyConsistent(
1313 CompressedReference<Object>::FromMirrorPtr(old_ref.Ptr()),
1314 CompressedReference<Object>::FromMirrorPtr(new_ref.Ptr()));
1315 }
1316 }
1317 };
1318
1319 // The pre-fence visitor for Class::CopyOf().
1320 class CopyClassVisitor {
1321 public:
CopyClassVisitor(Thread * self,Handle<Class> * orig,size_t new_length,size_t copy_bytes,ImTable * imt,PointerSize pointer_size)1322 CopyClassVisitor(Thread* self,
1323 Handle<Class>* orig,
1324 size_t new_length,
1325 size_t copy_bytes,
1326 ImTable* imt,
1327 PointerSize pointer_size)
1328 : self_(self), orig_(orig), new_length_(new_length),
1329 copy_bytes_(copy_bytes), imt_(imt), pointer_size_(pointer_size) {
1330 }
1331
operator ()(ObjPtr<Object> obj,size_t usable_size ATTRIBUTE_UNUSED) const1332 void operator()(ObjPtr<Object> obj, size_t usable_size ATTRIBUTE_UNUSED) const
1333 REQUIRES_SHARED(Locks::mutator_lock_) {
1334 StackHandleScope<1> hs(self_);
1335 Handle<mirror::Class> h_new_class_obj(hs.NewHandle(obj->AsClass()));
1336 Object::CopyObject(h_new_class_obj.Get(), orig_->Get(), copy_bytes_);
1337 Class::SetStatus(h_new_class_obj, ClassStatus::kResolving, self_);
1338 h_new_class_obj->PopulateEmbeddedVTable(pointer_size_);
1339 h_new_class_obj->SetImt(imt_, pointer_size_);
1340 h_new_class_obj->SetClassSize(new_length_);
1341 // Visit all of the references to make sure there is no from space references in the native
1342 // roots.
1343 h_new_class_obj->Object::VisitReferences(ReadBarrierOnNativeRootsVisitor(), VoidFunctor());
1344 }
1345
1346 private:
1347 Thread* const self_;
1348 Handle<Class>* const orig_;
1349 const size_t new_length_;
1350 const size_t copy_bytes_;
1351 ImTable* imt_;
1352 const PointerSize pointer_size_;
1353 DISALLOW_COPY_AND_ASSIGN(CopyClassVisitor);
1354 };
1355
CopyOf(Handle<Class> h_this,Thread * self,int32_t new_length,ImTable * imt,PointerSize pointer_size)1356 ObjPtr<Class> Class::CopyOf(Handle<Class> h_this,
1357 Thread* self,
1358 int32_t new_length,
1359 ImTable* imt,
1360 PointerSize pointer_size) {
1361 DCHECK_GE(new_length, static_cast<int32_t>(sizeof(Class)));
1362 // We may get copied by a compacting GC.
1363 Runtime* runtime = Runtime::Current();
1364 gc::Heap* heap = runtime->GetHeap();
1365 // The num_bytes (3rd param) is sizeof(Class) as opposed to SizeOf()
1366 // to skip copying the tail part that we will overwrite here.
1367 CopyClassVisitor visitor(self, &h_this, new_length, sizeof(Class), imt, pointer_size);
1368 ObjPtr<mirror::Class> java_lang_Class = GetClassRoot<mirror::Class>(runtime->GetClassLinker());
1369 ObjPtr<Object> new_class = kMovingClasses ?
1370 heap->AllocObject(self, java_lang_Class, new_length, visitor) :
1371 heap->AllocNonMovableObject(self, java_lang_Class, new_length, visitor);
1372 if (UNLIKELY(new_class == nullptr)) {
1373 self->AssertPendingOOMException();
1374 return nullptr;
1375 }
1376 return new_class->AsClass();
1377 }
1378
ProxyDescriptorEquals(const char * match)1379 bool Class::ProxyDescriptorEquals(const char* match) {
1380 DCHECK(IsProxyClass());
1381 std::string storage;
1382 const char* descriptor = GetDescriptor(&storage);
1383 DCHECK(descriptor == storage.c_str());
1384 return storage == match;
1385 }
1386
1387 // TODO: Move this to java_lang_Class.cc?
GetDeclaredConstructor(Thread * self,Handle<ObjectArray<Class>> args,PointerSize pointer_size)1388 ArtMethod* Class::GetDeclaredConstructor(
1389 Thread* self, Handle<ObjectArray<Class>> args, PointerSize pointer_size) {
1390 for (auto& m : GetDirectMethods(pointer_size)) {
1391 // Skip <clinit> which is a static constructor, as well as non constructors.
1392 if (m.IsStatic() || !m.IsConstructor()) {
1393 continue;
1394 }
1395 // May cause thread suspension and exceptions.
1396 if (m.GetInterfaceMethodIfProxy(kRuntimePointerSize)->EqualParameters(args)) {
1397 return &m;
1398 }
1399 if (UNLIKELY(self->IsExceptionPending())) {
1400 return nullptr;
1401 }
1402 }
1403 return nullptr;
1404 }
1405
Depth()1406 uint32_t Class::Depth() {
1407 uint32_t depth = 0;
1408 for (ObjPtr<Class> cls = this; cls->GetSuperClass() != nullptr; cls = cls->GetSuperClass()) {
1409 depth++;
1410 }
1411 return depth;
1412 }
1413
FindTypeIndexInOtherDexFile(const DexFile & dex_file)1414 dex::TypeIndex Class::FindTypeIndexInOtherDexFile(const DexFile& dex_file) {
1415 std::string temp;
1416 const dex::TypeId* type_id = dex_file.FindTypeId(GetDescriptor(&temp));
1417 return (type_id == nullptr) ? dex::TypeIndex() : dex_file.GetIndexForTypeId(*type_id);
1418 }
1419
1420 ALWAYS_INLINE
IsMethodPreferredOver(ArtMethod * orig_method,bool orig_method_hidden,ArtMethod * new_method,bool new_method_hidden)1421 static bool IsMethodPreferredOver(ArtMethod* orig_method,
1422 bool orig_method_hidden,
1423 ArtMethod* new_method,
1424 bool new_method_hidden) {
1425 DCHECK(new_method != nullptr);
1426
1427 // Is this the first result?
1428 if (orig_method == nullptr) {
1429 return true;
1430 }
1431
1432 // Original method is hidden, the new one is not?
1433 if (orig_method_hidden && !new_method_hidden) {
1434 return true;
1435 }
1436
1437 // We iterate over virtual methods first and then over direct ones,
1438 // so we can never be in situation where `orig_method` is direct and
1439 // `new_method` is virtual.
1440 DCHECK(!orig_method->IsDirect() || new_method->IsDirect());
1441
1442 // Original method is synthetic, the new one is not?
1443 if (orig_method->IsSynthetic() && !new_method->IsSynthetic()) {
1444 return true;
1445 }
1446
1447 return false;
1448 }
1449
1450 template <PointerSize kPointerSize>
GetDeclaredMethodInternal(Thread * self,ObjPtr<Class> klass,ObjPtr<String> name,ObjPtr<ObjectArray<Class>> args,const std::function<hiddenapi::AccessContext ()> & fn_get_access_context)1451 ObjPtr<Method> Class::GetDeclaredMethodInternal(
1452 Thread* self,
1453 ObjPtr<Class> klass,
1454 ObjPtr<String> name,
1455 ObjPtr<ObjectArray<Class>> args,
1456 const std::function<hiddenapi::AccessContext()>& fn_get_access_context) {
1457 // Covariant return types (or smali) permit the class to define
1458 // multiple methods with the same name and parameter types.
1459 // Prefer (in decreasing order of importance):
1460 // 1) non-hidden method over hidden
1461 // 2) virtual methods over direct
1462 // 3) non-synthetic methods over synthetic
1463 // We never return miranda methods that were synthesized by the runtime.
1464 StackHandleScope<3> hs(self);
1465 auto h_method_name = hs.NewHandle(name);
1466 if (UNLIKELY(h_method_name == nullptr)) {
1467 ThrowNullPointerException("name == null");
1468 return nullptr;
1469 }
1470 auto h_args = hs.NewHandle(args);
1471 Handle<Class> h_klass = hs.NewHandle(klass);
1472 constexpr hiddenapi::AccessMethod access_method = hiddenapi::AccessMethod::kNone;
1473 ArtMethod* result = nullptr;
1474 bool result_hidden = false;
1475 for (auto& m : h_klass->GetDeclaredVirtualMethods(kPointerSize)) {
1476 if (m.IsMiranda()) {
1477 continue;
1478 }
1479 auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
1480 // May cause thread suspension.
1481 ObjPtr<String> np_name = np_method->ResolveNameString();
1482 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
1483 if (UNLIKELY(self->IsExceptionPending())) {
1484 return nullptr;
1485 }
1486 continue;
1487 }
1488 bool m_hidden = hiddenapi::ShouldDenyAccessToMember(&m, fn_get_access_context, access_method);
1489 if (!m_hidden && !m.IsSynthetic()) {
1490 // Non-hidden, virtual, non-synthetic. Best possible result, exit early.
1491 return Method::CreateFromArtMethod<kPointerSize>(self, &m);
1492 } else if (IsMethodPreferredOver(result, result_hidden, &m, m_hidden)) {
1493 // Remember as potential result.
1494 result = &m;
1495 result_hidden = m_hidden;
1496 }
1497 }
1498
1499 if ((result != nullptr) && !result_hidden) {
1500 // We have not found a non-hidden, virtual, non-synthetic method, but
1501 // if we have found a non-hidden, virtual, synthetic method, we cannot
1502 // do better than that later.
1503 DCHECK(!result->IsDirect());
1504 DCHECK(result->IsSynthetic());
1505 } else {
1506 for (auto& m : h_klass->GetDirectMethods(kPointerSize)) {
1507 auto modifiers = m.GetAccessFlags();
1508 if ((modifiers & kAccConstructor) != 0) {
1509 continue;
1510 }
1511 auto* np_method = m.GetInterfaceMethodIfProxy(kPointerSize);
1512 // May cause thread suspension.
1513 ObjPtr<String> np_name = np_method->ResolveNameString();
1514 if (np_name == nullptr) {
1515 self->AssertPendingException();
1516 return nullptr;
1517 }
1518 if (!np_name->Equals(h_method_name.Get()) || !np_method->EqualParameters(h_args)) {
1519 if (UNLIKELY(self->IsExceptionPending())) {
1520 return nullptr;
1521 }
1522 continue;
1523 }
1524 DCHECK(!m.IsMiranda()); // Direct methods cannot be miranda methods.
1525 bool m_hidden = hiddenapi::ShouldDenyAccessToMember(&m, fn_get_access_context, access_method);
1526 if (!m_hidden && !m.IsSynthetic()) {
1527 // Non-hidden, direct, non-synthetic. Any virtual result could only have been
1528 // hidden, therefore this is the best possible match. Exit now.
1529 DCHECK((result == nullptr) || result_hidden);
1530 return Method::CreateFromArtMethod<kPointerSize>(self, &m);
1531 } else if (IsMethodPreferredOver(result, result_hidden, &m, m_hidden)) {
1532 // Remember as potential result.
1533 result = &m;
1534 result_hidden = m_hidden;
1535 }
1536 }
1537 }
1538
1539 return result != nullptr
1540 ? Method::CreateFromArtMethod<kPointerSize>(self, result)
1541 : nullptr;
1542 }
1543
1544 template
1545 ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k32>(
1546 Thread* self,
1547 ObjPtr<Class> klass,
1548 ObjPtr<String> name,
1549 ObjPtr<ObjectArray<Class>> args,
1550 const std::function<hiddenapi::AccessContext()>& fn_get_access_context);
1551 template
1552 ObjPtr<Method> Class::GetDeclaredMethodInternal<PointerSize::k64>(
1553 Thread* self,
1554 ObjPtr<Class> klass,
1555 ObjPtr<String> name,
1556 ObjPtr<ObjectArray<Class>> args,
1557 const std::function<hiddenapi::AccessContext()>& fn_get_access_context);
1558
1559 template <PointerSize kPointerSize>
GetDeclaredConstructorInternal(Thread * self,ObjPtr<Class> klass,ObjPtr<ObjectArray<Class>> args)1560 ObjPtr<Constructor> Class::GetDeclaredConstructorInternal(
1561 Thread* self,
1562 ObjPtr<Class> klass,
1563 ObjPtr<ObjectArray<Class>> args) {
1564 StackHandleScope<1> hs(self);
1565 ArtMethod* result = klass->GetDeclaredConstructor(self, hs.NewHandle(args), kPointerSize);
1566 return result != nullptr
1567 ? Constructor::CreateFromArtMethod<kPointerSize>(self, result)
1568 : nullptr;
1569 }
1570
1571 // Constructor::CreateFromArtMethod<kTransactionActive>(self, result)
1572
1573 template
1574 ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k32>(
1575 Thread* self,
1576 ObjPtr<Class> klass,
1577 ObjPtr<ObjectArray<Class>> args);
1578 template
1579 ObjPtr<Constructor> Class::GetDeclaredConstructorInternal<PointerSize::k64>(
1580 Thread* self,
1581 ObjPtr<Class> klass,
1582 ObjPtr<ObjectArray<Class>> args);
1583
GetInnerClassFlags(Handle<Class> h_this,int32_t default_value)1584 int32_t Class::GetInnerClassFlags(Handle<Class> h_this, int32_t default_value) {
1585 if (h_this->IsProxyClass() || h_this->GetDexCache() == nullptr) {
1586 return default_value;
1587 }
1588 uint32_t flags;
1589 if (!annotations::GetInnerClassFlags(h_this, &flags)) {
1590 return default_value;
1591 }
1592 return flags;
1593 }
1594
SetObjectSizeAllocFastPath(uint32_t new_object_size)1595 void Class::SetObjectSizeAllocFastPath(uint32_t new_object_size) {
1596 if (Runtime::Current()->IsActiveTransaction()) {
1597 SetField32Volatile<true>(ObjectSizeAllocFastPathOffset(), new_object_size);
1598 } else {
1599 SetField32Volatile<false>(ObjectSizeAllocFastPathOffset(), new_object_size);
1600 }
1601 }
1602
PrettyDescriptor(ObjPtr<mirror::Class> klass)1603 std::string Class::PrettyDescriptor(ObjPtr<mirror::Class> klass) {
1604 if (klass == nullptr) {
1605 return "null";
1606 }
1607 return klass->PrettyDescriptor();
1608 }
1609
PrettyDescriptor()1610 std::string Class::PrettyDescriptor() {
1611 std::string temp;
1612 return art::PrettyDescriptor(GetDescriptor(&temp));
1613 }
1614
PrettyClass(ObjPtr<mirror::Class> c)1615 std::string Class::PrettyClass(ObjPtr<mirror::Class> c) {
1616 if (c == nullptr) {
1617 return "null";
1618 }
1619 return c->PrettyClass();
1620 }
1621
PrettyClass()1622 std::string Class::PrettyClass() {
1623 std::string result;
1624 if (IsObsoleteObject()) {
1625 result += "(Obsolete)";
1626 }
1627 if (IsRetired()) {
1628 result += "(Retired)";
1629 }
1630 result += "java.lang.Class<";
1631 result += PrettyDescriptor();
1632 result += ">";
1633 return result;
1634 }
1635
PrettyClassAndClassLoader(ObjPtr<mirror::Class> c)1636 std::string Class::PrettyClassAndClassLoader(ObjPtr<mirror::Class> c) {
1637 if (c == nullptr) {
1638 return "null";
1639 }
1640 return c->PrettyClassAndClassLoader();
1641 }
1642
PrettyClassAndClassLoader()1643 std::string Class::PrettyClassAndClassLoader() {
1644 std::string result;
1645 result += "java.lang.Class<";
1646 result += PrettyDescriptor();
1647 result += ",";
1648 result += mirror::Object::PrettyTypeOf(GetClassLoader());
1649 // TODO: add an identifying hash value for the loader
1650 result += ">";
1651 return result;
1652 }
1653
GetAccessFlagsDCheck()1654 template<VerifyObjectFlags kVerifyFlags> void Class::GetAccessFlagsDCheck() {
1655 // Check class is loaded/retired or this is java.lang.String that has a
1656 // circularity issue during loading the names of its members
1657 DCHECK(IsIdxLoaded<kVerifyFlags>() || IsRetired<kVerifyFlags>() ||
1658 IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>() ||
1659 this == GetClassRoot<String>())
1660 << "IsIdxLoaded=" << IsIdxLoaded<kVerifyFlags>()
1661 << " IsRetired=" << IsRetired<kVerifyFlags>()
1662 << " IsErroneous=" <<
1663 IsErroneous<static_cast<VerifyObjectFlags>(kVerifyFlags & ~kVerifyThis)>()
1664 << " IsString=" << (this == GetClassRoot<String>())
1665 << " status= " << GetStatus<kVerifyFlags>()
1666 << " descriptor=" << PrettyDescriptor();
1667 }
1668 // Instantiate the common cases.
1669 template void Class::GetAccessFlagsDCheck<kVerifyNone>();
1670 template void Class::GetAccessFlagsDCheck<kVerifyThis>();
1671 template void Class::GetAccessFlagsDCheck<kVerifyReads>();
1672 template void Class::GetAccessFlagsDCheck<kVerifyWrites>();
1673 template void Class::GetAccessFlagsDCheck<kVerifyAll>();
1674
SetAccessFlagsDCheck(uint32_t new_access_flags)1675 void Class::SetAccessFlagsDCheck(uint32_t new_access_flags) {
1676 uint32_t old_access_flags = GetField32<kVerifyNone>(AccessFlagsOffset());
1677 // kAccVerificationAttempted is retained.
1678 CHECK((old_access_flags & kAccVerificationAttempted) == 0 ||
1679 (new_access_flags & kAccVerificationAttempted) != 0);
1680 }
1681
GetMethodIds()1682 ObjPtr<Object> Class::GetMethodIds() {
1683 ObjPtr<ClassExt> ext(GetExtData());
1684 if (ext.IsNull()) {
1685 return nullptr;
1686 } else {
1687 return ext->GetJMethodIDs();
1688 }
1689 }
EnsureMethodIds(Handle<Class> h_this)1690 bool Class::EnsureMethodIds(Handle<Class> h_this) {
1691 DCHECK_NE(Runtime::Current()->GetJniIdType(), JniIdType::kPointer) << "JNI Ids are pointers!";
1692 Thread* self = Thread::Current();
1693 ObjPtr<ClassExt> ext(EnsureExtDataPresent(h_this, self));
1694 if (ext.IsNull()) {
1695 self->AssertPendingOOMException();
1696 return false;
1697 }
1698 return ext->EnsureJMethodIDsArrayPresent(h_this->NumMethods());
1699 }
1700
GetStaticFieldIds()1701 ObjPtr<Object> Class::GetStaticFieldIds() {
1702 ObjPtr<ClassExt> ext(GetExtData());
1703 if (ext.IsNull()) {
1704 return nullptr;
1705 } else {
1706 return ext->GetStaticJFieldIDs();
1707 }
1708 }
EnsureStaticFieldIds(Handle<Class> h_this)1709 bool Class::EnsureStaticFieldIds(Handle<Class> h_this) {
1710 DCHECK_NE(Runtime::Current()->GetJniIdType(), JniIdType::kPointer) << "JNI Ids are pointers!";
1711 Thread* self = Thread::Current();
1712 ObjPtr<ClassExt> ext(EnsureExtDataPresent(h_this, self));
1713 if (ext.IsNull()) {
1714 self->AssertPendingOOMException();
1715 return false;
1716 }
1717 return ext->EnsureStaticJFieldIDsArrayPresent(h_this->NumStaticFields());
1718 }
GetInstanceFieldIds()1719 ObjPtr<Object> Class::GetInstanceFieldIds() {
1720 ObjPtr<ClassExt> ext(GetExtData());
1721 if (ext.IsNull()) {
1722 return nullptr;
1723 } else {
1724 return ext->GetInstanceJFieldIDs();
1725 }
1726 }
EnsureInstanceFieldIds(Handle<Class> h_this)1727 bool Class::EnsureInstanceFieldIds(Handle<Class> h_this) {
1728 DCHECK_NE(Runtime::Current()->GetJniIdType(), JniIdType::kPointer) << "JNI Ids are pointers!";
1729 Thread* self = Thread::Current();
1730 ObjPtr<ClassExt> ext(EnsureExtDataPresent(h_this, self));
1731 if (ext.IsNull()) {
1732 self->AssertPendingOOMException();
1733 return false;
1734 }
1735 return ext->EnsureInstanceJFieldIDsArrayPresent(h_this->NumInstanceFields());
1736 }
1737
GetStaticFieldIdOffset(ArtField * field)1738 size_t Class::GetStaticFieldIdOffset(ArtField* field) {
1739 DCHECK_LT(reinterpret_cast<uintptr_t>(field),
1740 reinterpret_cast<uintptr_t>(&*GetSFieldsPtr()->end()))
1741 << "field not part of the current class. " << field->PrettyField() << " class is "
1742 << PrettyClass();
1743 DCHECK_GE(reinterpret_cast<uintptr_t>(field),
1744 reinterpret_cast<uintptr_t>(&*GetSFieldsPtr()->begin()))
1745 << "field not part of the current class. " << field->PrettyField() << " class is "
1746 << PrettyClass();
1747 uintptr_t start = reinterpret_cast<uintptr_t>(&GetSFieldsPtr()->At(0));
1748 uintptr_t fld = reinterpret_cast<uintptr_t>(field);
1749 size_t res = (fld - start) / sizeof(ArtField);
1750 DCHECK_EQ(&GetSFieldsPtr()->At(res), field)
1751 << "Incorrect field computation expected: " << field->PrettyField()
1752 << " got: " << GetSFieldsPtr()->At(res).PrettyField();
1753 return res;
1754 }
1755
GetInstanceFieldIdOffset(ArtField * field)1756 size_t Class::GetInstanceFieldIdOffset(ArtField* field) {
1757 DCHECK_LT(reinterpret_cast<uintptr_t>(field),
1758 reinterpret_cast<uintptr_t>(&*GetIFieldsPtr()->end()))
1759 << "field not part of the current class. " << field->PrettyField() << " class is "
1760 << PrettyClass();
1761 DCHECK_GE(reinterpret_cast<uintptr_t>(field),
1762 reinterpret_cast<uintptr_t>(&*GetIFieldsPtr()->begin()))
1763 << "field not part of the current class. " << field->PrettyField() << " class is "
1764 << PrettyClass();
1765 uintptr_t start = reinterpret_cast<uintptr_t>(&GetIFieldsPtr()->At(0));
1766 uintptr_t fld = reinterpret_cast<uintptr_t>(field);
1767 size_t res = (fld - start) / sizeof(ArtField);
1768 DCHECK_EQ(&GetIFieldsPtr()->At(res), field)
1769 << "Incorrect field computation expected: " << field->PrettyField()
1770 << " got: " << GetIFieldsPtr()->At(res).PrettyField();
1771 return res;
1772 }
1773
GetMethodIdOffset(ArtMethod * method,PointerSize pointer_size)1774 size_t Class::GetMethodIdOffset(ArtMethod* method, PointerSize pointer_size) {
1775 DCHECK(GetMethodsSlice(kRuntimePointerSize).Contains(method))
1776 << "method not part of the current class. " << method->PrettyMethod() << "( " << reinterpret_cast<void*>(method) << ")" << " class is "
1777 << PrettyClass() << [&]() REQUIRES_SHARED(Locks::mutator_lock_) {
1778 std::ostringstream os;
1779 os << " Methods are [";
1780 for (ArtMethod& m : GetMethodsSlice(kRuntimePointerSize)) {
1781 os << m.PrettyMethod() << "( " << reinterpret_cast<void*>(&m) << "), ";
1782 }
1783 os << "]";
1784 return os.str();
1785 }();
1786 uintptr_t start = reinterpret_cast<uintptr_t>(&*GetMethodsSlice(pointer_size).begin());
1787 uintptr_t fld = reinterpret_cast<uintptr_t>(method);
1788 size_t art_method_size = ArtMethod::Size(pointer_size);
1789 size_t art_method_align = ArtMethod::Alignment(pointer_size);
1790 size_t res = (fld - start) / art_method_size;
1791 DCHECK_EQ(&GetMethodsPtr()->At(res, art_method_size, art_method_align), method)
1792 << "Incorrect method computation expected: " << method->PrettyMethod()
1793 << " got: " << GetMethodsPtr()->At(res, art_method_size, art_method_align).PrettyMethod();
1794 return res;
1795 }
1796
1797 } // namespace mirror
1798 } // namespace art
1799