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