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_linker.h"
18 
19 #include <memory>
20 #include <string>
21 #include <string_view>
22 
23 #include "android-base/strings.h"
24 
25 #include "art_field-inl.h"
26 #include "art_method-inl.h"
27 #include "base/pointer_size.h"
28 #include "class_linker-inl.h"
29 #include "class_root-inl.h"
30 #include "common_runtime_test.h"
31 #include "dex/dex_file_types.h"
32 #include "dex/signature-inl.h"
33 #include "dex/standard_dex_file.h"
34 #include "entrypoints/entrypoint_utils-inl.h"
35 #include "experimental_flags.h"
36 #include "gc/heap.h"
37 #include "handle_scope-inl.h"
38 #include "mirror/array-alloc-inl.h"
39 #include "mirror/accessible_object.h"
40 #include "mirror/call_site.h"
41 #include "mirror/class-inl.h"
42 #include "mirror/class_ext.h"
43 #include "mirror/dex_cache.h"
44 #include "mirror/emulated_stack_frame.h"
45 #include "mirror/executable.h"
46 #include "mirror/field.h"
47 #include "mirror/method_handle_impl.h"
48 #include "mirror/method_handles_lookup.h"
49 #include "mirror/method_type-inl.h"
50 #include "mirror/object-inl.h"
51 #include "mirror/object_array-alloc-inl.h"
52 #include "mirror/object_array-inl.h"
53 #include "mirror/proxy.h"
54 #include "mirror/reference.h"
55 #include "mirror/stack_frame_info.h"
56 #include "mirror/stack_trace_element.h"
57 #include "mirror/string-inl.h"
58 #include "mirror/var_handle.h"
59 #include "scoped_thread_state_change-inl.h"
60 #include "thread-current-inl.h"
61 
62 namespace art HIDDEN {
63 
64 class ClassLinkerTest : public CommonRuntimeTest {
65  protected:
AssertNonExistentClass(const std::string & descriptor)66   void AssertNonExistentClass(const std::string& descriptor)
67       REQUIRES_SHARED(Locks::mutator_lock_) {
68     Thread* self = Thread::Current();
69     EXPECT_TRUE(class_linker_->FindSystemClass(self, descriptor.c_str()) == nullptr);
70     EXPECT_TRUE(self->IsExceptionPending());
71     StackHandleScope<1> hs(self);
72     Handle<mirror::Object> exception = hs.NewHandle<mirror::Object>(self->GetException());
73     self->ClearException();
74     ObjPtr<mirror::Class> exception_class =
75         class_linker_->FindSystemClass(self, "Ljava/lang/NoClassDefFoundError;");
76     EXPECT_TRUE(exception->InstanceOf(exception_class));
77   }
78 
AssertPrimitiveClass(const std::string & descriptor)79   void AssertPrimitiveClass(const std::string& descriptor)
80       REQUIRES_SHARED(Locks::mutator_lock_) {
81     Thread* self = Thread::Current();
82     AssertPrimitiveClass(descriptor, class_linker_->FindSystemClass(self, descriptor.c_str()));
83   }
84 
AssertPrimitiveClass(const std::string & descriptor,ObjPtr<mirror::Class> primitive)85   void AssertPrimitiveClass(const std::string& descriptor, ObjPtr<mirror::Class> primitive)
86       REQUIRES_SHARED(Locks::mutator_lock_) {
87     ASSERT_TRUE(primitive != nullptr);
88     ASSERT_TRUE(primitive->GetClass() != nullptr);
89     ASSERT_OBJ_PTR_EQ(primitive->GetClass(), primitive->GetClass()->GetClass());
90     EXPECT_TRUE(primitive->GetClass()->GetSuperClass() != nullptr);
91     std::string temp;
92     ASSERT_STREQ(descriptor.c_str(), primitive->GetDescriptor(&temp));
93     EXPECT_TRUE(primitive->GetSuperClass() == nullptr);
94     EXPECT_FALSE(primitive->HasSuperClass());
95     EXPECT_TRUE(primitive->GetClassLoader() == nullptr);
96     EXPECT_EQ(ClassStatus::kVisiblyInitialized, primitive->GetStatus());
97     EXPECT_FALSE(primitive->IsErroneous());
98     EXPECT_TRUE(primitive->IsLoaded());
99     EXPECT_TRUE(primitive->IsResolved());
100     EXPECT_FALSE(primitive->IsErroneousResolved());
101     EXPECT_TRUE(primitive->IsVerified());
102     EXPECT_TRUE(primitive->IsInitialized());
103     EXPECT_FALSE(primitive->IsArrayInstance());
104     EXPECT_FALSE(primitive->IsArrayClass());
105     EXPECT_TRUE(primitive->GetComponentType() == nullptr);
106     EXPECT_FALSE(primitive->IsInterface());
107     EXPECT_TRUE(primitive->IsPublic());
108     EXPECT_TRUE(primitive->IsFinal());
109     EXPECT_TRUE(primitive->IsPrimitive());
110     EXPECT_FALSE(primitive->IsSynthetic());
111     EXPECT_EQ(0U, primitive->NumDirectMethods());
112     EXPECT_EQ(0U, primitive->NumVirtualMethods());
113     EXPECT_EQ(0U, primitive->NumInstanceFields());
114     EXPECT_EQ(0U, primitive->NumStaticFields());
115     EXPECT_EQ(0U, primitive->NumDirectInterfaces());
116     EXPECT_FALSE(primitive->HasVTable());
117     EXPECT_EQ(0, primitive->GetIfTableCount());
118     EXPECT_TRUE(primitive->GetIfTable() != nullptr);
119     EXPECT_EQ(primitive->GetIfTable()->Count(), 0u);
120     EXPECT_EQ(kAccPublic | kAccFinal | kAccAbstract, primitive->GetAccessFlags());
121   }
122 
AssertObjectClass(ObjPtr<mirror::Class> JavaLangObject)123   void AssertObjectClass(ObjPtr<mirror::Class> JavaLangObject)
124       REQUIRES_SHARED(Locks::mutator_lock_) {
125     ASSERT_TRUE(JavaLangObject != nullptr);
126     ASSERT_TRUE(JavaLangObject->GetClass() != nullptr);
127     ASSERT_OBJ_PTR_EQ(JavaLangObject->GetClass(), JavaLangObject->GetClass()->GetClass());
128     EXPECT_OBJ_PTR_EQ(JavaLangObject, JavaLangObject->GetClass()->GetSuperClass());
129     std::string temp;
130     ASSERT_STREQ(JavaLangObject->GetDescriptor(&temp), "Ljava/lang/Object;");
131     EXPECT_TRUE(JavaLangObject->GetSuperClass() == nullptr);
132     EXPECT_FALSE(JavaLangObject->HasSuperClass());
133     EXPECT_TRUE(JavaLangObject->GetClassLoader() == nullptr);
134     {
135       Thread* self = Thread::Current();
136       StackHandleScope<1> hs(self);
137       HandleWrapperObjPtr<mirror::Class> h(hs.NewHandleWrapper(&JavaLangObject));
138       ScopedThreadSuspension sts(self, ThreadState::kNative);
139       class_linker_->MakeInitializedClassesVisiblyInitialized(self, /*wait=*/ true);
140       // HandleWrapperObjPtr restores JavaLangObject here after becoming runnable again.
141     }
142     EXPECT_EQ(ClassStatus::kVisiblyInitialized, JavaLangObject->GetStatus());
143     EXPECT_FALSE(JavaLangObject->IsErroneous());
144     EXPECT_TRUE(JavaLangObject->IsLoaded());
145     EXPECT_TRUE(JavaLangObject->IsResolved());
146     EXPECT_FALSE(JavaLangObject->IsErroneousResolved());
147     EXPECT_TRUE(JavaLangObject->IsVerified());
148     EXPECT_TRUE(JavaLangObject->IsInitialized());
149     EXPECT_FALSE(JavaLangObject->IsArrayInstance());
150     EXPECT_FALSE(JavaLangObject->IsArrayClass());
151     EXPECT_TRUE(JavaLangObject->GetComponentType() == nullptr);
152     EXPECT_FALSE(JavaLangObject->IsInterface());
153     EXPECT_TRUE(JavaLangObject->IsPublic());
154     EXPECT_FALSE(JavaLangObject->IsFinal());
155     EXPECT_FALSE(JavaLangObject->IsPrimitive());
156     EXPECT_FALSE(JavaLangObject->IsSynthetic());
157     EXPECT_EQ(4U, JavaLangObject->NumDirectMethods());
158     EXPECT_EQ(11U, JavaLangObject->NumVirtualMethods());
159     EXPECT_EQ(2U, JavaLangObject->NumInstanceFields());
160     EXPECT_STREQ(JavaLangObject->GetInstanceField(0)->GetName(),
161                  "shadow$_klass_");
162     EXPECT_STREQ(JavaLangObject->GetInstanceField(1)->GetName(),
163                  "shadow$_monitor_");
164 
165     EXPECT_EQ(0U, JavaLangObject->NumStaticFields());
166     EXPECT_EQ(0U, JavaLangObject->NumDirectInterfaces());
167 
168     PointerSize pointer_size = class_linker_->GetImagePointerSize();
169     ArtMethod* unimplemented = runtime_->GetImtUnimplementedMethod();
170     ImTable* imt = JavaLangObject->GetImt(pointer_size);
171     ASSERT_NE(nullptr, imt);
172     for (size_t i = 0; i < ImTable::kSize; ++i) {
173       ASSERT_EQ(unimplemented, imt->Get(i, pointer_size));
174     }
175   }
176 
AssertArrayClass(const std::string & array_descriptor,const std::string & component_type,ObjPtr<mirror::ClassLoader> class_loader)177   void AssertArrayClass(const std::string& array_descriptor,
178                         const std::string& component_type,
179                         ObjPtr<mirror::ClassLoader> class_loader)
180       REQUIRES_SHARED(Locks::mutator_lock_) {
181     Thread* self = Thread::Current();
182     StackHandleScope<2> hs(self);
183     Handle<mirror::ClassLoader> loader(hs.NewHandle(class_loader));
184     Handle<mirror::Class> array(
185         hs.NewHandle(class_linker_->FindClass(self, array_descriptor.c_str(), loader)));
186     std::string temp;
187     EXPECT_STREQ(component_type.c_str(), array->GetComponentType()->GetDescriptor(&temp));
188     EXPECT_OBJ_PTR_EQ(loader.Get(), array->GetClassLoader());
189     EXPECT_EQ(kAccFinal | kAccAbstract, (array->GetAccessFlags() & (kAccFinal | kAccAbstract)));
190     AssertArrayClass(array_descriptor, array);
191   }
192 
AssertArrayClass(const std::string & array_descriptor,Handle<mirror::Class> array)193   void AssertArrayClass(const std::string& array_descriptor, Handle<mirror::Class> array)
194       REQUIRES_SHARED(Locks::mutator_lock_) {
195     ASSERT_TRUE(array != nullptr);
196     ASSERT_TRUE(array->GetClass() != nullptr);
197     ASSERT_OBJ_PTR_EQ(array->GetClass(), array->GetClass()->GetClass());
198     EXPECT_TRUE(array->GetClass()->GetSuperClass() != nullptr);
199     std::string temp;
200     ASSERT_STREQ(array_descriptor.c_str(), array->GetDescriptor(&temp));
201     EXPECT_TRUE(array->GetSuperClass() != nullptr);
202     Thread* self = Thread::Current();
203     EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(self, "Ljava/lang/Object;"),
204                       array->GetSuperClass());
205     EXPECT_TRUE(array->HasSuperClass());
206     ASSERT_TRUE(array->GetComponentType() != nullptr);
207     ASSERT_GT(strlen(array->GetComponentType()->GetDescriptor(&temp)), 0U);
208     EXPECT_EQ(ClassStatus::kVisiblyInitialized, array->GetStatus());
209     EXPECT_FALSE(array->IsErroneous());
210     EXPECT_TRUE(array->IsLoaded());
211     EXPECT_TRUE(array->IsResolved());
212     EXPECT_FALSE(array->IsErroneousResolved());
213     EXPECT_TRUE(array->IsVerified());
214     EXPECT_TRUE(array->IsInitialized());
215     EXPECT_FALSE(array->IsArrayInstance());
216     EXPECT_TRUE(array->IsArrayClass());
217     EXPECT_FALSE(array->IsInterface());
218     EXPECT_EQ(array->GetComponentType()->IsPublic(), array->IsPublic());
219     EXPECT_TRUE(array->IsFinal());
220     EXPECT_FALSE(array->IsPrimitive());
221     EXPECT_FALSE(array->IsSynthetic());
222     EXPECT_EQ(0U, array->NumDirectMethods());
223     EXPECT_EQ(0U, array->NumVirtualMethods());
224     EXPECT_EQ(0U, array->NumInstanceFields());
225     EXPECT_EQ(0U, array->NumStaticFields());
226     EXPECT_EQ(2U, array->NumDirectInterfaces());
227     EXPECT_TRUE(array->ShouldHaveImt());
228     EXPECT_TRUE(array->ShouldHaveEmbeddedVTable());
229     EXPECT_EQ(2, array->GetIfTableCount());
230     ASSERT_TRUE(array->GetIfTable() != nullptr);
231     ObjPtr<mirror::Class> direct_interface0 = array->GetDirectInterface(0);
232     EXPECT_TRUE(direct_interface0 != nullptr);
233     EXPECT_STREQ(direct_interface0->GetDescriptor(&temp), "Ljava/lang/Cloneable;");
234     ObjPtr<mirror::Class> direct_interface1 = array->GetDirectInterface(1);
235     EXPECT_STREQ(direct_interface1->GetDescriptor(&temp), "Ljava/io/Serializable;");
236     EXPECT_OBJ_PTR_EQ(class_linker_->FindArrayClass(self, array->GetComponentType()), array.Get());
237 
238     PointerSize pointer_size = class_linker_->GetImagePointerSize();
239     ObjPtr<mirror::Class> JavaLangObject =
240         class_linker_->FindSystemClass(self, "Ljava/lang/Object;");
241     ImTable* JavaLangObject_imt = JavaLangObject->GetImt(pointer_size);
242     // IMT of a array class should be shared with the IMT of the java.lag.Object
243     ASSERT_EQ(JavaLangObject_imt, array->GetImt(pointer_size));
244   }
245 
AssertMethod(ArtMethod * method)246   void AssertMethod(ArtMethod* method) REQUIRES_SHARED(Locks::mutator_lock_) {
247     EXPECT_TRUE(method != nullptr);
248     EXPECT_TRUE(method->GetDeclaringClass() != nullptr);
249     EXPECT_TRUE(method->GetName() != nullptr);
250     EXPECT_TRUE(method->GetSignature() != Signature::NoSignature());
251   }
252 
AssertField(ObjPtr<mirror::Class> klass,ArtField * field)253   void AssertField(ObjPtr<mirror::Class> klass, ArtField* field)
254       REQUIRES_SHARED(Locks::mutator_lock_) {
255     EXPECT_TRUE(field != nullptr);
256     EXPECT_OBJ_PTR_EQ(klass, field->GetDeclaringClass());
257     EXPECT_TRUE(field->GetName() != nullptr);
258     EXPECT_TRUE(field->ResolveType() != nullptr);
259   }
260 
AssertClass(const std::string & descriptor,Handle<mirror::Class> klass)261   void AssertClass(const std::string& descriptor, Handle<mirror::Class> klass)
262       REQUIRES_SHARED(Locks::mutator_lock_) {
263     std::string temp;
264     EXPECT_STREQ(descriptor.c_str(), klass->GetDescriptor(&temp));
265     if (descriptor == "Ljava/lang/Object;") {
266       EXPECT_FALSE(klass->HasSuperClass());
267     } else {
268       EXPECT_TRUE(klass->HasSuperClass());
269       EXPECT_TRUE(klass->GetSuperClass() != nullptr);
270     }
271     EXPECT_TRUE(klass->GetClass() != nullptr);
272     EXPECT_OBJ_PTR_EQ(klass->GetClass(), klass->GetClass()->GetClass());
273     EXPECT_TRUE(klass->GetDexCache() != nullptr);
274     EXPECT_TRUE(klass->IsLoaded());
275     EXPECT_TRUE(klass->IsResolved());
276     EXPECT_FALSE(klass->IsErroneousResolved());
277     EXPECT_FALSE(klass->IsErroneous());
278     EXPECT_FALSE(klass->IsArrayClass());
279     EXPECT_TRUE(klass->GetComponentType() == nullptr);
280     EXPECT_TRUE(klass->IsInSamePackage(klass.Get()));
281     std::string temp2;
282     EXPECT_TRUE(mirror::Class::IsInSamePackage(klass->GetDescriptor(&temp),
283                                                klass->GetDescriptor(&temp2)));
284     if (klass->IsInterface()) {
285       EXPECT_TRUE(klass->IsAbstract());
286       // Check that all methods are direct and either static (<clinit> or a regular static method),
287       // or private.
288       for (ArtMethod& m : klass->GetDirectMethods(kRuntimePointerSize)) {
289         EXPECT_TRUE(m.IsStatic() || m.IsPrivate());
290         EXPECT_TRUE(m.IsDirect());
291       }
292     } else {
293       if (!klass->IsSynthetic()) {
294         EXPECT_NE(0U, klass->NumDirectMethods());
295       }
296     }
297     EXPECT_EQ(klass->IsInterface(), !klass->HasVTable());
298     ObjPtr<mirror::IfTable> iftable = klass->GetIfTable();
299     for (int i = 0; i < klass->GetIfTableCount(); i++) {
300       ObjPtr<mirror::Class> interface = iftable->GetInterface(i);
301       ASSERT_TRUE(interface != nullptr);
302       if (klass->IsInterface()) {
303         EXPECT_EQ(0U, iftable->GetMethodArrayCount(i));
304       } else {
305         EXPECT_EQ(interface->NumDeclaredVirtualMethods(), iftable->GetMethodArrayCount(i));
306       }
307     }
308     if (klass->IsAbstract()) {
309       EXPECT_FALSE(klass->IsFinal());
310     } else {
311       EXPECT_FALSE(klass->IsAnnotation());
312     }
313     if (klass->IsFinal()) {
314       EXPECT_FALSE(klass->IsAbstract());
315       EXPECT_FALSE(klass->IsAnnotation());
316     }
317     if (klass->IsAnnotation()) {
318       EXPECT_FALSE(klass->IsFinal());
319       EXPECT_TRUE(klass->IsAbstract());
320     }
321 
322     EXPECT_FALSE(klass->IsPrimitive());
323     EXPECT_TRUE(klass->CanAccess(klass.Get()));
324 
325     for (ArtMethod& method : klass->GetDirectMethods(kRuntimePointerSize)) {
326       AssertMethod(&method);
327       EXPECT_TRUE(method.IsDirect());
328       EXPECT_OBJ_PTR_EQ(klass.Get(), method.GetDeclaringClass());
329     }
330 
331     for (ArtMethod& method : klass->GetDeclaredVirtualMethods(kRuntimePointerSize)) {
332       AssertMethod(&method);
333       EXPECT_FALSE(method.IsDirect());
334       EXPECT_OBJ_PTR_EQ(klass.Get(), method.GetDeclaringClass());
335     }
336 
337     for (ArtMethod& method : klass->GetCopiedMethods(kRuntimePointerSize)) {
338       AssertMethod(&method);
339       EXPECT_FALSE(method.IsDirect());
340       EXPECT_TRUE(method.IsCopied());
341       EXPECT_TRUE(method.GetDeclaringClass()->IsInterface())
342           << "declaring class: " << method.GetDeclaringClass()->PrettyClass();
343       EXPECT_TRUE(method.GetDeclaringClass()->IsAssignableFrom(klass.Get()))
344           << "declaring class: " << method.GetDeclaringClass()->PrettyClass();
345     }
346 
347     for (size_t i = 0; i < klass->NumInstanceFields(); i++) {
348       ArtField* field = klass->GetInstanceField(i);
349       AssertField(klass.Get(), field);
350       EXPECT_FALSE(field->IsStatic());
351     }
352 
353     for (size_t i = 0; i < klass->NumStaticFields(); i++) {
354       ArtField* field = klass->GetStaticField(i);
355       AssertField(klass.Get(), field);
356       EXPECT_TRUE(field->IsStatic());
357     }
358 
359     // Confirm that all instances field offsets are packed together at the start.
360     EXPECT_GE(klass->NumInstanceFields(), klass->NumReferenceInstanceFields());
361     MemberOffset start_ref_offset = klass->GetFirstReferenceInstanceFieldOffset();
362     MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
363                                 klass->NumReferenceInstanceFields() *
364                                     sizeof(mirror::HeapReference<mirror::Object>));
365     MemberOffset current_ref_offset = start_ref_offset;
366     for (size_t i = 0; i < klass->NumInstanceFields(); i++) {
367       ArtField* field = klass->GetInstanceField(i);
368       ObjPtr<mirror::Class> field_type = field->ResolveType();
369       ASSERT_TRUE(field_type != nullptr);
370       if (!field->IsPrimitiveType()) {
371         ASSERT_TRUE(!field_type->IsPrimitive());
372         ASSERT_EQ(current_ref_offset.Uint32Value(), field->GetOffset().Uint32Value());
373         if (current_ref_offset.Uint32Value() == end_ref_offset.Uint32Value()) {
374           // While Reference.referent is not primitive, the ClassLinker
375           // treats it as such so that the garbage collector won't scan it.
376           EXPECT_EQ(field->PrettyField(), "java.lang.Object java.lang.ref.Reference.referent");
377         } else {
378           current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
379                                             sizeof(mirror::HeapReference<mirror::Object>));
380         }
381       } else {
382         if (field->GetOffset().Uint32Value() < end_ref_offset.Uint32Value()) {
383           // Shuffled before references.
384           ASSERT_LT(field->GetOffset().Uint32Value(), start_ref_offset.Uint32Value());
385           CHECK(!IsAligned<4>(field->GetOffset().Uint32Value()));
386         }
387       }
388     }
389     ASSERT_EQ(end_ref_offset.Uint32Value(), current_ref_offset.Uint32Value());
390 
391     uint32_t total_num_reference_instance_fields = 0;
392     ObjPtr<mirror::Class> k = klass.Get();
393     while (k != nullptr) {
394       total_num_reference_instance_fields += k->NumReferenceInstanceFields();
395       k = k->GetSuperClass();
396     }
397     EXPECT_GE(total_num_reference_instance_fields, 1U);  // Should always have Object's class.
398     if (klass->GetReferenceInstanceOffsets() != mirror::Class::kClassWalkSuper) {
399       // The reference instance offsets have a bit set for each reference offset.
400       // +1 for Object's class.
401       EXPECT_EQ(static_cast<uint32_t>(POPCOUNT(klass->GetReferenceInstanceOffsets())) + 1,
402                 total_num_reference_instance_fields);
403     }
404   }
405 
AssertDexFileClass(ObjPtr<mirror::ClassLoader> class_loader,const std::string & descriptor)406   void AssertDexFileClass(ObjPtr<mirror::ClassLoader> class_loader, const std::string& descriptor)
407       REQUIRES_SHARED(Locks::mutator_lock_) {
408     ASSERT_FALSE(descriptor.empty());
409     Thread* self = Thread::Current();
410     StackHandleScope<1> hs(self);
411     Handle<mirror::Class> klass(
412         hs.NewHandle(class_linker_->FindSystemClass(self, descriptor.c_str())));
413     ASSERT_TRUE(klass != nullptr);
414     std::string temp;
415     EXPECT_STREQ(descriptor.c_str(), klass->GetDescriptor(&temp));
416     EXPECT_OBJ_PTR_EQ(class_loader, klass->GetClassLoader());
417     if (klass->IsPrimitive()) {
418       AssertPrimitiveClass(descriptor, klass.Get());
419     } else if (klass->IsArrayClass()) {
420       AssertArrayClass(descriptor, klass);
421     } else {
422       AssertClass(descriptor, klass);
423     }
424   }
425 
AssertDexFile(const DexFile & dex,ObjPtr<mirror::ClassLoader> class_loader)426   void AssertDexFile(const DexFile& dex, ObjPtr<mirror::ClassLoader> class_loader)
427       REQUIRES_SHARED(Locks::mutator_lock_) {
428     // Verify all the classes defined in this file
429     for (size_t i = 0; i < dex.NumClassDefs(); i++) {
430       const dex::ClassDef& class_def = dex.GetClassDef(i);
431       const char* descriptor = dex.GetClassDescriptor(class_def);
432       AssertDexFileClass(class_loader, descriptor);
433     }
434     // Verify all the types referenced by this file
435     for (size_t i = 0; i < dex.NumTypeIds(); i++) {
436       const dex::TypeId& type_id = dex.GetTypeId(dex::TypeIndex(i));
437       const char* descriptor = dex.GetTypeDescriptor(type_id);
438       AssertDexFileClass(class_loader, descriptor);
439     }
440     TestRootVisitor visitor;
441     class_linker_->VisitRoots(&visitor, kVisitRootFlagAllRoots);
442   }
443 
444   class TestRootVisitor : public SingleRootVisitor {
445    public:
VisitRoot(mirror::Object * root,const RootInfo & info)446     void VisitRoot(mirror::Object* root, [[maybe_unused]] const RootInfo& info) override {
447       EXPECT_TRUE(root != nullptr);
448     }
449   };
450 };
451 
452 class ClassLinkerMethodHandlesTest : public ClassLinkerTest {
453  protected:
SetUpRuntimeOptions(RuntimeOptions * options)454   void SetUpRuntimeOptions(RuntimeOptions* options) override {
455     CommonRuntimeTest::SetUpRuntimeOptions(options);
456   }
457 };
458 
459 struct CheckOffset {
460   size_t cpp_offset;
461   const char* java_name;
CheckOffsetart::CheckOffset462   CheckOffset(size_t c, const char* j) : cpp_offset(c), java_name(j) {}
463 };
464 
465 template <typename T>
466 struct CheckOffsets {
CheckOffsetsart::CheckOffsets467   CheckOffsets(bool is_static_in, const char* class_descriptor_in)
468       : is_static(is_static_in), class_descriptor(class_descriptor_in) {}
469   bool is_static;
470   std::string class_descriptor;
471   std::vector<CheckOffset> offsets;
472 
Checkart::CheckOffsets473   bool Check() REQUIRES_SHARED(Locks::mutator_lock_) {
474     Thread* self = Thread::Current();
475     ObjPtr<mirror::Class> klass =
476         Runtime::Current()->GetClassLinker()->FindSystemClass(self, class_descriptor.c_str());
477     CHECK(klass != nullptr) << class_descriptor;
478     CHECK(klass->IsMirrored()) << class_descriptor;
479 
480     bool error = false;
481 
482     // Classes have a different size due to padding field. Strings are variable length.
483     if (!klass->IsClassClass() && !klass->IsStringClass() && !is_static) {
484       // The RoundUp is required for some mirror classes that have a gap at the end,
485       // such as AccessibleObject, ByteArrayViewVarHandle and ByteBufferViewVarHandle.
486       // For example, the AccessibleObject has size 9 according to the class linker.
487       // However, the C++ sizeof(AccessibleObject) is 12 bytes due to alignment, even
488       // though members in C++ subclasses are actually starting at offset 9.
489       //
490       // TODO: We could define a subclass with a `uint8_t` member and check its offset instead.
491       static constexpr size_t kPackAlignment = 4;
492       size_t expected_size = RoundUp(klass->GetObjectSize(), kPackAlignment);
493       if (sizeof(T) != expected_size) {
494         LOG(ERROR) << "Class size mismatch:"
495            << " class=" << class_descriptor
496            << " Java=" << expected_size
497            << " C++=" << sizeof(T);
498         error = true;
499       }
500     }
501 
502     size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
503     if (offsets.size() != num_fields) {
504       LOG(ERROR) << "Field count mismatch:"
505          << " class=" << class_descriptor
506          << " Java=" << num_fields
507          << " C++=" << offsets.size();
508       error = true;
509     }
510 
511     for (size_t i = 0; i < offsets.size(); i++) {
512       ArtField* field = is_static ? klass->GetStaticField(i) : klass->GetInstanceField(i);
513       std::string_view field_name(field->GetName());
514       if (field_name != offsets[i].java_name) {
515         error = true;
516       }
517     }
518     if (error) {
519       for (size_t i = 0; i < offsets.size(); i++) {
520         CheckOffset& offset = offsets[i];
521         ArtField* field = is_static ? klass->GetStaticField(i) : klass->GetInstanceField(i);
522         std::string_view field_name(field->GetName());
523         if (field_name != offsets[i].java_name) {
524           LOG(ERROR) << "JAVA FIELD ORDER MISMATCH NEXT LINE:";
525         }
526         LOG(ERROR) << "Java field order:"
527            << " i=" << i << " class=" << class_descriptor
528            << " Java=" << field_name
529            << " CheckOffsets=" << offset.java_name;
530       }
531     }
532 
533     for (size_t i = 0; i < offsets.size(); i++) {
534       CheckOffset& offset = offsets[i];
535       ArtField* field = is_static ? klass->GetStaticField(i) : klass->GetInstanceField(i);
536       if (field->GetOffset().Uint32Value() != offset.cpp_offset) {
537         error = true;
538       }
539     }
540     if (error) {
541       for (size_t i = 0; i < offsets.size(); i++) {
542         CheckOffset& offset = offsets[i];
543         ArtField* field = is_static ? klass->GetStaticField(i) : klass->GetInstanceField(i);
544         if (field->GetOffset().Uint32Value() != offset.cpp_offset) {
545           LOG(ERROR) << "OFFSET MISMATCH NEXT LINE:";
546         }
547         LOG(ERROR) << "Offset: class=" << class_descriptor << " field=" << offset.java_name
548            << " Java=" << field->GetOffset().Uint32Value() << " C++=" << offset.cpp_offset;
549       }
550     }
551 
552     return !error;
553   };
554 
addOffsetart::CheckOffsets555   void addOffset(size_t offset, const char* name) {
556     offsets.push_back(CheckOffset(offset, name));
557   }
558 
559  private:
560   DISALLOW_IMPLICIT_CONSTRUCTORS(CheckOffsets);
561 };
562 
563 // Note that ClassLinkerTest.ValidateFieldOrderOfJavaCppUnionClasses
564 // is first since if it is failing, others are unlikely to succeed.
565 
566 struct ObjectOffsets : public CheckOffsets<mirror::Object> {
ObjectOffsetsart::ObjectOffsets567   ObjectOffsets() : CheckOffsets<mirror::Object>(false, "Ljava/lang/Object;") {
568     addOffset(OFFSETOF_MEMBER(mirror::Object, klass_), "shadow$_klass_");
569     addOffset(OFFSETOF_MEMBER(mirror::Object, monitor_), "shadow$_monitor_");
570   }
571 };
572 
573 struct ClassOffsets : public CheckOffsets<mirror::Class> {
ClassOffsetsart::ClassOffsets574   ClassOffsets() : CheckOffsets<mirror::Class>(false, "Ljava/lang/Class;") {
575     addOffset(OFFSETOF_MEMBER(mirror::Class, access_flags_), "accessFlags");
576     addOffset(OFFSETOF_MEMBER(mirror::Class, class_flags_), "classFlags");
577     addOffset(OFFSETOF_MEMBER(mirror::Class, class_loader_), "classLoader");
578     addOffset(OFFSETOF_MEMBER(mirror::Class, class_size_), "classSize");
579     addOffset(OFFSETOF_MEMBER(mirror::Class, clinit_thread_id_), "clinitThreadId");
580     addOffset(OFFSETOF_MEMBER(mirror::Class, component_type_), "componentType");
581     addOffset(OFFSETOF_MEMBER(mirror::Class, copied_methods_offset_), "copiedMethodsOffset");
582     addOffset(OFFSETOF_MEMBER(mirror::Class, dex_cache_), "dexCache");
583     addOffset(OFFSETOF_MEMBER(mirror::Class, dex_class_def_idx_), "dexClassDefIndex");
584     addOffset(OFFSETOF_MEMBER(mirror::Class, dex_type_idx_), "dexTypeIndex");
585     addOffset(OFFSETOF_MEMBER(mirror::Class, ext_data_), "extData");
586     addOffset(OFFSETOF_MEMBER(mirror::Class, ifields_), "iFields");
587     addOffset(OFFSETOF_MEMBER(mirror::Class, iftable_), "ifTable");
588     addOffset(OFFSETOF_MEMBER(mirror::Class, methods_), "methods");
589     addOffset(OFFSETOF_MEMBER(mirror::Class, name_), "name");
590     addOffset(OFFSETOF_MEMBER(mirror::Class, num_reference_instance_fields_),
591               "numReferenceInstanceFields");
592     addOffset(OFFSETOF_MEMBER(mirror::Class, num_reference_static_fields_),
593               "numReferenceStaticFields");
594     addOffset(OFFSETOF_MEMBER(mirror::Class, object_size_), "objectSize");
595     addOffset(OFFSETOF_MEMBER(mirror::Class, object_size_alloc_fast_path_),
596               "objectSizeAllocFastPath");
597     addOffset(OFFSETOF_MEMBER(mirror::Class, primitive_type_), "primitiveType");
598     addOffset(OFFSETOF_MEMBER(mirror::Class, reference_instance_offsets_),
599               "referenceInstanceOffsets");
600     addOffset(OFFSETOF_MEMBER(mirror::Class, sfields_), "sFields");
601     addOffset(OFFSETOF_MEMBER(mirror::Class, status_), "status");
602     addOffset(OFFSETOF_MEMBER(mirror::Class, super_class_), "superClass");
603     addOffset(OFFSETOF_MEMBER(mirror::Class, virtual_methods_offset_), "virtualMethodsOffset");
604     addOffset(OFFSETOF_MEMBER(mirror::Class, vtable_), "vtable");
605   }
606 };
607 
608 struct ClassExtOffsets : public CheckOffsets<mirror::ClassExt> {
ClassExtOffsetsart::ClassExtOffsets609   ClassExtOffsets() : CheckOffsets<mirror::ClassExt>(false, "Ldalvik/system/ClassExt;") {
610     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, class_value_map_), "classValueMap");
611     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, erroneous_state_error_), "erroneousStateError");
612     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, instance_jfield_ids_), "instanceJfieldIDs");
613     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, jmethod_ids_), "jmethodIDs");
614     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, obsolete_class_), "obsoleteClass");
615     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, obsolete_dex_caches_), "obsoleteDexCaches");
616     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, obsolete_methods_), "obsoleteMethods");
617     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, original_dex_file_), "originalDexFile");
618     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, pre_redefine_class_def_index_),
619               "preRedefineClassDefIndex");
620     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, pre_redefine_dex_file_ptr_),
621               "preRedefineDexFilePtr");
622     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, static_jfield_ids_), "staticJfieldIDs");
623   }
624 };
625 
626 struct StringOffsets : public CheckOffsets<mirror::String> {
StringOffsetsart::StringOffsets627   StringOffsets() : CheckOffsets<mirror::String>(false, "Ljava/lang/String;") {
628     addOffset(OFFSETOF_MEMBER(mirror::String, count_), "count");
629     addOffset(OFFSETOF_MEMBER(mirror::String, hash_code_), "hash");
630   }
631 };
632 
633 struct ThrowableOffsets : public CheckOffsets<mirror::Throwable> {
ThrowableOffsetsart::ThrowableOffsets634   ThrowableOffsets() : CheckOffsets<mirror::Throwable>(false, "Ljava/lang/Throwable;") {
635     addOffset(OFFSETOF_MEMBER(mirror::Throwable, backtrace_), "backtrace");
636     addOffset(OFFSETOF_MEMBER(mirror::Throwable, cause_), "cause");
637     addOffset(OFFSETOF_MEMBER(mirror::Throwable, detail_message_), "detailMessage");
638     addOffset(OFFSETOF_MEMBER(mirror::Throwable, stack_trace_), "stackTrace");
639     addOffset(OFFSETOF_MEMBER(mirror::Throwable, suppressed_exceptions_), "suppressedExceptions");
640   }
641 };
642 
643 struct StackTraceElementOffsets : public CheckOffsets<mirror::StackTraceElement> {
StackTraceElementOffsetsart::StackTraceElementOffsets644   StackTraceElementOffsets() : CheckOffsets<mirror::StackTraceElement>(
645       false, "Ljava/lang/StackTraceElement;") {
646     addOffset(OFFSETOF_MEMBER(mirror::StackTraceElement, declaring_class_), "declaringClass");
647     addOffset(OFFSETOF_MEMBER(mirror::StackTraceElement, file_name_), "fileName");
648     addOffset(OFFSETOF_MEMBER(mirror::StackTraceElement, line_number_), "lineNumber");
649     addOffset(OFFSETOF_MEMBER(mirror::StackTraceElement, method_name_), "methodName");
650   }
651 };
652 
653 struct StackFrameInfoOffsets : public CheckOffsets<mirror::StackFrameInfo> {
StackFrameInfoOffsetsart::StackFrameInfoOffsets654   StackFrameInfoOffsets() : CheckOffsets<mirror::StackFrameInfo>(
655       false, "Ljava/lang/StackFrameInfo;") {
656     addOffset(OFFSETOF_MEMBER(mirror::StackFrameInfo, bci_), "bci");
657     addOffset(OFFSETOF_MEMBER(mirror::StackFrameInfo, declaring_class_), "declaringClass");
658     addOffset(OFFSETOF_MEMBER(mirror::StackFrameInfo, file_name_), "fileName");
659     addOffset(OFFSETOF_MEMBER(mirror::StackFrameInfo, line_number_), "lineNumber");
660     addOffset(OFFSETOF_MEMBER(mirror::StackFrameInfo, method_name_), "methodName");
661     addOffset(OFFSETOF_MEMBER(mirror::StackFrameInfo, method_type_), "methodType");
662     addOffset(OFFSETOF_MEMBER(mirror::StackFrameInfo, retain_class_ref_), "retainClassRef");
663     addOffset(OFFSETOF_MEMBER(mirror::StackFrameInfo, ste_), "ste");
664   }
665 };
666 
667 struct ClassLoaderOffsets : public CheckOffsets<mirror::ClassLoader> {
ClassLoaderOffsetsart::ClassLoaderOffsets668   ClassLoaderOffsets() : CheckOffsets<mirror::ClassLoader>(false, "Ljava/lang/ClassLoader;") {
669     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, allocator_), "allocator");
670     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, class_table_), "classTable");
671     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, name_), "name");
672     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, packages_), "packages");
673     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, parent_), "parent");
674     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, proxyCache_), "proxyCache");
675   }
676 };
677 
678 struct ProxyOffsets : public CheckOffsets<mirror::Proxy> {
ProxyOffsetsart::ProxyOffsets679   ProxyOffsets() : CheckOffsets<mirror::Proxy>(false, "Ljava/lang/reflect/Proxy;") {
680     addOffset(OFFSETOF_MEMBER(mirror::Proxy, h_), "h");
681   }
682 };
683 
684 struct DexCacheOffsets : public CheckOffsets<mirror::DexCache> {
DexCacheOffsetsart::DexCacheOffsets685   DexCacheOffsets() : CheckOffsets<mirror::DexCache>(false, "Ljava/lang/DexCache;") {
686     addOffset(OFFSETOF_MEMBER(mirror::DexCache, class_loader_), "classLoader");
687     addOffset(OFFSETOF_MEMBER(mirror::DexCache, dex_file_), "dexFile");
688     addOffset(OFFSETOF_MEMBER(mirror::DexCache, location_), "location");
689     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_call_sites_), "resolvedCallSites");
690     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_fields_), "resolvedFields");
691     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_fields_array_), "resolvedFieldsArray");
692     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_method_types_), "resolvedMethodTypes");
693     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_method_types_array_),
694               "resolvedMethodTypesArray");
695     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_methods_), "resolvedMethods");
696     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_methods_array_), "resolvedMethodsArray");
697     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_types_), "resolvedTypes");
698     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_types_array_), "resolvedTypesArray");
699     addOffset(OFFSETOF_MEMBER(mirror::DexCache, strings_), "strings");
700     addOffset(OFFSETOF_MEMBER(mirror::DexCache, strings_array_), "stringsArray");
701   }
702 };
703 
704 struct ReferenceOffsets : public CheckOffsets<mirror::Reference> {
ReferenceOffsetsart::ReferenceOffsets705   ReferenceOffsets() : CheckOffsets<mirror::Reference>(false, "Ljava/lang/ref/Reference;") {
706     addOffset(OFFSETOF_MEMBER(mirror::Reference, pending_next_), "pendingNext");
707     addOffset(OFFSETOF_MEMBER(mirror::Reference, queue_), "queue");
708     addOffset(OFFSETOF_MEMBER(mirror::Reference, queue_next_), "queueNext");
709     addOffset(OFFSETOF_MEMBER(mirror::Reference, referent_), "referent");
710   }
711 };
712 
713 struct FinalizerReferenceOffsets : public CheckOffsets<mirror::FinalizerReference> {
FinalizerReferenceOffsetsart::FinalizerReferenceOffsets714   FinalizerReferenceOffsets() : CheckOffsets<mirror::FinalizerReference>(
715       false, "Ljava/lang/ref/FinalizerReference;") {
716     addOffset(OFFSETOF_MEMBER(mirror::FinalizerReference, next_), "next");
717     addOffset(OFFSETOF_MEMBER(mirror::FinalizerReference, prev_), "prev");
718     addOffset(OFFSETOF_MEMBER(mirror::FinalizerReference, zombie_), "zombie");
719   }
720 };
721 
722 struct AccessibleObjectOffsets : public CheckOffsets<mirror::AccessibleObject> {
AccessibleObjectOffsetsart::AccessibleObjectOffsets723   AccessibleObjectOffsets() : CheckOffsets<mirror::AccessibleObject>(
724       false, "Ljava/lang/reflect/AccessibleObject;") {
725     addOffset(mirror::AccessibleObject::FlagOffset().Uint32Value(), "override");
726   }
727 };
728 
729 struct FieldOffsets : public CheckOffsets<mirror::Field> {
FieldOffsetsart::FieldOffsets730   FieldOffsets() : CheckOffsets<mirror::Field>(false, "Ljava/lang/reflect/Field;") {
731     addOffset(OFFSETOF_MEMBER(mirror::Field, access_flags_), "accessFlags");
732     addOffset(OFFSETOF_MEMBER(mirror::Field, art_field_index_), "artFieldIndex");
733     addOffset(OFFSETOF_MEMBER(mirror::Field, declaring_class_), "declaringClass");
734     addOffset(OFFSETOF_MEMBER(mirror::Field, offset_), "offset");
735     addOffset(OFFSETOF_MEMBER(mirror::Field, type_), "type");
736   }
737 };
738 
739 struct ExecutableOffsets : public CheckOffsets<mirror::Executable> {
ExecutableOffsetsart::ExecutableOffsets740   ExecutableOffsets() : CheckOffsets<mirror::Executable>(
741       false, "Ljava/lang/reflect/Executable;") {
742     addOffset(OFFSETOF_MEMBER(mirror::Executable, access_flags_), "accessFlags");
743     addOffset(OFFSETOF_MEMBER(mirror::Executable, art_method_), "artMethod");
744     addOffset(OFFSETOF_MEMBER(mirror::Executable, declaring_class_), "declaringClass");
745     addOffset(OFFSETOF_MEMBER(mirror::Executable, declaring_class_of_overridden_method_),
746               "declaringClassOfOverriddenMethod");
747     addOffset(OFFSETOF_MEMBER(mirror::Executable, dex_method_index_), "dexMethodIndex");
748     addOffset(OFFSETOF_MEMBER(mirror::Executable, has_real_parameter_data_),
749               "hasRealParameterData");
750     addOffset(OFFSETOF_MEMBER(mirror::Executable, parameters_), "parameters");
751   }
752 };
753 
754 struct MethodTypeOffsets : public CheckOffsets<mirror::MethodType> {
MethodTypeOffsetsart::MethodTypeOffsets755   MethodTypeOffsets() : CheckOffsets<mirror::MethodType>(
756       false, "Ljava/lang/invoke/MethodType;") {
757     addOffset(OFFSETOF_MEMBER(mirror::MethodType, form_), "form");
758     addOffset(OFFSETOF_MEMBER(mirror::MethodType, method_descriptor_), "methodDescriptor");
759     addOffset(OFFSETOF_MEMBER(mirror::MethodType, p_types_), "ptypes");
760     addOffset(OFFSETOF_MEMBER(mirror::MethodType, r_type_), "rtype");
761     addOffset(OFFSETOF_MEMBER(mirror::MethodType, wrap_alt_), "wrapAlt");
762   }
763 };
764 
765 struct MethodHandleOffsets : public CheckOffsets<mirror::MethodHandle> {
MethodHandleOffsetsart::MethodHandleOffsets766   MethodHandleOffsets() : CheckOffsets<mirror::MethodHandle>(
767       false, "Ljava/lang/invoke/MethodHandle;") {
768     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, art_field_or_method_), "artFieldOrMethod");
769     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, as_type_cache_), "asTypeCache");
770     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, cached_spread_invoker_),
771               "cachedSpreadInvoker");
772     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, handle_kind_), "handleKind");
773     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, method_type_), "type");
774   }
775 };
776 
777 struct MethodHandleImplOffsets : public CheckOffsets<mirror::MethodHandleImpl> {
MethodHandleImplOffsetsart::MethodHandleImplOffsets778   MethodHandleImplOffsets() : CheckOffsets<mirror::MethodHandleImpl>(
779       false, "Ljava/lang/invoke/MethodHandleImpl;") {
780     addOffset(OFFSETOF_MEMBER(mirror::MethodHandleImpl, info_), "info");
781   }
782 };
783 
784 struct MethodHandlesLookupOffsets : public CheckOffsets<mirror::MethodHandlesLookup> {
MethodHandlesLookupOffsetsart::MethodHandlesLookupOffsets785   MethodHandlesLookupOffsets() : CheckOffsets<mirror::MethodHandlesLookup>(
786       false, "Ljava/lang/invoke/MethodHandles$Lookup;") {
787     addOffset(OFFSETOF_MEMBER(mirror::MethodHandlesLookup, allowed_modes_), "allowedModes");
788     addOffset(OFFSETOF_MEMBER(mirror::MethodHandlesLookup, lookup_class_), "lookupClass");
789   }
790 };
791 
792 struct EmulatedStackFrameOffsets : public CheckOffsets<mirror::EmulatedStackFrame> {
EmulatedStackFrameOffsetsart::EmulatedStackFrameOffsets793   EmulatedStackFrameOffsets() : CheckOffsets<mirror::EmulatedStackFrame>(
794       false, "Ldalvik/system/EmulatedStackFrame;") {
795     addOffset(OFFSETOF_MEMBER(mirror::EmulatedStackFrame, references_), "references");
796     addOffset(OFFSETOF_MEMBER(mirror::EmulatedStackFrame, stack_frame_), "stackFrame");
797     addOffset(OFFSETOF_MEMBER(mirror::EmulatedStackFrame, type_), "type");
798   }
799 };
800 
801 struct CallSiteOffsets : public CheckOffsets<mirror::CallSite> {
CallSiteOffsetsart::CallSiteOffsets802   CallSiteOffsets() : CheckOffsets<mirror::CallSite>(
803       false, "Ljava/lang/invoke/CallSite;") {
804     addOffset(OFFSETOF_MEMBER(mirror::CallSite, target_), "target");
805   }
806 };
807 
808 struct VarHandleOffsets : public CheckOffsets<mirror::VarHandle> {
VarHandleOffsetsart::VarHandleOffsets809   VarHandleOffsets() : CheckOffsets<mirror::VarHandle>(
810       false, "Ljava/lang/invoke/VarHandle;") {
811     addOffset(OFFSETOF_MEMBER(mirror::VarHandle, access_modes_bit_mask_), "accessModesBitMask");
812     addOffset(OFFSETOF_MEMBER(mirror::VarHandle, coordinate_type0_), "coordinateType0");
813     addOffset(OFFSETOF_MEMBER(mirror::VarHandle, coordinate_type1_), "coordinateType1");
814     addOffset(OFFSETOF_MEMBER(mirror::VarHandle, var_type_), "varType");
815   }
816 };
817 
818 struct FieldVarHandleOffsets : public CheckOffsets<mirror::FieldVarHandle> {
FieldVarHandleOffsetsart::FieldVarHandleOffsets819   FieldVarHandleOffsets() : CheckOffsets<mirror::FieldVarHandle>(
820       false, "Ljava/lang/invoke/FieldVarHandle;") {
821     addOffset(OFFSETOF_MEMBER(mirror::FieldVarHandle, art_field_), "artField");
822   }
823 };
824 
825 struct StaticFieldVarHandleOffsets : public CheckOffsets<mirror::StaticFieldVarHandle> {
StaticFieldVarHandleOffsetsart::StaticFieldVarHandleOffsets826   StaticFieldVarHandleOffsets() : CheckOffsets<mirror::StaticFieldVarHandle>(
827       false, "Ljava/lang/invoke/StaticFieldVarHandle;") {
828     addOffset(OFFSETOF_MEMBER(mirror::StaticFieldVarHandle, declaring_class_), "declaringClass");
829   }
830 };
831 
832 struct ArrayElementVarHandleOffsets : public CheckOffsets<mirror::ArrayElementVarHandle> {
ArrayElementVarHandleOffsetsart::ArrayElementVarHandleOffsets833   ArrayElementVarHandleOffsets() : CheckOffsets<mirror::ArrayElementVarHandle>(
834       false, "Ljava/lang/invoke/ArrayElementVarHandle;") {
835   }
836 };
837 
838 struct ByteArrayViewVarHandleOffsets : public CheckOffsets<mirror::ByteArrayViewVarHandle> {
ByteArrayViewVarHandleOffsetsart::ByteArrayViewVarHandleOffsets839   ByteArrayViewVarHandleOffsets() : CheckOffsets<mirror::ByteArrayViewVarHandle>(
840       false, "Ljava/lang/invoke/ByteArrayViewVarHandle;") {
841     addOffset(OFFSETOF_MEMBER(mirror::ByteArrayViewVarHandle, native_byte_order_),
842               "nativeByteOrder");
843   }
844 };
845 
846 struct ByteBufferViewVarHandleOffsets : public CheckOffsets<mirror::ByteBufferViewVarHandle> {
ByteBufferViewVarHandleOffsetsart::ByteBufferViewVarHandleOffsets847   ByteBufferViewVarHandleOffsets() : CheckOffsets<mirror::ByteBufferViewVarHandle>(
848       false, "Ljava/lang/invoke/ByteBufferViewVarHandle;") {
849     addOffset(OFFSETOF_MEMBER(mirror::ByteBufferViewVarHandle, native_byte_order_),
850               "nativeByteOrder");
851   }
852 };
853 
854 // C++ fields must exactly match the fields in the Java classes. If this fails,
855 // reorder the fields in the C++ class. Managed class fields are ordered by
856 // ClassLinker::LinkFieldsHelper::LinkFields.
TEST_F(ClassLinkerTest,ValidateFieldOrderOfJavaCppUnionClasses)857 TEST_F(ClassLinkerTest, ValidateFieldOrderOfJavaCppUnionClasses) {
858   ScopedObjectAccess soa(Thread::Current());
859   EXPECT_TRUE(ObjectOffsets().Check());
860   EXPECT_TRUE(ClassOffsets().Check());
861   EXPECT_TRUE(ClassExtOffsets().Check());
862   EXPECT_TRUE(StringOffsets().Check());
863   EXPECT_TRUE(ThrowableOffsets().Check());
864   EXPECT_TRUE(StackTraceElementOffsets().Check());
865   EXPECT_TRUE(ClassLoaderOffsets().Check());
866   EXPECT_TRUE(ProxyOffsets().Check());
867   EXPECT_TRUE(DexCacheOffsets().Check());
868   EXPECT_TRUE(ReferenceOffsets().Check());
869   EXPECT_TRUE(FinalizerReferenceOffsets().Check());
870   EXPECT_TRUE(AccessibleObjectOffsets().Check());
871   EXPECT_TRUE(FieldOffsets().Check());
872   EXPECT_TRUE(ExecutableOffsets().Check());
873   EXPECT_TRUE(MethodTypeOffsets().Check());
874   EXPECT_TRUE(MethodHandleOffsets().Check());
875   EXPECT_TRUE(MethodHandleImplOffsets().Check());
876   EXPECT_TRUE(MethodHandlesLookupOffsets().Check());
877   EXPECT_TRUE(EmulatedStackFrameOffsets().Check());
878   EXPECT_TRUE(CallSiteOffsets().Check());
879   EXPECT_TRUE(VarHandleOffsets().Check());
880   EXPECT_TRUE(FieldVarHandleOffsets().Check());
881   EXPECT_TRUE(ArrayElementVarHandleOffsets().Check());
882   EXPECT_TRUE(ByteArrayViewVarHandleOffsets().Check());
883   EXPECT_TRUE(ByteBufferViewVarHandleOffsets().Check());
884   EXPECT_TRUE(StackFrameInfoOffsets().Check());
885 }
886 
TEST_F(ClassLinkerTest,FindClassNonexistent)887 TEST_F(ClassLinkerTest, FindClassNonexistent) {
888   ScopedObjectAccess soa(Thread::Current());
889   AssertNonExistentClass("NoSuchClass;");
890   AssertNonExistentClass("LNoSuchClass;");
891 }
892 
TEST_F(ClassLinkerTest,GetDexFiles)893 TEST_F(ClassLinkerTest, GetDexFiles) {
894   ScopedObjectAccess soa(Thread::Current());
895 
896   jobject jclass_loader = LoadDex("Nested");
897   std::vector<const DexFile*> dex_files(GetDexFiles(jclass_loader));
898   ASSERT_EQ(dex_files.size(), 1U);
899   EXPECT_TRUE(dex_files[0]->GetLocation().ends_with("Nested.jar"));
900 
901   jobject jclass_loader2 = LoadDex("MultiDex");
902   std::vector<const DexFile*> dex_files2(GetDexFiles(jclass_loader2));
903   ASSERT_EQ(dex_files2.size(), 2U);
904   EXPECT_TRUE(dex_files2[0]->GetLocation().ends_with("MultiDex.jar"));
905 }
906 
TEST_F(ClassLinkerTest,FindClassNested)907 TEST_F(ClassLinkerTest, FindClassNested) {
908   ScopedObjectAccess soa(Thread::Current());
909   StackHandleScope<1> hs(soa.Self());
910   Handle<mirror::ClassLoader> class_loader(
911       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Nested"))));
912 
913   ObjPtr<mirror::Class> outer = class_linker_->FindClass(soa.Self(), "LNested;", class_loader);
914   ASSERT_TRUE(outer != nullptr);
915   EXPECT_EQ(0U, outer->NumVirtualMethods());
916   EXPECT_EQ(1U, outer->NumDirectMethods());
917 
918   ObjPtr<mirror::Class> inner =
919       class_linker_->FindClass(soa.Self(), "LNested$Inner;", class_loader);
920   ASSERT_TRUE(inner != nullptr);
921   EXPECT_EQ(0U, inner->NumVirtualMethods());
922   EXPECT_EQ(1U, inner->NumDirectMethods());
923 }
924 
TEST_F(ClassLinkerTest,FindClass_Primitives)925 TEST_F(ClassLinkerTest, FindClass_Primitives) {
926   ScopedObjectAccess soa(Thread::Current());
927   const std::string expected("BCDFIJSZV");
928   for (int ch = 1; ch < 256; ++ch) {
929     std::string descriptor;
930     descriptor.push_back(ch);
931     if (expected.find(ch) == std::string::npos) {
932       AssertNonExistentClass(descriptor);
933     } else {
934       AssertPrimitiveClass(descriptor);
935     }
936   }
937 }
938 
TEST_F(ClassLinkerTest,FindClass)939 TEST_F(ClassLinkerTest, FindClass) {
940   ScopedObjectAccess soa(Thread::Current());
941   StackHandleScope<2> hs(soa.Self());
942   Handle<mirror::Class> JavaLangObject = hs.NewHandle(
943       class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;"));
944   AssertObjectClass(JavaLangObject.Get());
945 
946   Handle<mirror::ClassLoader> class_loader(
947       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MyClass"))));
948   AssertNonExistentClass("LMyClass;");
949   ObjPtr<mirror::Class> MyClass = class_linker_->FindClass(soa.Self(), "LMyClass;", class_loader);
950   ASSERT_TRUE(MyClass != nullptr);
951   ASSERT_TRUE(MyClass->GetClass() != nullptr);
952   ASSERT_OBJ_PTR_EQ(MyClass->GetClass(), MyClass->GetClass()->GetClass());
953   EXPECT_OBJ_PTR_EQ(JavaLangObject.Get(), MyClass->GetClass()->GetSuperClass());
954   std::string temp;
955   ASSERT_STREQ(MyClass->GetDescriptor(&temp), "LMyClass;");
956   EXPECT_OBJ_PTR_EQ(MyClass->GetSuperClass(), JavaLangObject.Get());
957   EXPECT_TRUE(MyClass->HasSuperClass());
958   EXPECT_OBJ_PTR_EQ(class_loader.Get(), MyClass->GetClassLoader());
959   EXPECT_EQ(ClassStatus::kResolved, MyClass->GetStatus());
960   EXPECT_FALSE(MyClass->IsErroneous());
961   EXPECT_TRUE(MyClass->IsLoaded());
962   EXPECT_TRUE(MyClass->IsResolved());
963   EXPECT_FALSE(MyClass->IsErroneousResolved());
964   EXPECT_FALSE(MyClass->IsVerified());
965   EXPECT_FALSE(MyClass->IsInitialized());
966   EXPECT_FALSE(MyClass->IsArrayInstance());
967   EXPECT_FALSE(MyClass->IsArrayClass());
968   EXPECT_TRUE(MyClass->GetComponentType() == nullptr);
969   EXPECT_FALSE(MyClass->IsInterface());
970   EXPECT_FALSE(MyClass->IsPublic());
971   EXPECT_FALSE(MyClass->IsFinal());
972   EXPECT_FALSE(MyClass->IsPrimitive());
973   EXPECT_FALSE(MyClass->IsSynthetic());
974   EXPECT_EQ(1U, MyClass->NumDirectMethods());
975   EXPECT_EQ(0U, MyClass->NumVirtualMethods());
976   EXPECT_EQ(0U, MyClass->NumInstanceFields());
977   EXPECT_EQ(0U, MyClass->NumStaticFields());
978   EXPECT_EQ(0U, MyClass->NumDirectInterfaces());
979 
980   EXPECT_OBJ_PTR_EQ(JavaLangObject->GetClass()->GetClass(), MyClass->GetClass()->GetClass());
981 
982   // created by class_linker
983   AssertArrayClass("[C", "C", nullptr);
984   AssertArrayClass("[Ljava/lang/Object;", "Ljava/lang/Object;", nullptr);
985   // synthesized on the fly
986   AssertArrayClass("[[C", "[C", nullptr);
987   AssertArrayClass("[[[LMyClass;", "[[LMyClass;", class_loader.Get());
988   // or not available at all
989   AssertNonExistentClass("[[[[LNonExistentClass;");
990 }
991 
TEST_F(ClassLinkerTest,LookupResolvedType)992 TEST_F(ClassLinkerTest, LookupResolvedType) {
993   ScopedObjectAccess soa(Thread::Current());
994   StackHandleScope<1> hs(soa.Self());
995   Handle<mirror::ClassLoader> class_loader(
996       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MyClass"))));
997   AssertNonExistentClass("LMyClass;");
998   ObjPtr<mirror::Class> klass = class_linker_->FindClass(soa.Self(), "LMyClass;", class_loader);
999   dex::TypeIndex type_idx = klass->GetClassDef()->class_idx_;
1000   ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
1001   EXPECT_OBJ_PTR_EQ(
1002       class_linker_->LookupResolvedType(type_idx, dex_cache, class_loader.Get()),
1003       klass);
1004   // Zero out the resolved type and make sure LookupResolvedType still finds it.
1005   dex_cache->ClearResolvedType(type_idx);
1006   EXPECT_TRUE(dex_cache->GetResolvedType(type_idx) == nullptr);
1007   EXPECT_OBJ_PTR_EQ(
1008       class_linker_->LookupResolvedType(type_idx, dex_cache, class_loader.Get()),
1009       klass);
1010 }
1011 
TEST_F(ClassLinkerTest,LookupResolvedTypeArray)1012 TEST_F(ClassLinkerTest, LookupResolvedTypeArray) {
1013   ScopedObjectAccess soa(Thread::Current());
1014   StackHandleScope<2> hs(soa.Self());
1015   Handle<mirror::ClassLoader> class_loader(
1016       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("AllFields"))));
1017   // Get the AllFields class for the dex cache and dex file.
1018   ObjPtr<mirror::Class> all_fields_klass
1019       = class_linker_->FindClass(soa.Self(), "LAllFields;", class_loader);
1020   ASSERT_TRUE(all_fields_klass != nullptr);
1021   Handle<mirror::DexCache> dex_cache = hs.NewHandle(all_fields_klass->GetDexCache());
1022   const DexFile& dex_file = *dex_cache->GetDexFile();
1023   // Get the index of the array class we want to test.
1024   const dex::TypeId* array_id = dex_file.FindTypeId("[Ljava/lang/Object;");
1025   ASSERT_TRUE(array_id != nullptr);
1026   dex::TypeIndex array_idx = dex_file.GetIndexForTypeId(*array_id);
1027   // Check that the array class wasn't resolved yet.
1028   EXPECT_TRUE(
1029       class_linker_->LookupResolvedType(array_idx, dex_cache.Get(), class_loader.Get()) == nullptr);
1030   // Resolve the array class we want to test.
1031   ObjPtr<mirror::Class> array_klass
1032       = class_linker_->FindClass(soa.Self(), "[Ljava/lang/Object;", class_loader);
1033   ASSERT_TRUE(array_klass != nullptr);
1034   // Test that LookupResolvedType() finds the array class.
1035   EXPECT_OBJ_PTR_EQ(
1036       class_linker_->LookupResolvedType(array_idx, dex_cache.Get(), class_loader.Get()),
1037       array_klass);
1038   // Zero out the resolved type and make sure LookupResolvedType() still finds it.
1039   dex_cache->ClearResolvedType(array_idx);
1040   EXPECT_TRUE(dex_cache->GetResolvedType(array_idx) == nullptr);
1041   EXPECT_OBJ_PTR_EQ(
1042       class_linker_->LookupResolvedType(array_idx, dex_cache.Get(), class_loader.Get()),
1043       array_klass);
1044 }
1045 
TEST_F(ClassLinkerTest,LookupResolvedTypeErroneousInit)1046 TEST_F(ClassLinkerTest, LookupResolvedTypeErroneousInit) {
1047   ScopedObjectAccess soa(Thread::Current());
1048   StackHandleScope<3> hs(soa.Self());
1049   Handle<mirror::ClassLoader> class_loader(
1050       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("ErroneousInit"))));
1051   AssertNonExistentClass("LErroneousInit;");
1052   Handle<mirror::Class> klass =
1053       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LErroneousInit;", class_loader));
1054   ASSERT_TRUE(klass != nullptr);
1055   dex::TypeIndex type_idx = klass->GetClassDef()->class_idx_;
1056   Handle<mirror::DexCache> dex_cache = hs.NewHandle(klass->GetDexCache());
1057   EXPECT_OBJ_PTR_EQ(
1058       class_linker_->LookupResolvedType(type_idx, dex_cache.Get(), class_loader.Get()),
1059       klass.Get());
1060   // Zero out the resolved type and make sure LookupResolvedType still finds it.
1061   dex_cache->ClearResolvedType(type_idx);
1062   EXPECT_TRUE(dex_cache->GetResolvedType(type_idx) == nullptr);
1063   EXPECT_OBJ_PTR_EQ(
1064       class_linker_->LookupResolvedType(type_idx, dex_cache.Get(), class_loader.Get()),
1065       klass.Get());
1066   // Force initialization to turn the class erroneous.
1067   bool initialized = class_linker_->EnsureInitialized(soa.Self(),
1068                                                       klass,
1069                                                       /* can_init_fields= */ true,
1070                                                       /* can_init_parents= */ true);
1071   EXPECT_FALSE(initialized);
1072   EXPECT_TRUE(soa.Self()->IsExceptionPending());
1073   soa.Self()->ClearException();
1074   // Check that the LookupResolvedType() can still find the resolved type.
1075   EXPECT_OBJ_PTR_EQ(
1076       class_linker_->LookupResolvedType(type_idx, dex_cache.Get(), class_loader.Get()),
1077       klass.Get());
1078   // Zero out the resolved type and make sure LookupResolvedType() still finds it.
1079   dex_cache->ClearResolvedType(type_idx);
1080   EXPECT_TRUE(dex_cache->GetResolvedType(type_idx) == nullptr);
1081   EXPECT_OBJ_PTR_EQ(
1082       class_linker_->LookupResolvedType(type_idx, dex_cache.Get(), class_loader.Get()),
1083       klass.Get());
1084 }
1085 
TEST_F(ClassLinkerTest,LibCore)1086 TEST_F(ClassLinkerTest, LibCore) {
1087   ScopedObjectAccess soa(Thread::Current());
1088   ASSERT_TRUE(java_lang_dex_file_ != nullptr);
1089   AssertDexFile(*java_lang_dex_file_, nullptr);
1090 }
1091 
1092 // The first reference array element must be a multiple of 4 bytes from the
1093 // start of the object
TEST_F(ClassLinkerTest,ValidateObjectArrayElementsOffset)1094 TEST_F(ClassLinkerTest, ValidateObjectArrayElementsOffset) {
1095   ScopedObjectAccess soa(Thread::Current());
1096   ObjPtr<mirror::Class> array_class =
1097       class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/String;");
1098   ObjPtr<mirror::ObjectArray<mirror::String>> array =
1099       mirror::ObjectArray<mirror::String>::Alloc(soa.Self(), array_class, 0);
1100   uintptr_t data_offset =
1101       reinterpret_cast<uintptr_t>(array->GetRawData(sizeof(mirror::HeapReference<mirror::String>),
1102                                                     0));
1103   if (sizeof(mirror::HeapReference<mirror::String>) == sizeof(int32_t)) {
1104     EXPECT_TRUE(IsAligned<4>(data_offset));  // Check 4 byte alignment.
1105   } else {
1106     EXPECT_TRUE(IsAligned<8>(data_offset));  // Check 8 byte alignment.
1107   }
1108 }
1109 
TEST_F(ClassLinkerTest,ValidatePrimitiveArrayElementsOffset)1110 TEST_F(ClassLinkerTest, ValidatePrimitiveArrayElementsOffset) {
1111   ScopedObjectAccess soa(Thread::Current());
1112   StackHandleScope<5> hs(soa.Self());
1113   Handle<mirror::LongArray> long_array(hs.NewHandle(mirror::LongArray::Alloc(soa.Self(), 0)));
1114   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[J"), long_array->GetClass());
1115   uintptr_t data_offset = reinterpret_cast<uintptr_t>(long_array->GetData());
1116   EXPECT_TRUE(IsAligned<8>(data_offset));  // Longs require 8 byte alignment
1117 
1118   Handle<mirror::DoubleArray> double_array(hs.NewHandle(mirror::DoubleArray::Alloc(soa.Self(), 0)));
1119   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[D"), double_array->GetClass());
1120   data_offset = reinterpret_cast<uintptr_t>(double_array->GetData());
1121   EXPECT_TRUE(IsAligned<8>(data_offset));  // Doubles require 8 byte alignment
1122 
1123   Handle<mirror::IntArray> int_array(hs.NewHandle(mirror::IntArray::Alloc(soa.Self(), 0)));
1124   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[I"), int_array->GetClass());
1125   data_offset = reinterpret_cast<uintptr_t>(int_array->GetData());
1126   EXPECT_TRUE(IsAligned<4>(data_offset));  // Ints require 4 byte alignment
1127 
1128   Handle<mirror::CharArray> char_array(hs.NewHandle(mirror::CharArray::Alloc(soa.Self(), 0)));
1129   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[C"), char_array->GetClass());
1130   data_offset = reinterpret_cast<uintptr_t>(char_array->GetData());
1131   EXPECT_TRUE(IsAligned<2>(data_offset));  // Chars require 2 byte alignment
1132 
1133   Handle<mirror::ShortArray> short_array(hs.NewHandle(mirror::ShortArray::Alloc(soa.Self(), 0)));
1134   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[S"), short_array->GetClass());
1135   data_offset = reinterpret_cast<uintptr_t>(short_array->GetData());
1136   EXPECT_TRUE(IsAligned<2>(data_offset));  // Shorts require 2 byte alignment
1137 
1138   // Take it as given that bytes and booleans have byte alignment
1139 }
1140 
TEST_F(ClassLinkerTest,ValidateBoxedTypes)1141 TEST_F(ClassLinkerTest, ValidateBoxedTypes) {
1142   // Validate that the "value" field is always the 0th field in each of java.lang's box classes.
1143   // This lets UnboxPrimitive avoid searching for the field by name at runtime.
1144   ScopedObjectAccess soa(Thread::Current());
1145   ScopedNullHandle<mirror::ClassLoader> class_loader;
1146   ObjPtr<mirror::Class> c;
1147   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Boolean;", class_loader);
1148   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1149   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Byte;", class_loader);
1150   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1151   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Character;", class_loader);
1152   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1153   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Double;", class_loader);
1154   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1155   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Float;", class_loader);
1156   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1157   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Integer;", class_loader);
1158   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1159   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Long;", class_loader);
1160   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1161   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Short;", class_loader);
1162   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1163 }
1164 
TEST_F(ClassLinkerTest,TwoClassLoadersOneClass)1165 TEST_F(ClassLinkerTest, TwoClassLoadersOneClass) {
1166   ScopedObjectAccess soa(Thread::Current());
1167   StackHandleScope<3> hs(soa.Self());
1168   Handle<mirror::ClassLoader> class_loader_1(
1169       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MyClass"))));
1170   Handle<mirror::ClassLoader> class_loader_2(
1171       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MyClass"))));
1172   Handle<mirror::Class> MyClass_1 = hs.NewHandle(
1173       class_linker_->FindClass(soa.Self(), "LMyClass;", class_loader_1));
1174   ObjPtr<mirror::Class> MyClass_2 =
1175       class_linker_->FindClass(soa.Self(), "LMyClass;", class_loader_2);
1176   EXPECT_TRUE(MyClass_1 != nullptr);
1177   EXPECT_TRUE(MyClass_2 != nullptr);
1178   EXPECT_OBJ_PTR_NE(MyClass_1.Get(), MyClass_2);
1179 }
1180 
TEST_F(ClassLinkerTest,StaticFields)1181 TEST_F(ClassLinkerTest, StaticFields) {
1182   ScopedObjectAccess soa(Thread::Current());
1183   StackHandleScope<2> hs(soa.Self());
1184   Handle<mirror::ClassLoader> class_loader(
1185       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Statics"))));
1186   Handle<mirror::Class> statics(
1187       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LStatics;", class_loader)));
1188   class_linker_->EnsureInitialized(soa.Self(), statics, true, true);
1189 
1190   // Static final primitives that are initialized by a compile-time constant
1191   // expression resolve to a copy of a constant value from the constant pool.
1192   // So <clinit> should be null.
1193   ArtMethod* clinit = statics->FindClassMethod("<clinit>", "()V", kRuntimePointerSize);
1194   EXPECT_TRUE(clinit == nullptr);
1195 
1196   EXPECT_EQ(9U, statics->NumStaticFields());
1197 
1198   ArtField* s0 = statics->FindStaticField("s0", "Z");
1199   EXPECT_EQ(s0->GetTypeAsPrimitiveType(), Primitive::kPrimBoolean);
1200   EXPECT_EQ(true, s0->GetBoolean(statics.Get()));
1201   s0->SetBoolean<false>(statics.Get(), false);
1202 
1203   ArtField* s1 = statics->FindStaticField("s1", "B");
1204   EXPECT_EQ(s1->GetTypeAsPrimitiveType(), Primitive::kPrimByte);
1205   EXPECT_EQ(5, s1->GetByte(statics.Get()));
1206   s1->SetByte<false>(statics.Get(), 6);
1207 
1208   ArtField* s2 = statics->FindStaticField("s2", "C");
1209   EXPECT_EQ(s2->GetTypeAsPrimitiveType(), Primitive::kPrimChar);
1210   EXPECT_EQ('a', s2->GetChar(statics.Get()));
1211   s2->SetChar<false>(statics.Get(), 'b');
1212 
1213   ArtField* s3 = statics->FindStaticField("s3", "S");
1214   EXPECT_EQ(s3->GetTypeAsPrimitiveType(), Primitive::kPrimShort);
1215   EXPECT_EQ(-536, s3->GetShort(statics.Get()));
1216   s3->SetShort<false>(statics.Get(), -535);
1217 
1218   ArtField* s4 = statics->FindStaticField("s4", "I");
1219   EXPECT_EQ(s4->GetTypeAsPrimitiveType(), Primitive::kPrimInt);
1220   EXPECT_EQ(2000000000, s4->GetInt(statics.Get()));
1221   s4->SetInt<false>(statics.Get(), 2000000001);
1222 
1223   ArtField* s5 = statics->FindStaticField("s5", "J");
1224   EXPECT_EQ(s5->GetTypeAsPrimitiveType(), Primitive::kPrimLong);
1225   EXPECT_EQ(0x1234567890abcdefLL, s5->GetLong(statics.Get()));
1226   s5->SetLong<false>(statics.Get(), INT64_C(0x34567890abcdef12));
1227 
1228   ArtField* s6 = statics->FindStaticField("s6", "F");
1229   EXPECT_EQ(s6->GetTypeAsPrimitiveType(), Primitive::kPrimFloat);
1230   EXPECT_DOUBLE_EQ(0.5, s6->GetFloat(statics.Get()));
1231   s6->SetFloat<false>(statics.Get(), 0.75);
1232 
1233   ArtField* s7 = statics->FindStaticField("s7", "D");
1234   EXPECT_EQ(s7->GetTypeAsPrimitiveType(), Primitive::kPrimDouble);
1235   EXPECT_DOUBLE_EQ(16777217.0, s7->GetDouble(statics.Get()));
1236   s7->SetDouble<false>(statics.Get(), 16777219);
1237 
1238   ArtField* s8 = statics->FindStaticField("s8", "Ljava/lang/String;");
1239   EXPECT_EQ(s8->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
1240   EXPECT_TRUE(s8->GetObject(statics.Get())->AsString()->Equals("android"));
1241   ObjPtr<mirror::String> str_value = mirror::String::AllocFromModifiedUtf8(soa.Self(), "robot");
1242   s8->SetObject<false>(s8->GetDeclaringClass(), str_value);
1243 
1244   // TODO: Remove EXPECT_FALSE when GCC can handle EXPECT_EQ
1245   // http://code.google.com/p/googletest/issues/detail?id=322
1246   EXPECT_FALSE(s0->GetBoolean(statics.Get()));
1247   EXPECT_EQ(6, s1->GetByte(statics.Get()));
1248   EXPECT_EQ('b', s2->GetChar(statics.Get()));
1249   EXPECT_EQ(-535, s3->GetShort(statics.Get()));
1250   EXPECT_EQ(2000000001, s4->GetInt(statics.Get()));
1251   EXPECT_EQ(INT64_C(0x34567890abcdef12), s5->GetLong(statics.Get()));
1252   EXPECT_FLOAT_EQ(0.75, s6->GetFloat(statics.Get()));
1253   EXPECT_DOUBLE_EQ(16777219.0, s7->GetDouble(statics.Get()));
1254   EXPECT_TRUE(s8->GetObject(statics.Get())->AsString()->Equals("robot"));
1255 }
1256 
TEST_F(ClassLinkerTest,Interfaces)1257 TEST_F(ClassLinkerTest, Interfaces) {
1258   ScopedObjectAccess soa(Thread::Current());
1259   StackHandleScope<6> hs(soa.Self());
1260   Handle<mirror::ClassLoader> class_loader(
1261       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Interfaces"))));
1262   Handle<mirror::Class> I(
1263       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$I;", class_loader)));
1264   Handle<mirror::Class> J(
1265       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$J;", class_loader)));
1266   Handle<mirror::Class> K(
1267       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$K;", class_loader)));
1268   Handle<mirror::Class> A(
1269       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$A;", class_loader)));
1270   Handle<mirror::Class> B(
1271       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$B;", class_loader)));
1272   EXPECT_TRUE(I->IsAssignableFrom(A.Get()));
1273   EXPECT_TRUE(J->IsAssignableFrom(A.Get()));
1274   EXPECT_TRUE(J->IsAssignableFrom(K.Get()));
1275   EXPECT_TRUE(K->IsAssignableFrom(B.Get()));
1276   EXPECT_TRUE(J->IsAssignableFrom(B.Get()));
1277 
1278   const std::string_view void_sig("()V");
1279   ArtMethod* Ii = I->FindClassMethod("i", void_sig, kRuntimePointerSize);
1280   ArtMethod* Jj1 = J->FindClassMethod("j1", void_sig, kRuntimePointerSize);
1281   ArtMethod* Jj2 = J->FindClassMethod("j2", void_sig, kRuntimePointerSize);
1282   ArtMethod* Kj1 = K->FindInterfaceMethod("j1", void_sig, kRuntimePointerSize);
1283   ArtMethod* Kj2 = K->FindInterfaceMethod("j2", void_sig, kRuntimePointerSize);
1284   ArtMethod* Kk = K->FindInterfaceMethod("k", void_sig, kRuntimePointerSize);
1285   ArtMethod* Ai = A->FindClassMethod("i", void_sig, kRuntimePointerSize);
1286   ArtMethod* Aj1 = A->FindClassMethod("j1", void_sig, kRuntimePointerSize);
1287   ArtMethod* Aj2 = A->FindClassMethod("j2", void_sig, kRuntimePointerSize);
1288   ASSERT_TRUE(Ii != nullptr);
1289   ASSERT_FALSE(Ii->IsDirect());
1290   ASSERT_TRUE(Jj1 != nullptr);
1291   ASSERT_FALSE(Jj1->IsDirect());
1292   ASSERT_TRUE(Jj2 != nullptr);
1293   ASSERT_FALSE(Jj2->IsDirect());
1294   ASSERT_TRUE(Kj1 != nullptr);
1295   ASSERT_TRUE(Kj2 != nullptr);
1296   ASSERT_TRUE(Kk != nullptr);
1297   ASSERT_TRUE(Ai != nullptr);
1298   ASSERT_FALSE(Ai->IsDirect());
1299   ASSERT_TRUE(Aj1 != nullptr);
1300   ASSERT_FALSE(Aj1->IsDirect());
1301   ASSERT_TRUE(Aj2 != nullptr);
1302   ASSERT_FALSE(Aj2->IsDirect());
1303   EXPECT_NE(Ii, Ai);
1304   EXPECT_NE(Jj1, Aj1);
1305   EXPECT_NE(Jj2, Aj2);
1306   EXPECT_EQ(Kj1, Jj1);
1307   EXPECT_EQ(Kj2, Jj2);
1308   EXPECT_EQ(Ai, A->FindVirtualMethodForInterface(Ii, kRuntimePointerSize));
1309   EXPECT_EQ(Aj1, A->FindVirtualMethodForInterface(Jj1, kRuntimePointerSize));
1310   EXPECT_EQ(Aj2, A->FindVirtualMethodForInterface(Jj2, kRuntimePointerSize));
1311   EXPECT_EQ(Ai, A->FindVirtualMethodForVirtualOrInterface(Ii, kRuntimePointerSize));
1312   EXPECT_EQ(Aj1, A->FindVirtualMethodForVirtualOrInterface(Jj1, kRuntimePointerSize));
1313   EXPECT_EQ(Aj2, A->FindVirtualMethodForVirtualOrInterface(Jj2, kRuntimePointerSize));
1314 
1315   ArtField* Afoo = A->FindStaticField("foo", "Ljava/lang/String;");
1316   ArtField* Bfoo = B->FindStaticField("foo", "Ljava/lang/String;");
1317   ArtField* Jfoo = J->FindStaticField("foo", "Ljava/lang/String;");
1318   ArtField* Kfoo = K->FindStaticField("foo", "Ljava/lang/String;");
1319   ASSERT_TRUE(Afoo != nullptr);
1320   EXPECT_EQ(Afoo, Bfoo);
1321   EXPECT_EQ(Afoo, Jfoo);
1322   EXPECT_EQ(Afoo, Kfoo);
1323 }
1324 
TEST_F(ClassLinkerTest,ResolveVerifyAndClinit)1325 TEST_F(ClassLinkerTest, ResolveVerifyAndClinit) {
1326   // pretend we are trying to get the static storage for the StaticsFromCode class.
1327 
1328   // case 1, get the uninitialized storage from StaticsFromCode.<clinit>
1329   // case 2, get the initialized storage from StaticsFromCode.getS0
1330 
1331   ScopedObjectAccess soa(Thread::Current());
1332   jobject jclass_loader = LoadDex("StaticsFromCode");
1333   const DexFile* dex_file = GetFirstDexFile(jclass_loader);
1334   StackHandleScope<1> hs(soa.Self());
1335   Handle<mirror::ClassLoader> class_loader(
1336       hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
1337   ObjPtr<mirror::Class> klass =
1338       class_linker_->FindClass(soa.Self(), "LStaticsFromCode;", class_loader);
1339   ArtMethod* clinit = klass->FindClassInitializer(kRuntimePointerSize);
1340   ArtMethod* getS0 =
1341       klass->FindClassMethod("getS0", "()Ljava/lang/Object;", kRuntimePointerSize);
1342   ASSERT_TRUE(getS0 != nullptr);
1343   ASSERT_TRUE(getS0->IsStatic());
1344   const dex::TypeId* type_id = dex_file->FindTypeId("LStaticsFromCode;");
1345   ASSERT_TRUE(type_id != nullptr);
1346   dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1347   ObjPtr<mirror::Class> uninit = ResolveVerifyAndClinit(type_idx,
1348                                                         clinit,
1349                                                         soa.Self(),
1350                                                         /* can_run_clinit= */ true,
1351                                                         /* verify_access= */ false);
1352   EXPECT_TRUE(uninit != nullptr);
1353   EXPECT_FALSE(uninit->IsInitialized());
1354   ObjPtr<mirror::Class> init = ResolveVerifyAndClinit(type_idx,
1355                                                       getS0,
1356                                                       soa.Self(),
1357                                                       /* can_run_clinit= */ true,
1358                                                       /* verify_access= */ false);
1359   EXPECT_TRUE(init != nullptr);
1360   EXPECT_TRUE(init->IsInitialized());
1361 }
1362 
TEST_F(ClassLinkerTest,ErroneousClass)1363 TEST_F(ClassLinkerTest, ErroneousClass) {
1364   ScopedObjectAccess soa(Thread::Current());
1365   jobject jclass_loader = LoadMultiDex("ErroneousA", "ErroneousB");
1366   StackHandleScope<1> hs(soa.Self());
1367   Handle<mirror::ClassLoader> class_loader(
1368       hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
1369   hs.Self()->AssertNoPendingException();
1370   const char* descriptor = "LErroneous;";
1371   ObjPtr<mirror::Class> klass = class_linker_->FindClass(soa.Self(), descriptor, class_loader);
1372   // Erronenous since we are extending final class.
1373   hs.Self()->AssertPendingException();
1374   EXPECT_TRUE(klass == nullptr);
1375   klass = class_linker_->LookupClass(soa.Self(), descriptor, class_loader.Get());
1376   EXPECT_FALSE(klass == nullptr);
1377   EXPECT_TRUE(klass->IsErroneous());
1378   EXPECT_TRUE(klass->GetIfTable() != nullptr);
1379 }
1380 
TEST_F(ClassLinkerTest,FinalizableBit)1381 TEST_F(ClassLinkerTest, FinalizableBit) {
1382   ScopedObjectAccess soa(Thread::Current());
1383   ObjPtr<mirror::Class> c;
1384 
1385   // Object has a finalize method, but we know it's empty.
1386   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;");
1387   EXPECT_FALSE(c->IsFinalizable());
1388 
1389   // Enum has a finalize method to prevent its subclasses from implementing one.
1390   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Enum;");
1391   EXPECT_FALSE(c->IsFinalizable());
1392 
1393   // RoundingMode is an enum.
1394   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/math/RoundingMode;");
1395   EXPECT_FALSE(c->IsFinalizable());
1396 
1397   // RandomAccessFile extends Object and overrides finalize.
1398   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/io/RandomAccessFile;");
1399   EXPECT_TRUE(c->IsFinalizable());
1400 
1401   // FileInputStream is finalizable and extends InputStream which isn't.
1402   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/io/InputStream;");
1403   EXPECT_FALSE(c->IsFinalizable());
1404   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/io/FileInputStream;");
1405   EXPECT_TRUE(c->IsFinalizable());
1406 
1407   // ScheduledThreadPoolExecutor doesn't have a finalize method but
1408   // extends ThreadPoolExecutor which does.
1409   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/util/concurrent/ThreadPoolExecutor;");
1410   EXPECT_TRUE(c->IsFinalizable());
1411   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/util/concurrent/ScheduledThreadPoolExecutor;");
1412   EXPECT_TRUE(c->IsFinalizable());
1413 }
1414 
TEST_F(ClassLinkerTest,ClassRootDescriptors)1415 TEST_F(ClassLinkerTest, ClassRootDescriptors) {
1416   ScopedObjectAccess soa(Thread::Current());
1417   std::string temp;
1418   for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1419     ObjPtr<mirror::Class> klass = GetClassRoot(ClassRoot(i), class_linker_);
1420     EXPECT_GT(strlen(klass->GetDescriptor(&temp)), 0U);
1421     EXPECT_STREQ(klass->GetDescriptor(&temp), GetClassRootDescriptor(ClassRoot(i))) << " i = " << i;
1422   }
1423 }
1424 
TEST_F(ClassLinkerTest,ValidatePredefinedClassSizes)1425 TEST_F(ClassLinkerTest, ValidatePredefinedClassSizes) {
1426   ScopedObjectAccess soa(Thread::Current());
1427   ScopedNullHandle<mirror::ClassLoader> class_loader;
1428   ObjPtr<mirror::Class> c;
1429 
1430   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Class;", class_loader);
1431   ASSERT_TRUE(c != nullptr);
1432   EXPECT_EQ(c->GetClassSize(), mirror::Class::ClassClassSize(kRuntimePointerSize));
1433 
1434   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Object;", class_loader);
1435   ASSERT_TRUE(c != nullptr);
1436   EXPECT_EQ(c->GetClassSize(), mirror::Object::ClassSize(kRuntimePointerSize));
1437 
1438   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/String;", class_loader);
1439   ASSERT_TRUE(c != nullptr);
1440   EXPECT_EQ(c->GetClassSize(), mirror::String::ClassSize(kRuntimePointerSize));
1441 
1442   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/DexCache;", class_loader);
1443   ASSERT_TRUE(c != nullptr);
1444   EXPECT_EQ(c->GetClassSize(), mirror::DexCache::ClassSize(kRuntimePointerSize));
1445 }
1446 
CheckMethod(ArtMethod * method,bool verified)1447 static void CheckMethod(ArtMethod* method, bool verified)
1448     REQUIRES_SHARED(Locks::mutator_lock_) {
1449   if (!method->IsNative() && !method->IsAbstract()) {
1450     EXPECT_EQ((method->GetAccessFlags() & kAccSkipAccessChecks) != 0U, verified)
1451         << method->PrettyMethod(true);
1452   }
1453 }
1454 
CheckVerificationAttempted(ObjPtr<mirror::Class> c,bool preverified)1455 static void CheckVerificationAttempted(ObjPtr<mirror::Class> c, bool preverified)
1456     REQUIRES_SHARED(Locks::mutator_lock_) {
1457   for (auto& m : c->GetMethods(kRuntimePointerSize)) {
1458     CheckMethod(&m, preverified);
1459   }
1460 }
1461 
TEST_F(ClassLinkerTest,Preverified_InitializedBoot)1462 TEST_F(ClassLinkerTest, Preverified_InitializedBoot) {
1463   ScopedObjectAccess soa(Thread::Current());
1464 
1465   ObjPtr<mirror::Class> JavaLangObject =
1466       class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;");
1467   ASSERT_TRUE(JavaLangObject != nullptr);
1468   EXPECT_TRUE(JavaLangObject->IsInitialized()) << "Not testing already initialized class from the "
1469                                                   "core";
1470   CheckVerificationAttempted(JavaLangObject, true);
1471 }
1472 
TEST_F(ClassLinkerTest,Preverified_UninitializedBoot)1473 TEST_F(ClassLinkerTest, Preverified_UninitializedBoot) {
1474   ScopedObjectAccess soa(Thread::Current());
1475 
1476   StackHandleScope<1> hs(soa.Self());
1477 
1478   Handle<mirror::Class> security_manager(hs.NewHandle(class_linker_->FindSystemClass(
1479       soa.Self(), "Ljava/lang/SecurityManager;")));
1480   EXPECT_FALSE(security_manager->IsInitialized()) << "Not testing uninitialized class from the "
1481                                                      "core";
1482 
1483   CheckVerificationAttempted(security_manager.Get(), false);
1484 
1485   class_linker_->EnsureInitialized(soa.Self(), security_manager, true, true);
1486   CheckVerificationAttempted(security_manager.Get(), true);
1487 }
1488 
TEST_F(ClassLinkerTest,Preverified_App)1489 TEST_F(ClassLinkerTest, Preverified_App) {
1490   ScopedObjectAccess soa(Thread::Current());
1491 
1492   StackHandleScope<2> hs(soa.Self());
1493   Handle<mirror::ClassLoader> class_loader(
1494       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Statics"))));
1495   Handle<mirror::Class> statics(
1496       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LStatics;", class_loader)));
1497 
1498   CheckVerificationAttempted(statics.Get(), false);
1499 
1500   class_linker_->EnsureInitialized(soa.Self(), statics, true, true);
1501   CheckVerificationAttempted(statics.Get(), true);
1502 }
1503 
TEST_F(ClassLinkerTest,IsBootStrapClassLoaded)1504 TEST_F(ClassLinkerTest, IsBootStrapClassLoaded) {
1505   ScopedObjectAccess soa(Thread::Current());
1506 
1507   StackHandleScope<3> hs(soa.Self());
1508   Handle<mirror::ClassLoader> class_loader(
1509       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Statics"))));
1510 
1511   // java.lang.Object is a bootstrap class.
1512   Handle<mirror::Class> jlo_class(
1513       hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;")));
1514   ASSERT_TRUE(jlo_class != nullptr);
1515   EXPECT_TRUE(jlo_class->IsBootStrapClassLoaded());
1516 
1517   // Statics is not a bootstrap class.
1518   Handle<mirror::Class> statics(
1519       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LStatics;", class_loader)));
1520   ASSERT_TRUE(statics != nullptr);
1521   EXPECT_FALSE(statics->IsBootStrapClassLoaded());
1522 }
1523 
1524 // Regression test for b/26799552.
TEST_F(ClassLinkerTest,RegisterDexFileName)1525 TEST_F(ClassLinkerTest, RegisterDexFileName) {
1526   ScopedObjectAccess soa(Thread::Current());
1527   StackHandleScope<2> hs(soa.Self());
1528   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1529   MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
1530   {
1531     ReaderMutexLock mu(soa.Self(), *Locks::dex_lock_);
1532     for (const auto& entry : class_linker->GetDexCachesData()) {
1533       const ClassLinker::DexCacheData& data = entry.second;
1534       dex_cache.Assign(soa.Self()->DecodeJObject(data.weak_root)->AsDexCache());
1535       if (dex_cache != nullptr) {
1536         break;
1537       }
1538     }
1539     ASSERT_TRUE(dex_cache != nullptr);
1540   }
1541   const uint16_t data[] = { 0x20AC, 0x20A1 };
1542   Handle<mirror::String> location(hs.NewHandle(mirror::String::AllocFromUtf16(soa.Self(),
1543                                                                               arraysize(data),
1544                                                                               data)));
1545   const DexFile* old_dex_file = dex_cache->GetDexFile();
1546 
1547   auto container =
1548       std::make_shared<MemoryDexFileContainer>(old_dex_file->Begin(), old_dex_file->Size());
1549   std::unique_ptr<DexFile> dex_file(new StandardDexFile(
1550       old_dex_file->Begin(), location->ToModifiedUtf8(), 0u, nullptr, std::move(container)));
1551   // Make a copy of the dex cache with changed name.
1552   dex_cache.Assign(class_linker->AllocAndInitializeDexCache(Thread::Current(),
1553                                                             *dex_file,
1554                                                             /* class_loader= */ nullptr));
1555   DCHECK_EQ(dex_cache->GetLocation()->CompareTo(location.Get()), 0);
1556   {
1557     WriterMutexLock mu(soa.Self(), *Locks::dex_lock_);
1558     // Check that inserting with a UTF16 name works.
1559     class_linker->RegisterDexFileLocked(*dex_file, dex_cache.Get(), /* class_loader= */ nullptr);
1560   }
1561 }
1562 
TEST_F(ClassLinkerMethodHandlesTest,TestResolveMethodTypes)1563 TEST_F(ClassLinkerMethodHandlesTest, TestResolveMethodTypes) {
1564   ScopedObjectAccess soa(Thread::Current());
1565   StackHandleScope<7> hs(soa.Self());
1566 
1567   Handle<mirror::ClassLoader> class_loader(
1568       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MethodTypes"))));
1569   Handle<mirror::Class> method_types(
1570       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LMethodTypes;", class_loader)));
1571   class_linker_->EnsureInitialized(soa.Self(), method_types, true, true);
1572 
1573   ArtMethod* method1 = method_types->FindClassMethod(
1574       "method1",
1575       "(Ljava/lang/String;)Ljava/lang/String;",
1576       kRuntimePointerSize);
1577   ASSERT_TRUE(method1 != nullptr);
1578   ASSERT_FALSE(method1->IsDirect());
1579 
1580   const DexFile& dex_file = *(method1->GetDexFile());
1581   Handle<mirror::DexCache> dex_cache = hs.NewHandle(
1582       class_linker_->FindDexCache(soa.Self(), dex_file));
1583 
1584   const dex::MethodId& method1_id = dex_file.GetMethodId(method1->GetDexMethodIndex());
1585 
1586   // This is the MethodType corresponding to the prototype of
1587   // String MethodTypes# method1(String).
1588   // Its RType = Ljava/lang/String;
1589   // Its PTypes = { Ljava/lang/String; }
1590   Handle<mirror::MethodType> method1_type = hs.NewHandle(
1591       class_linker_->ResolveMethodType(soa.Self(), method1_id.proto_idx_, dex_cache, class_loader));
1592 
1593   // Assert that the method type was resolved successfully.
1594   ASSERT_TRUE(method1_type != nullptr);
1595 
1596   // Assert that the return type and the method arguments are as we expect.
1597   Handle<mirror::Class> string_class(hs.NewHandle(class_linker_->FindClass(soa.Self(),
1598                                                                            "Ljava/lang/String;",
1599                                                                            class_loader)));
1600   ASSERT_OBJ_PTR_EQ(string_class.Get(), method1_type->GetRType());
1601   ASSERT_OBJ_PTR_EQ(string_class.Get(), method1_type->GetPTypes()->Get(0));
1602 
1603   // Resolve the method type again and assert that we get back the same value.
1604   Handle<mirror::MethodType> method1_type2 = hs.NewHandle(
1605       class_linker_->ResolveMethodType(soa.Self(), method1_id.proto_idx_, dex_cache, class_loader));
1606   ASSERT_OBJ_PTR_EQ(method1_type.Get(), method1_type2.Get());
1607 
1608   // Resolve the MethodType associated with a different method signature
1609   // and assert it's different.
1610   ArtMethod* method2 = method_types->FindClassMethod(
1611       "method2",
1612       "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
1613       kRuntimePointerSize);
1614   ASSERT_TRUE(method2 != nullptr);
1615   ASSERT_FALSE(method2->IsDirect());
1616   const dex::MethodId& method2_id = dex_file.GetMethodId(method2->GetDexMethodIndex());
1617   Handle<mirror::MethodType> method2_type = hs.NewHandle(
1618       class_linker_->ResolveMethodType(soa.Self(), method2_id.proto_idx_, dex_cache, class_loader));
1619   ASSERT_OBJ_PTR_NE(method1_type.Get(), method2_type.Get());
1620 }
1621 
1622 // Verify that ClassLinker's CreateWellknownClassLoader works as expected
1623 // by creating a chain of class loaders with various dex files.
TEST_F(ClassLinkerTest,CreateWellKnownClassLoader)1624 TEST_F(ClassLinkerTest, CreateWellKnownClassLoader) {
1625   // LoadDexIn*ClassLoader methods already assert that the parent loader is the expected one.
1626   // No need to check again.
1627   jobject class_loader_a = LoadDexInPathClassLoader("MyClass", nullptr);
1628   jobject class_loader_b = LoadDexInDelegateLastClassLoader("Nested", class_loader_a);
1629   jobject class_loader_c = LoadDexInPathClassLoader("MultiDex", class_loader_b);
1630   LoadDexInDelegateLastClassLoader("Interfaces", class_loader_c);
1631 }
1632 
TEST_F(ClassLinkerTest,PrettyClass)1633 TEST_F(ClassLinkerTest, PrettyClass) {
1634   ScopedObjectAccess soa(Thread::Current());
1635   EXPECT_EQ("null", mirror::Class::PrettyClass(nullptr));
1636   ObjPtr<mirror::Class> c = class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/String;");
1637   ASSERT_TRUE(c != nullptr);
1638   ObjPtr<mirror::Object> o = mirror::ObjectArray<mirror::String>::Alloc(soa.Self(), c, 0);
1639   EXPECT_EQ("java.lang.Class<java.lang.String[]>", mirror::Class::PrettyClass(o->GetClass()));
1640 }
1641 
TEST_F(ClassLinkerTest,PrettyClassAndClassLoader)1642 TEST_F(ClassLinkerTest, PrettyClassAndClassLoader) {
1643   ScopedObjectAccess soa(Thread::Current());
1644   EXPECT_EQ("null", mirror::Class::PrettyClassAndClassLoader(nullptr));
1645   ObjPtr<mirror::Class> c = class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/String;");
1646   ASSERT_TRUE(c != nullptr);
1647   ObjPtr<mirror::Object> o = mirror::ObjectArray<mirror::String>::Alloc(soa.Self(), c, 0);
1648   EXPECT_EQ("java.lang.Class<java.lang.String[],null>",
1649             mirror::Class::PrettyClassAndClassLoader(o->GetClass()));
1650 }
1651 
TEST_F(ClassLinkerTest,PrettyField)1652 TEST_F(ClassLinkerTest, PrettyField) {
1653   ScopedObjectAccess soa(Thread::Current());
1654   EXPECT_EQ("null", ArtField::PrettyField(nullptr));
1655 
1656   ObjPtr<mirror::Class> java_lang_String = class_linker_->FindSystemClass(soa.Self(),
1657                                                                           "Ljava/lang/String;");
1658 
1659   ArtField* f;
1660   f = java_lang_String->FindDeclaredInstanceField("count", "I");
1661   EXPECT_EQ("int java.lang.String.count", f->PrettyField());
1662   EXPECT_EQ("java.lang.String.count", f->PrettyField(false));
1663 }
1664 
TEST_F(ClassLinkerTest,JniShortName_JniLongName)1665 TEST_F(ClassLinkerTest, JniShortName_JniLongName) {
1666   ScopedObjectAccess soa(Thread::Current());
1667   ObjPtr<mirror::Class> c = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/String;");
1668   ASSERT_TRUE(c != nullptr);
1669   ArtMethod* m;
1670 
1671   m = c->FindClassMethod("charAt", "(I)C", kRuntimePointerSize);
1672   ASSERT_TRUE(m != nullptr);
1673   ASSERT_FALSE(m->IsDirect());
1674   EXPECT_EQ("Java_java_lang_String_charAt", m->JniShortName());
1675   EXPECT_EQ("Java_java_lang_String_charAt__I", m->JniLongName());
1676 
1677   m = c->FindClassMethod("indexOf", "(Ljava/lang/String;I)I", kRuntimePointerSize);
1678   ASSERT_TRUE(m != nullptr);
1679   ASSERT_FALSE(m->IsDirect());
1680   EXPECT_EQ("Java_java_lang_String_indexOf", m->JniShortName());
1681   EXPECT_EQ("Java_java_lang_String_indexOf__Ljava_lang_String_2I", m->JniLongName());
1682 
1683   m = c->FindClassMethod("copyValueOf", "([CII)Ljava/lang/String;", kRuntimePointerSize);
1684   ASSERT_TRUE(m != nullptr);
1685   ASSERT_TRUE(m->IsStatic());
1686   EXPECT_EQ("Java_java_lang_String_copyValueOf", m->JniShortName());
1687   EXPECT_EQ("Java_java_lang_String_copyValueOf___3CII", m->JniLongName());
1688 }
1689 
1690 class ClassLinkerClassLoaderTest : public ClassLinkerTest {
1691  protected:
1692   // Verifies that the class identified by the given descriptor is loaded with
1693   // the expected_class_loader_obj when search from class_loader_to_search_obj.
1694   // When expected_class_loader_obj is null the check will be done against BootClassLoader.
VerifyClassResolution(const std::string & descriptor,jobject class_loader_to_search_obj,jobject expected_class_loader_obj,bool should_find=true)1695   void VerifyClassResolution(const std::string& descriptor,
1696                              jobject class_loader_to_search_obj,
1697                              jobject expected_class_loader_obj,
1698                              bool should_find = true) {
1699     Thread* self = Thread::Current();
1700     ScopedObjectAccess soa(self);
1701     StackHandleScope<3> hs(self);
1702     Handle<mirror::ClassLoader> class_loader_to_search(
1703         hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader_to_search_obj)));
1704 
1705     Handle<mirror::Class> klass = hs.NewHandle(
1706         class_linker_->FindClass(soa.Self(), descriptor.c_str(), class_loader_to_search));
1707 
1708     if (!should_find) {
1709       if (self->IsExceptionPending()) {
1710         self->ClearException();
1711       }
1712       ASSERT_TRUE(klass == nullptr);
1713     } else if (expected_class_loader_obj == nullptr) {
1714       ASSERT_TRUE(ClassLinker::IsBootClassLoader(klass->GetClassLoader()));
1715     } else {
1716       ASSERT_TRUE(klass != nullptr) << descriptor;
1717       Handle<mirror::ClassLoader> expected_class_loader(
1718           hs.NewHandle(soa.Decode<mirror::ClassLoader>(expected_class_loader_obj)));
1719       ASSERT_OBJ_PTR_EQ(klass->GetClassLoader(), expected_class_loader.Get());
1720     }
1721   }
1722 };
1723 
TEST_F(ClassLinkerClassLoaderTest,CreatePathClassLoader)1724 TEST_F(ClassLinkerClassLoaderTest, CreatePathClassLoader) {
1725   jobject class_loader_a = LoadDexInPathClassLoader("ForClassLoaderA", nullptr);
1726   VerifyClassResolution("LDefinedInA;", class_loader_a, class_loader_a);
1727   VerifyClassResolution("Ljava/lang/String;", class_loader_a, nullptr);
1728   VerifyClassResolution("LDefinedInB;", class_loader_a, nullptr, /*should_find=*/ false);
1729 }
1730 
TEST_F(ClassLinkerClassLoaderTest,CreateDelegateLastClassLoader)1731 TEST_F(ClassLinkerClassLoaderTest, CreateDelegateLastClassLoader) {
1732   jobject class_loader_a = LoadDexInDelegateLastClassLoader("ForClassLoaderA", nullptr);
1733   VerifyClassResolution("LDefinedInA;", class_loader_a, class_loader_a);
1734   VerifyClassResolution("Ljava/lang/String;", class_loader_a, nullptr);
1735   VerifyClassResolution("LDefinedInB;", class_loader_a, nullptr, /*should_find=*/ false);
1736 }
1737 
TEST_F(ClassLinkerClassLoaderTest,CreateClassLoaderChain)1738 TEST_F(ClassLinkerClassLoaderTest, CreateClassLoaderChain) {
1739   // The chain is
1740   //    ClassLoaderA (PathClassLoader, defines: A, AB, AC, AD)
1741   //       ^
1742   //       |
1743   //    ClassLoaderB (DelegateLastClassLoader, defines: B, AB, BC, BD)
1744   //       ^
1745   //       |
1746   //    ClassLoaderC (PathClassLoader, defines: C, AC, BC, CD)
1747   //       ^
1748   //       |
1749   //    ClassLoaderD (DelegateLastClassLoader, defines: D, AD, BD, CD)
1750 
1751   jobject class_loader_a = LoadDexInPathClassLoader("ForClassLoaderA", nullptr);
1752   jobject class_loader_b = LoadDexInDelegateLastClassLoader("ForClassLoaderB", class_loader_a);
1753   jobject class_loader_c = LoadDexInPathClassLoader("ForClassLoaderC", class_loader_b);
1754   jobject class_loader_d = LoadDexInDelegateLastClassLoader("ForClassLoaderD", class_loader_c);
1755 
1756   // Verify exclusive classes (present in only one class loader).
1757   VerifyClassResolution("LDefinedInD;", class_loader_d, class_loader_d);
1758   VerifyClassResolution("LDefinedInC;", class_loader_d, class_loader_c);
1759   VerifyClassResolution("LDefinedInB;", class_loader_d, class_loader_b);
1760   VerifyClassResolution("LDefinedInA;", class_loader_d, class_loader_a);
1761 
1762   // Verify classes that are defined in multiple classloader.
1763 
1764   // Classes defined in B should be found in B even if they are defined in A or C because
1765   // B is a DelegateLastClassLoader.
1766   VerifyClassResolution("LDefinedInAB;", class_loader_d, class_loader_b);
1767   VerifyClassResolution("LDefinedInABC;", class_loader_d, class_loader_b);
1768   VerifyClassResolution("LDefinedInBC;", class_loader_d, class_loader_b);
1769 
1770   // Classes defined in D should be found in D even if they are defined in parent class loaders
1771   // as well because D is a DelegateLastClassLoader.
1772   VerifyClassResolution("LDefinedInAD;", class_loader_d, class_loader_d);
1773   VerifyClassResolution("LDefinedInBD;", class_loader_d, class_loader_d);
1774   VerifyClassResolution("LDefinedInCD;", class_loader_d, class_loader_d);
1775 
1776 
1777   // Classes not defined in the DelegateLastClassLoaders (i.e. D or B) should be found
1778   // in the top parent.
1779   VerifyClassResolution("LDefinedInAC;", class_loader_d, class_loader_a);
1780 
1781   // Check that we don't find an undefined class.
1782   VerifyClassResolution("LNotDefined;", class_loader_d, nullptr, /*should_find=*/ false);
1783 }
1784 
1785 }  // namespace art
1786