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-inl.h"
30 #include "common_runtime_test.h"
31 #include "dex/dex_file_types.h"
32 #include "dex/signature-inl.h"
33 #include "dex/standard_dex_file.h"
34 #include "entrypoints/entrypoint_utils-inl.h"
35 #include "experimental_flags.h"
36 #include "gc/heap.h"
37 #include "handle_scope-inl.h"
38 #include "mirror/array-alloc-inl.h"
39 #include "mirror/accessible_object.h"
40 #include "mirror/call_site.h"
41 #include "mirror/class-inl.h"
42 #include "mirror/class_ext.h"
43 #include "mirror/dex_cache.h"
44 #include "mirror/emulated_stack_frame.h"
45 #include "mirror/executable.h"
46 #include "mirror/field.h"
47 #include "mirror/method_handle_impl.h"
48 #include "mirror/method_handles_lookup.h"
49 #include "mirror/method_type-inl.h"
50 #include "mirror/object-inl.h"
51 #include "mirror/object_array-alloc-inl.h"
52 #include "mirror/object_array-inl.h"
53 #include "mirror/proxy.h"
54 #include "mirror/reference.h"
55 #include "mirror/stack_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       // The RoundUp is required for some mirror classes that have a gap at the end,
489       // such as AccessibleObject, ByteArrayViewVarHandle and ByteBufferViewVarHandle.
490       // For example, the AccessibleObject has size 9 according to the class linker.
491       // However, the C++ sizeof(AccessibleObject) is 12 bytes due to alignment, even
492       // though members in C++ subclasses are actually starting at offset 9.
493       //
494       // TODO: We could define a subclass with a `uint8_t` member and check its offset instead.
495       static constexpr size_t kPackAlignment = 4;
496       size_t expected_size = RoundUp(klass->GetObjectSize(), kPackAlignment);
497       if (sizeof(T) != expected_size) {
498         LOG(ERROR) << "Class size mismatch:"
499            << " class=" << class_descriptor
500            << " Java=" << expected_size
501            << " C++=" << sizeof(T);
502         error = true;
503       }
504     }
505 
506     size_t num_fields = is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
507     if (offsets.size() != num_fields) {
508       LOG(ERROR) << "Field count mismatch:"
509          << " class=" << class_descriptor
510          << " Java=" << num_fields
511          << " C++=" << offsets.size();
512       error = true;
513     }
514 
515     for (size_t i = 0; i < offsets.size(); i++) {
516       ArtField* field = is_static ? klass->GetStaticField(i) : klass->GetInstanceField(i);
517       std::string_view field_name(field->GetName());
518       if (field_name != offsets[i].java_name) {
519         error = true;
520       }
521     }
522     if (error) {
523       for (size_t i = 0; i < offsets.size(); i++) {
524         CheckOffset& offset = offsets[i];
525         ArtField* field = is_static ? klass->GetStaticField(i) : klass->GetInstanceField(i);
526         std::string_view field_name(field->GetName());
527         if (field_name != offsets[i].java_name) {
528           LOG(ERROR) << "JAVA FIELD ORDER MISMATCH NEXT LINE:";
529         }
530         LOG(ERROR) << "Java field order:"
531            << " i=" << i << " class=" << class_descriptor
532            << " Java=" << field_name
533            << " CheckOffsets=" << offset.java_name;
534       }
535     }
536 
537     for (size_t i = 0; i < offsets.size(); i++) {
538       CheckOffset& offset = offsets[i];
539       ArtField* field = is_static ? klass->GetStaticField(i) : klass->GetInstanceField(i);
540       if (field->GetOffset().Uint32Value() != offset.cpp_offset) {
541         error = true;
542       }
543     }
544     if (error) {
545       for (size_t i = 0; i < offsets.size(); i++) {
546         CheckOffset& offset = offsets[i];
547         ArtField* field = is_static ? klass->GetStaticField(i) : klass->GetInstanceField(i);
548         if (field->GetOffset().Uint32Value() != offset.cpp_offset) {
549           LOG(ERROR) << "OFFSET MISMATCH NEXT LINE:";
550         }
551         LOG(ERROR) << "Offset: class=" << class_descriptor << " field=" << offset.java_name
552            << " Java=" << field->GetOffset().Uint32Value() << " C++=" << offset.cpp_offset;
553       }
554     }
555 
556     return !error;
557   };
558 
addOffsetart::CheckOffsets559   void addOffset(size_t offset, const char* name) {
560     offsets.push_back(CheckOffset(offset, name));
561   }
562 
563  private:
564   DISALLOW_IMPLICIT_CONSTRUCTORS(CheckOffsets);
565 };
566 
567 // Note that ClassLinkerTest.ValidateFieldOrderOfJavaCppUnionClasses
568 // is first since if it is failing, others are unlikely to succeed.
569 
570 struct ObjectOffsets : public CheckOffsets<mirror::Object> {
ObjectOffsetsart::ObjectOffsets571   ObjectOffsets() : CheckOffsets<mirror::Object>(false, "Ljava/lang/Object;") {
572     addOffset(OFFSETOF_MEMBER(mirror::Object, klass_), "shadow$_klass_");
573     addOffset(OFFSETOF_MEMBER(mirror::Object, monitor_), "shadow$_monitor_");
574 #ifdef USE_BROOKS_READ_BARRIER
575     addOffset(OFFSETOF_MEMBER(mirror::Object, x_rb_ptr_), "shadow$_x_rb_ptr_");
576     addOffset(OFFSETOF_MEMBER(mirror::Object, x_xpadding_), "shadow$_x_xpadding_");
577 #endif
578   }
579 };
580 
581 struct ClassOffsets : public CheckOffsets<mirror::Class> {
ClassOffsetsart::ClassOffsets582   ClassOffsets() : CheckOffsets<mirror::Class>(false, "Ljava/lang/Class;") {
583     addOffset(OFFSETOF_MEMBER(mirror::Class, access_flags_), "accessFlags");
584     addOffset(OFFSETOF_MEMBER(mirror::Class, class_flags_), "classFlags");
585     addOffset(OFFSETOF_MEMBER(mirror::Class, class_loader_), "classLoader");
586     addOffset(OFFSETOF_MEMBER(mirror::Class, class_size_), "classSize");
587     addOffset(OFFSETOF_MEMBER(mirror::Class, clinit_thread_id_), "clinitThreadId");
588     addOffset(OFFSETOF_MEMBER(mirror::Class, component_type_), "componentType");
589     addOffset(OFFSETOF_MEMBER(mirror::Class, copied_methods_offset_), "copiedMethodsOffset");
590     addOffset(OFFSETOF_MEMBER(mirror::Class, dex_cache_), "dexCache");
591     addOffset(OFFSETOF_MEMBER(mirror::Class, dex_class_def_idx_), "dexClassDefIndex");
592     addOffset(OFFSETOF_MEMBER(mirror::Class, dex_type_idx_), "dexTypeIndex");
593     addOffset(OFFSETOF_MEMBER(mirror::Class, ext_data_), "extData");
594     addOffset(OFFSETOF_MEMBER(mirror::Class, ifields_), "iFields");
595     addOffset(OFFSETOF_MEMBER(mirror::Class, iftable_), "ifTable");
596     addOffset(OFFSETOF_MEMBER(mirror::Class, methods_), "methods");
597     addOffset(OFFSETOF_MEMBER(mirror::Class, name_), "name");
598     addOffset(OFFSETOF_MEMBER(mirror::Class, num_reference_instance_fields_),
599               "numReferenceInstanceFields");
600     addOffset(OFFSETOF_MEMBER(mirror::Class, num_reference_static_fields_),
601               "numReferenceStaticFields");
602     addOffset(OFFSETOF_MEMBER(mirror::Class, object_size_), "objectSize");
603     addOffset(OFFSETOF_MEMBER(mirror::Class, object_size_alloc_fast_path_),
604               "objectSizeAllocFastPath");
605     addOffset(OFFSETOF_MEMBER(mirror::Class, primitive_type_), "primitiveType");
606     addOffset(OFFSETOF_MEMBER(mirror::Class, reference_instance_offsets_),
607               "referenceInstanceOffsets");
608     addOffset(OFFSETOF_MEMBER(mirror::Class, sfields_), "sFields");
609     addOffset(OFFSETOF_MEMBER(mirror::Class, status_), "status");
610     addOffset(OFFSETOF_MEMBER(mirror::Class, super_class_), "superClass");
611     addOffset(OFFSETOF_MEMBER(mirror::Class, virtual_methods_offset_), "virtualMethodsOffset");
612     addOffset(OFFSETOF_MEMBER(mirror::Class, vtable_), "vtable");
613   }
614 };
615 
616 struct ClassExtOffsets : public CheckOffsets<mirror::ClassExt> {
ClassExtOffsetsart::ClassExtOffsets617   ClassExtOffsets() : CheckOffsets<mirror::ClassExt>(false, "Ldalvik/system/ClassExt;") {
618     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, instance_jfield_ids_), "instanceJfieldIDs");
619     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, jmethod_ids_), "jmethodIDs");
620     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, obsolete_class_), "obsoleteClass");
621     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, obsolete_dex_caches_), "obsoleteDexCaches");
622     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, obsolete_methods_), "obsoleteMethods");
623     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, original_dex_file_), "originalDexFile");
624     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, pre_redefine_class_def_index_),
625               "preRedefineClassDefIndex");
626     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, pre_redefine_dex_file_ptr_),
627               "preRedefineDexFilePtr");
628     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, static_jfield_ids_), "staticJfieldIDs");
629     addOffset(OFFSETOF_MEMBER(mirror::ClassExt, verify_error_), "verifyError");
630   }
631 };
632 
633 struct StringOffsets : public CheckOffsets<mirror::String> {
StringOffsetsart::StringOffsets634   StringOffsets() : CheckOffsets<mirror::String>(false, "Ljava/lang/String;") {
635     addOffset(OFFSETOF_MEMBER(mirror::String, count_), "count");
636     addOffset(OFFSETOF_MEMBER(mirror::String, hash_code_), "hash");
637   }
638 };
639 
640 struct ThrowableOffsets : public CheckOffsets<mirror::Throwable> {
ThrowableOffsetsart::ThrowableOffsets641   ThrowableOffsets() : CheckOffsets<mirror::Throwable>(false, "Ljava/lang/Throwable;") {
642     addOffset(OFFSETOF_MEMBER(mirror::Throwable, backtrace_), "backtrace");
643     addOffset(OFFSETOF_MEMBER(mirror::Throwable, cause_), "cause");
644     addOffset(OFFSETOF_MEMBER(mirror::Throwable, detail_message_), "detailMessage");
645     addOffset(OFFSETOF_MEMBER(mirror::Throwable, stack_trace_), "stackTrace");
646     addOffset(OFFSETOF_MEMBER(mirror::Throwable, suppressed_exceptions_), "suppressedExceptions");
647   }
648 };
649 
650 struct StackTraceElementOffsets : public CheckOffsets<mirror::StackTraceElement> {
StackTraceElementOffsetsart::StackTraceElementOffsets651   StackTraceElementOffsets() : CheckOffsets<mirror::StackTraceElement>(
652       false, "Ljava/lang/StackTraceElement;") {
653     addOffset(OFFSETOF_MEMBER(mirror::StackTraceElement, declaring_class_), "declaringClass");
654     addOffset(OFFSETOF_MEMBER(mirror::StackTraceElement, file_name_), "fileName");
655     addOffset(OFFSETOF_MEMBER(mirror::StackTraceElement, line_number_), "lineNumber");
656     addOffset(OFFSETOF_MEMBER(mirror::StackTraceElement, method_name_), "methodName");
657   }
658 };
659 
660 struct ClassLoaderOffsets : public CheckOffsets<mirror::ClassLoader> {
ClassLoaderOffsetsart::ClassLoaderOffsets661   ClassLoaderOffsets() : CheckOffsets<mirror::ClassLoader>(false, "Ljava/lang/ClassLoader;") {
662     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, allocator_), "allocator");
663     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, class_table_), "classTable");
664     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, packages_), "packages");
665     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, parent_), "parent");
666     addOffset(OFFSETOF_MEMBER(mirror::ClassLoader, proxyCache_), "proxyCache");
667   }
668 };
669 
670 struct ProxyOffsets : public CheckOffsets<mirror::Proxy> {
ProxyOffsetsart::ProxyOffsets671   ProxyOffsets() : CheckOffsets<mirror::Proxy>(false, "Ljava/lang/reflect/Proxy;") {
672     addOffset(OFFSETOF_MEMBER(mirror::Proxy, h_), "h");
673   }
674 };
675 
676 struct DexCacheOffsets : public CheckOffsets<mirror::DexCache> {
DexCacheOffsetsart::DexCacheOffsets677   DexCacheOffsets() : CheckOffsets<mirror::DexCache>(false, "Ljava/lang/DexCache;") {
678     addOffset(OFFSETOF_MEMBER(mirror::DexCache, class_loader_), "classLoader");
679     addOffset(OFFSETOF_MEMBER(mirror::DexCache, dex_file_), "dexFile");
680     addOffset(OFFSETOF_MEMBER(mirror::DexCache, location_), "location");
681     addOffset(OFFSETOF_MEMBER(mirror::DexCache, num_preresolved_strings_), "numPreResolvedStrings");
682     addOffset(OFFSETOF_MEMBER(mirror::DexCache, num_resolved_call_sites_), "numResolvedCallSites");
683     addOffset(OFFSETOF_MEMBER(mirror::DexCache, num_resolved_fields_), "numResolvedFields");
684     addOffset(OFFSETOF_MEMBER(mirror::DexCache, num_resolved_method_types_), "numResolvedMethodTypes");
685     addOffset(OFFSETOF_MEMBER(mirror::DexCache, num_resolved_methods_), "numResolvedMethods");
686     addOffset(OFFSETOF_MEMBER(mirror::DexCache, num_resolved_types_), "numResolvedTypes");
687     addOffset(OFFSETOF_MEMBER(mirror::DexCache, num_strings_), "numStrings");
688     addOffset(OFFSETOF_MEMBER(mirror::DexCache, preresolved_strings_), "preResolvedStrings");
689     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_call_sites_), "resolvedCallSites");
690     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_fields_), "resolvedFields");
691     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_method_types_), "resolvedMethodTypes");
692     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_methods_), "resolvedMethods");
693     addOffset(OFFSETOF_MEMBER(mirror::DexCache, resolved_types_), "resolvedTypes");
694     addOffset(OFFSETOF_MEMBER(mirror::DexCache, strings_), "strings");
695   }
696 };
697 
698 struct ReferenceOffsets : public CheckOffsets<mirror::Reference> {
ReferenceOffsetsart::ReferenceOffsets699   ReferenceOffsets() : CheckOffsets<mirror::Reference>(false, "Ljava/lang/ref/Reference;") {
700     addOffset(OFFSETOF_MEMBER(mirror::Reference, pending_next_), "pendingNext");
701     addOffset(OFFSETOF_MEMBER(mirror::Reference, queue_), "queue");
702     addOffset(OFFSETOF_MEMBER(mirror::Reference, queue_next_), "queueNext");
703     addOffset(OFFSETOF_MEMBER(mirror::Reference, referent_), "referent");
704   }
705 };
706 
707 struct FinalizerReferenceOffsets : public CheckOffsets<mirror::FinalizerReference> {
FinalizerReferenceOffsetsart::FinalizerReferenceOffsets708   FinalizerReferenceOffsets() : CheckOffsets<mirror::FinalizerReference>(
709       false, "Ljava/lang/ref/FinalizerReference;") {
710     addOffset(OFFSETOF_MEMBER(mirror::FinalizerReference, next_), "next");
711     addOffset(OFFSETOF_MEMBER(mirror::FinalizerReference, prev_), "prev");
712     addOffset(OFFSETOF_MEMBER(mirror::FinalizerReference, zombie_), "zombie");
713   }
714 };
715 
716 struct AccessibleObjectOffsets : public CheckOffsets<mirror::AccessibleObject> {
AccessibleObjectOffsetsart::AccessibleObjectOffsets717   AccessibleObjectOffsets() : CheckOffsets<mirror::AccessibleObject>(
718       false, "Ljava/lang/reflect/AccessibleObject;") {
719     addOffset(mirror::AccessibleObject::FlagOffset().Uint32Value(), "override");
720   }
721 };
722 
723 struct FieldOffsets : public CheckOffsets<mirror::Field> {
FieldOffsetsart::FieldOffsets724   FieldOffsets() : CheckOffsets<mirror::Field>(false, "Ljava/lang/reflect/Field;") {
725     addOffset(OFFSETOF_MEMBER(mirror::Field, access_flags_), "accessFlags");
726     addOffset(OFFSETOF_MEMBER(mirror::Field, art_field_index_), "artFieldIndex");
727     addOffset(OFFSETOF_MEMBER(mirror::Field, declaring_class_), "declaringClass");
728     addOffset(OFFSETOF_MEMBER(mirror::Field, offset_), "offset");
729     addOffset(OFFSETOF_MEMBER(mirror::Field, type_), "type");
730   }
731 };
732 
733 struct ExecutableOffsets : public CheckOffsets<mirror::Executable> {
ExecutableOffsetsart::ExecutableOffsets734   ExecutableOffsets() : CheckOffsets<mirror::Executable>(
735       false, "Ljava/lang/reflect/Executable;") {
736     addOffset(OFFSETOF_MEMBER(mirror::Executable, access_flags_), "accessFlags");
737     addOffset(OFFSETOF_MEMBER(mirror::Executable, art_method_), "artMethod");
738     addOffset(OFFSETOF_MEMBER(mirror::Executable, declaring_class_), "declaringClass");
739     addOffset(OFFSETOF_MEMBER(mirror::Executable, declaring_class_of_overridden_method_),
740               "declaringClassOfOverriddenMethod");
741     addOffset(OFFSETOF_MEMBER(mirror::Executable, dex_method_index_), "dexMethodIndex");
742     addOffset(OFFSETOF_MEMBER(mirror::Executable, has_real_parameter_data_),
743               "hasRealParameterData");
744     addOffset(OFFSETOF_MEMBER(mirror::Executable, parameters_), "parameters");
745   }
746 };
747 
748 struct MethodTypeOffsets : public CheckOffsets<mirror::MethodType> {
MethodTypeOffsetsart::MethodTypeOffsets749   MethodTypeOffsets() : CheckOffsets<mirror::MethodType>(
750       false, "Ljava/lang/invoke/MethodType;") {
751     addOffset(OFFSETOF_MEMBER(mirror::MethodType, form_), "form");
752     addOffset(OFFSETOF_MEMBER(mirror::MethodType, method_descriptor_), "methodDescriptor");
753     addOffset(OFFSETOF_MEMBER(mirror::MethodType, p_types_), "ptypes");
754     addOffset(OFFSETOF_MEMBER(mirror::MethodType, r_type_), "rtype");
755     addOffset(OFFSETOF_MEMBER(mirror::MethodType, wrap_alt_), "wrapAlt");
756   }
757 };
758 
759 struct MethodHandleOffsets : public CheckOffsets<mirror::MethodHandle> {
MethodHandleOffsetsart::MethodHandleOffsets760   MethodHandleOffsets() : CheckOffsets<mirror::MethodHandle>(
761       false, "Ljava/lang/invoke/MethodHandle;") {
762     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, art_field_or_method_), "artFieldOrMethod");
763     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, cached_spread_invoker_),
764               "cachedSpreadInvoker");
765     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, handle_kind_), "handleKind");
766     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, nominal_type_), "nominalType");
767     addOffset(OFFSETOF_MEMBER(mirror::MethodHandle, method_type_), "type");
768   }
769 };
770 
771 struct MethodHandleImplOffsets : public CheckOffsets<mirror::MethodHandleImpl> {
MethodHandleImplOffsetsart::MethodHandleImplOffsets772   MethodHandleImplOffsets() : CheckOffsets<mirror::MethodHandleImpl>(
773       false, "Ljava/lang/invoke/MethodHandleImpl;") {
774     addOffset(OFFSETOF_MEMBER(mirror::MethodHandleImpl, info_), "info");
775   }
776 };
777 
778 struct MethodHandlesLookupOffsets : public CheckOffsets<mirror::MethodHandlesLookup> {
MethodHandlesLookupOffsetsart::MethodHandlesLookupOffsets779   MethodHandlesLookupOffsets() : CheckOffsets<mirror::MethodHandlesLookup>(
780       false, "Ljava/lang/invoke/MethodHandles$Lookup;") {
781     addOffset(OFFSETOF_MEMBER(mirror::MethodHandlesLookup, allowed_modes_), "allowedModes");
782     addOffset(OFFSETOF_MEMBER(mirror::MethodHandlesLookup, lookup_class_), "lookupClass");
783   }
784 };
785 
786 struct EmulatedStackFrameOffsets : public CheckOffsets<mirror::EmulatedStackFrame> {
EmulatedStackFrameOffsetsart::EmulatedStackFrameOffsets787   EmulatedStackFrameOffsets() : CheckOffsets<mirror::EmulatedStackFrame>(
788       false, "Ldalvik/system/EmulatedStackFrame;") {
789     addOffset(OFFSETOF_MEMBER(mirror::EmulatedStackFrame, callsite_type_), "callsiteType");
790     addOffset(OFFSETOF_MEMBER(mirror::EmulatedStackFrame, references_), "references");
791     addOffset(OFFSETOF_MEMBER(mirror::EmulatedStackFrame, stack_frame_), "stackFrame");
792     addOffset(OFFSETOF_MEMBER(mirror::EmulatedStackFrame, type_), "type");
793   }
794 };
795 
796 struct CallSiteOffsets : public CheckOffsets<mirror::CallSite> {
CallSiteOffsetsart::CallSiteOffsets797   CallSiteOffsets() : CheckOffsets<mirror::CallSite>(
798       false, "Ljava/lang/invoke/CallSite;") {
799     addOffset(OFFSETOF_MEMBER(mirror::CallSite, target_), "target");
800   }
801 };
802 
803 struct VarHandleOffsets : public CheckOffsets<mirror::VarHandle> {
VarHandleOffsetsart::VarHandleOffsets804   VarHandleOffsets() : CheckOffsets<mirror::VarHandle>(
805       false, "Ljava/lang/invoke/VarHandle;") {
806     addOffset(OFFSETOF_MEMBER(mirror::VarHandle, access_modes_bit_mask_), "accessModesBitMask");
807     addOffset(OFFSETOF_MEMBER(mirror::VarHandle, coordinate_type0_), "coordinateType0");
808     addOffset(OFFSETOF_MEMBER(mirror::VarHandle, coordinate_type1_), "coordinateType1");
809     addOffset(OFFSETOF_MEMBER(mirror::VarHandle, var_type_), "varType");
810   }
811 };
812 
813 struct FieldVarHandleOffsets : public CheckOffsets<mirror::FieldVarHandle> {
FieldVarHandleOffsetsart::FieldVarHandleOffsets814   FieldVarHandleOffsets() : CheckOffsets<mirror::FieldVarHandle>(
815       false, "Ljava/lang/invoke/FieldVarHandle;") {
816     addOffset(OFFSETOF_MEMBER(mirror::FieldVarHandle, art_field_), "artField");
817   }
818 };
819 
820 struct ArrayElementVarHandleOffsets : public CheckOffsets<mirror::ArrayElementVarHandle> {
ArrayElementVarHandleOffsetsart::ArrayElementVarHandleOffsets821   ArrayElementVarHandleOffsets() : CheckOffsets<mirror::ArrayElementVarHandle>(
822       false, "Ljava/lang/invoke/ArrayElementVarHandle;") {
823   }
824 };
825 
826 struct ByteArrayViewVarHandleOffsets : public CheckOffsets<mirror::ByteArrayViewVarHandle> {
ByteArrayViewVarHandleOffsetsart::ByteArrayViewVarHandleOffsets827   ByteArrayViewVarHandleOffsets() : CheckOffsets<mirror::ByteArrayViewVarHandle>(
828       false, "Ljava/lang/invoke/ByteArrayViewVarHandle;") {
829     addOffset(OFFSETOF_MEMBER(mirror::ByteArrayViewVarHandle, native_byte_order_),
830               "nativeByteOrder");
831   }
832 };
833 
834 struct ByteBufferViewVarHandleOffsets : public CheckOffsets<mirror::ByteBufferViewVarHandle> {
ByteBufferViewVarHandleOffsetsart::ByteBufferViewVarHandleOffsets835   ByteBufferViewVarHandleOffsets() : CheckOffsets<mirror::ByteBufferViewVarHandle>(
836       false, "Ljava/lang/invoke/ByteBufferViewVarHandle;") {
837     addOffset(OFFSETOF_MEMBER(mirror::ByteBufferViewVarHandle, native_byte_order_),
838               "nativeByteOrder");
839   }
840 };
841 
842 // C++ fields must exactly match the fields in the Java classes. If this fails,
843 // reorder the fields in the C++ class. Managed class fields are ordered by
844 // ClassLinker::LinkFields.
TEST_F(ClassLinkerTest,ValidateFieldOrderOfJavaCppUnionClasses)845 TEST_F(ClassLinkerTest, ValidateFieldOrderOfJavaCppUnionClasses) {
846   ScopedObjectAccess soa(Thread::Current());
847   EXPECT_TRUE(ObjectOffsets().Check());
848   EXPECT_TRUE(ClassOffsets().Check());
849   EXPECT_TRUE(ClassExtOffsets().Check());
850   EXPECT_TRUE(StringOffsets().Check());
851   EXPECT_TRUE(ThrowableOffsets().Check());
852   EXPECT_TRUE(StackTraceElementOffsets().Check());
853   EXPECT_TRUE(ClassLoaderOffsets().Check());
854   EXPECT_TRUE(ProxyOffsets().Check());
855   EXPECT_TRUE(DexCacheOffsets().Check());
856   EXPECT_TRUE(ReferenceOffsets().Check());
857   EXPECT_TRUE(FinalizerReferenceOffsets().Check());
858   EXPECT_TRUE(AccessibleObjectOffsets().Check());
859   EXPECT_TRUE(FieldOffsets().Check());
860   EXPECT_TRUE(ExecutableOffsets().Check());
861   EXPECT_TRUE(MethodTypeOffsets().Check());
862   EXPECT_TRUE(MethodHandleOffsets().Check());
863   EXPECT_TRUE(MethodHandleImplOffsets().Check());
864   EXPECT_TRUE(MethodHandlesLookupOffsets().Check());
865   EXPECT_TRUE(EmulatedStackFrameOffsets().Check());
866   EXPECT_TRUE(CallSiteOffsets().Check());
867   EXPECT_TRUE(VarHandleOffsets().Check());
868   EXPECT_TRUE(FieldVarHandleOffsets().Check());
869   EXPECT_TRUE(ArrayElementVarHandleOffsets().Check());
870   EXPECT_TRUE(ByteArrayViewVarHandleOffsets().Check());
871   EXPECT_TRUE(ByteBufferViewVarHandleOffsets().Check());
872 }
873 
TEST_F(ClassLinkerTest,FindClassNonexistent)874 TEST_F(ClassLinkerTest, FindClassNonexistent) {
875   ScopedObjectAccess soa(Thread::Current());
876   AssertNonExistentClass("NoSuchClass;");
877   AssertNonExistentClass("LNoSuchClass;");
878 }
879 
TEST_F(ClassLinkerTest,GetDexFiles)880 TEST_F(ClassLinkerTest, GetDexFiles) {
881   ScopedObjectAccess soa(Thread::Current());
882 
883   jobject jclass_loader = LoadDex("Nested");
884   std::vector<const DexFile*> dex_files(GetDexFiles(jclass_loader));
885   ASSERT_EQ(dex_files.size(), 1U);
886   EXPECT_TRUE(android::base::EndsWith(dex_files[0]->GetLocation(), "Nested.jar"));
887 
888   jobject jclass_loader2 = LoadDex("MultiDex");
889   std::vector<const DexFile*> dex_files2(GetDexFiles(jclass_loader2));
890   ASSERT_EQ(dex_files2.size(), 2U);
891   EXPECT_TRUE(android::base::EndsWith(dex_files2[0]->GetLocation(), "MultiDex.jar"));
892 }
893 
TEST_F(ClassLinkerTest,FindClassNested)894 TEST_F(ClassLinkerTest, FindClassNested) {
895   ScopedObjectAccess soa(Thread::Current());
896   StackHandleScope<1> hs(soa.Self());
897   Handle<mirror::ClassLoader> class_loader(
898       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Nested"))));
899 
900   ObjPtr<mirror::Class> outer = class_linker_->FindClass(soa.Self(), "LNested;", class_loader);
901   ASSERT_TRUE(outer != nullptr);
902   EXPECT_EQ(0U, outer->NumVirtualMethods());
903   EXPECT_EQ(1U, outer->NumDirectMethods());
904 
905   ObjPtr<mirror::Class> inner =
906       class_linker_->FindClass(soa.Self(), "LNested$Inner;", class_loader);
907   ASSERT_TRUE(inner != nullptr);
908   EXPECT_EQ(0U, inner->NumVirtualMethods());
909   EXPECT_EQ(1U, inner->NumDirectMethods());
910 }
911 
TEST_F(ClassLinkerTest,FindClass_Primitives)912 TEST_F(ClassLinkerTest, FindClass_Primitives) {
913   ScopedObjectAccess soa(Thread::Current());
914   const std::string expected("BCDFIJSZV");
915   for (int ch = 1; ch < 256; ++ch) {
916     std::string descriptor;
917     descriptor.push_back(ch);
918     if (expected.find(ch) == std::string::npos) {
919       AssertNonExistentClass(descriptor);
920     } else {
921       AssertPrimitiveClass(descriptor);
922     }
923   }
924 }
925 
TEST_F(ClassLinkerTest,FindClass)926 TEST_F(ClassLinkerTest, FindClass) {
927   ScopedObjectAccess soa(Thread::Current());
928   StackHandleScope<2> hs(soa.Self());
929   Handle<mirror::Class> JavaLangObject = hs.NewHandle(
930       class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;"));
931   AssertObjectClass(JavaLangObject.Get());
932 
933   Handle<mirror::ClassLoader> class_loader(
934       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MyClass"))));
935   AssertNonExistentClass("LMyClass;");
936   ObjPtr<mirror::Class> MyClass = class_linker_->FindClass(soa.Self(), "LMyClass;", class_loader);
937   ASSERT_TRUE(MyClass != nullptr);
938   ASSERT_TRUE(MyClass->GetClass() != nullptr);
939   ASSERT_OBJ_PTR_EQ(MyClass->GetClass(), MyClass->GetClass()->GetClass());
940   EXPECT_OBJ_PTR_EQ(JavaLangObject.Get(), MyClass->GetClass()->GetSuperClass());
941   std::string temp;
942   ASSERT_STREQ(MyClass->GetDescriptor(&temp), "LMyClass;");
943   EXPECT_OBJ_PTR_EQ(MyClass->GetSuperClass(), JavaLangObject.Get());
944   EXPECT_TRUE(MyClass->HasSuperClass());
945   EXPECT_OBJ_PTR_EQ(class_loader.Get(), MyClass->GetClassLoader());
946   EXPECT_EQ(ClassStatus::kResolved, MyClass->GetStatus());
947   EXPECT_FALSE(MyClass->IsErroneous());
948   EXPECT_TRUE(MyClass->IsLoaded());
949   EXPECT_TRUE(MyClass->IsResolved());
950   EXPECT_FALSE(MyClass->IsErroneousResolved());
951   EXPECT_FALSE(MyClass->IsVerified());
952   EXPECT_FALSE(MyClass->IsInitialized());
953   EXPECT_FALSE(MyClass->IsArrayInstance());
954   EXPECT_FALSE(MyClass->IsArrayClass());
955   EXPECT_TRUE(MyClass->GetComponentType() == nullptr);
956   EXPECT_FALSE(MyClass->IsInterface());
957   EXPECT_FALSE(MyClass->IsPublic());
958   EXPECT_FALSE(MyClass->IsFinal());
959   EXPECT_FALSE(MyClass->IsPrimitive());
960   EXPECT_FALSE(MyClass->IsSynthetic());
961   EXPECT_EQ(1U, MyClass->NumDirectMethods());
962   EXPECT_EQ(0U, MyClass->NumVirtualMethods());
963   EXPECT_EQ(0U, MyClass->NumInstanceFields());
964   EXPECT_EQ(0U, MyClass->NumStaticFields());
965   EXPECT_EQ(0U, MyClass->NumDirectInterfaces());
966 
967   EXPECT_OBJ_PTR_EQ(JavaLangObject->GetClass()->GetClass(), MyClass->GetClass()->GetClass());
968 
969   // created by class_linker
970   AssertArrayClass("[C", "C", nullptr);
971   AssertArrayClass("[Ljava/lang/Object;", "Ljava/lang/Object;", nullptr);
972   // synthesized on the fly
973   AssertArrayClass("[[C", "[C", nullptr);
974   AssertArrayClass("[[[LMyClass;", "[[LMyClass;", class_loader.Get());
975   // or not available at all
976   AssertNonExistentClass("[[[[LNonExistentClass;");
977 }
978 
TEST_F(ClassLinkerTest,LookupResolvedType)979 TEST_F(ClassLinkerTest, LookupResolvedType) {
980   ScopedObjectAccess soa(Thread::Current());
981   StackHandleScope<1> hs(soa.Self());
982   Handle<mirror::ClassLoader> class_loader(
983       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MyClass"))));
984   AssertNonExistentClass("LMyClass;");
985   ObjPtr<mirror::Class> klass = class_linker_->FindClass(soa.Self(), "LMyClass;", class_loader);
986   dex::TypeIndex type_idx = klass->GetClassDef()->class_idx_;
987   ObjPtr<mirror::DexCache> dex_cache = klass->GetDexCache();
988   EXPECT_OBJ_PTR_EQ(
989       class_linker_->LookupResolvedType(type_idx, dex_cache, class_loader.Get()),
990       klass);
991   // Zero out the resolved type and make sure LookupResolvedType still finds it.
992   dex_cache->ClearResolvedType(type_idx);
993   EXPECT_TRUE(dex_cache->GetResolvedType(type_idx) == nullptr);
994   EXPECT_OBJ_PTR_EQ(
995       class_linker_->LookupResolvedType(type_idx, dex_cache, class_loader.Get()),
996       klass);
997 }
998 
TEST_F(ClassLinkerTest,LookupResolvedTypeArray)999 TEST_F(ClassLinkerTest, LookupResolvedTypeArray) {
1000   ScopedObjectAccess soa(Thread::Current());
1001   StackHandleScope<2> hs(soa.Self());
1002   Handle<mirror::ClassLoader> class_loader(
1003       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("AllFields"))));
1004   // Get the AllFields class for the dex cache and dex file.
1005   ObjPtr<mirror::Class> all_fields_klass
1006       = class_linker_->FindClass(soa.Self(), "LAllFields;", class_loader);
1007   ASSERT_TRUE(all_fields_klass != nullptr);
1008   Handle<mirror::DexCache> dex_cache = hs.NewHandle(all_fields_klass->GetDexCache());
1009   const DexFile& dex_file = *dex_cache->GetDexFile();
1010   // Get the index of the array class we want to test.
1011   const dex::TypeId* array_id = dex_file.FindTypeId("[Ljava/lang/Object;");
1012   ASSERT_TRUE(array_id != nullptr);
1013   dex::TypeIndex array_idx = dex_file.GetIndexForTypeId(*array_id);
1014   // Check that the array class wasn't resolved yet.
1015   EXPECT_TRUE(
1016       class_linker_->LookupResolvedType(array_idx, dex_cache.Get(), class_loader.Get()) == nullptr);
1017   // Resolve the array class we want to test.
1018   ObjPtr<mirror::Class> array_klass
1019       = class_linker_->FindClass(soa.Self(), "[Ljava/lang/Object;", class_loader);
1020   ASSERT_TRUE(array_klass != nullptr);
1021   // Test that LookupResolvedType() finds the array class.
1022   EXPECT_OBJ_PTR_EQ(
1023       class_linker_->LookupResolvedType(array_idx, dex_cache.Get(), class_loader.Get()),
1024       array_klass);
1025   // Zero out the resolved type and make sure LookupResolvedType() still finds it.
1026   dex_cache->ClearResolvedType(array_idx);
1027   EXPECT_TRUE(dex_cache->GetResolvedType(array_idx) == nullptr);
1028   EXPECT_OBJ_PTR_EQ(
1029       class_linker_->LookupResolvedType(array_idx, dex_cache.Get(), class_loader.Get()),
1030       array_klass);
1031 }
1032 
TEST_F(ClassLinkerTest,LookupResolvedTypeErroneousInit)1033 TEST_F(ClassLinkerTest, LookupResolvedTypeErroneousInit) {
1034   ScopedObjectAccess soa(Thread::Current());
1035   StackHandleScope<3> hs(soa.Self());
1036   Handle<mirror::ClassLoader> class_loader(
1037       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("ErroneousInit"))));
1038   AssertNonExistentClass("LErroneousInit;");
1039   Handle<mirror::Class> klass =
1040       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LErroneousInit;", class_loader));
1041   ASSERT_TRUE(klass != nullptr);
1042   dex::TypeIndex type_idx = klass->GetClassDef()->class_idx_;
1043   Handle<mirror::DexCache> dex_cache = hs.NewHandle(klass->GetDexCache());
1044   EXPECT_OBJ_PTR_EQ(
1045       class_linker_->LookupResolvedType(type_idx, dex_cache.Get(), class_loader.Get()),
1046       klass.Get());
1047   // Zero out the resolved type and make sure LookupResolvedType still finds it.
1048   dex_cache->ClearResolvedType(type_idx);
1049   EXPECT_TRUE(dex_cache->GetResolvedType(type_idx) == nullptr);
1050   EXPECT_OBJ_PTR_EQ(
1051       class_linker_->LookupResolvedType(type_idx, dex_cache.Get(), class_loader.Get()),
1052       klass.Get());
1053   // Force initialization to turn the class erroneous.
1054   bool initialized = class_linker_->EnsureInitialized(soa.Self(),
1055                                                       klass,
1056                                                       /* can_init_fields= */ true,
1057                                                       /* can_init_parents= */ true);
1058   EXPECT_FALSE(initialized);
1059   EXPECT_TRUE(soa.Self()->IsExceptionPending());
1060   soa.Self()->ClearException();
1061   // Check that the LookupResolvedType() can still find the resolved type.
1062   EXPECT_OBJ_PTR_EQ(
1063       class_linker_->LookupResolvedType(type_idx, dex_cache.Get(), class_loader.Get()),
1064       klass.Get());
1065   // Zero out the resolved type and make sure LookupResolvedType() still finds it.
1066   dex_cache->ClearResolvedType(type_idx);
1067   EXPECT_TRUE(dex_cache->GetResolvedType(type_idx) == nullptr);
1068   EXPECT_OBJ_PTR_EQ(
1069       class_linker_->LookupResolvedType(type_idx, dex_cache.Get(), class_loader.Get()),
1070       klass.Get());
1071 }
1072 
TEST_F(ClassLinkerTest,LibCore)1073 TEST_F(ClassLinkerTest, LibCore) {
1074   ScopedObjectAccess soa(Thread::Current());
1075   ASSERT_TRUE(java_lang_dex_file_ != nullptr);
1076   AssertDexFile(*java_lang_dex_file_, nullptr);
1077 }
1078 
1079 // The first reference array element must be a multiple of 4 bytes from the
1080 // start of the object
TEST_F(ClassLinkerTest,ValidateObjectArrayElementsOffset)1081 TEST_F(ClassLinkerTest, ValidateObjectArrayElementsOffset) {
1082   ScopedObjectAccess soa(Thread::Current());
1083   ObjPtr<mirror::Class> array_class =
1084       class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/String;");
1085   ObjPtr<mirror::ObjectArray<mirror::String>> array =
1086       mirror::ObjectArray<mirror::String>::Alloc(soa.Self(), array_class, 0);
1087   uintptr_t data_offset =
1088       reinterpret_cast<uintptr_t>(array->GetRawData(sizeof(mirror::HeapReference<mirror::String>),
1089                                                     0));
1090   if (sizeof(mirror::HeapReference<mirror::String>) == sizeof(int32_t)) {
1091     EXPECT_TRUE(IsAligned<4>(data_offset));  // Check 4 byte alignment.
1092   } else {
1093     EXPECT_TRUE(IsAligned<8>(data_offset));  // Check 8 byte alignment.
1094   }
1095 }
1096 
TEST_F(ClassLinkerTest,ValidatePrimitiveArrayElementsOffset)1097 TEST_F(ClassLinkerTest, ValidatePrimitiveArrayElementsOffset) {
1098   ScopedObjectAccess soa(Thread::Current());
1099   StackHandleScope<5> hs(soa.Self());
1100   Handle<mirror::LongArray> long_array(hs.NewHandle(mirror::LongArray::Alloc(soa.Self(), 0)));
1101   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[J"), long_array->GetClass());
1102   uintptr_t data_offset = reinterpret_cast<uintptr_t>(long_array->GetData());
1103   EXPECT_TRUE(IsAligned<8>(data_offset));  // Longs require 8 byte alignment
1104 
1105   Handle<mirror::DoubleArray> double_array(hs.NewHandle(mirror::DoubleArray::Alloc(soa.Self(), 0)));
1106   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[D"), double_array->GetClass());
1107   data_offset = reinterpret_cast<uintptr_t>(double_array->GetData());
1108   EXPECT_TRUE(IsAligned<8>(data_offset));  // Doubles require 8 byte alignment
1109 
1110   Handle<mirror::IntArray> int_array(hs.NewHandle(mirror::IntArray::Alloc(soa.Self(), 0)));
1111   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[I"), int_array->GetClass());
1112   data_offset = reinterpret_cast<uintptr_t>(int_array->GetData());
1113   EXPECT_TRUE(IsAligned<4>(data_offset));  // Ints require 4 byte alignment
1114 
1115   Handle<mirror::CharArray> char_array(hs.NewHandle(mirror::CharArray::Alloc(soa.Self(), 0)));
1116   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[C"), char_array->GetClass());
1117   data_offset = reinterpret_cast<uintptr_t>(char_array->GetData());
1118   EXPECT_TRUE(IsAligned<2>(data_offset));  // Chars require 2 byte alignment
1119 
1120   Handle<mirror::ShortArray> short_array(hs.NewHandle(mirror::ShortArray::Alloc(soa.Self(), 0)));
1121   EXPECT_OBJ_PTR_EQ(class_linker_->FindSystemClass(soa.Self(), "[S"), short_array->GetClass());
1122   data_offset = reinterpret_cast<uintptr_t>(short_array->GetData());
1123   EXPECT_TRUE(IsAligned<2>(data_offset));  // Shorts require 2 byte alignment
1124 
1125   // Take it as given that bytes and booleans have byte alignment
1126 }
1127 
TEST_F(ClassLinkerTest,ValidateBoxedTypes)1128 TEST_F(ClassLinkerTest, ValidateBoxedTypes) {
1129   // Validate that the "value" field is always the 0th field in each of java.lang's box classes.
1130   // This lets UnboxPrimitive avoid searching for the field by name at runtime.
1131   ScopedObjectAccess soa(Thread::Current());
1132   ScopedNullHandle<mirror::ClassLoader> class_loader;
1133   ObjPtr<mirror::Class> c;
1134   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Boolean;", class_loader);
1135   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1136   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Byte;", class_loader);
1137   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1138   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Character;", class_loader);
1139   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1140   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Double;", class_loader);
1141   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1142   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Float;", class_loader);
1143   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1144   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Integer;", class_loader);
1145   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1146   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Long;", class_loader);
1147   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1148   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Short;", class_loader);
1149   EXPECT_STREQ("value", c->GetIFieldsPtr()->At(0).GetName());
1150 }
1151 
TEST_F(ClassLinkerTest,TwoClassLoadersOneClass)1152 TEST_F(ClassLinkerTest, TwoClassLoadersOneClass) {
1153   ScopedObjectAccess soa(Thread::Current());
1154   StackHandleScope<3> hs(soa.Self());
1155   Handle<mirror::ClassLoader> class_loader_1(
1156       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MyClass"))));
1157   Handle<mirror::ClassLoader> class_loader_2(
1158       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MyClass"))));
1159   Handle<mirror::Class> MyClass_1 = hs.NewHandle(
1160       class_linker_->FindClass(soa.Self(), "LMyClass;", class_loader_1));
1161   ObjPtr<mirror::Class> MyClass_2 =
1162       class_linker_->FindClass(soa.Self(), "LMyClass;", class_loader_2);
1163   EXPECT_TRUE(MyClass_1 != nullptr);
1164   EXPECT_TRUE(MyClass_2 != nullptr);
1165   EXPECT_OBJ_PTR_NE(MyClass_1.Get(), MyClass_2);
1166 }
1167 
TEST_F(ClassLinkerTest,StaticFields)1168 TEST_F(ClassLinkerTest, StaticFields) {
1169   ScopedObjectAccess soa(Thread::Current());
1170   StackHandleScope<2> hs(soa.Self());
1171   Handle<mirror::ClassLoader> class_loader(
1172       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Statics"))));
1173   Handle<mirror::Class> statics(
1174       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LStatics;", class_loader)));
1175   class_linker_->EnsureInitialized(soa.Self(), statics, true, true);
1176 
1177   // Static final primitives that are initialized by a compile-time constant
1178   // expression resolve to a copy of a constant value from the constant pool.
1179   // So <clinit> should be null.
1180   ArtMethod* clinit = statics->FindClassMethod("<clinit>", "()V", kRuntimePointerSize);
1181   EXPECT_TRUE(clinit == nullptr);
1182 
1183   EXPECT_EQ(9U, statics->NumStaticFields());
1184 
1185   ArtField* s0 = mirror::Class::FindStaticField(soa.Self(), statics.Get(), "s0", "Z");
1186   EXPECT_EQ(s0->GetTypeAsPrimitiveType(), Primitive::kPrimBoolean);
1187   EXPECT_EQ(true, s0->GetBoolean(statics.Get()));
1188   s0->SetBoolean<false>(statics.Get(), false);
1189 
1190   ArtField* s1 = mirror::Class::FindStaticField(soa.Self(), statics.Get(), "s1", "B");
1191   EXPECT_EQ(s1->GetTypeAsPrimitiveType(), Primitive::kPrimByte);
1192   EXPECT_EQ(5, s1->GetByte(statics.Get()));
1193   s1->SetByte<false>(statics.Get(), 6);
1194 
1195   ArtField* s2 = mirror::Class::FindStaticField(soa.Self(), statics.Get(), "s2", "C");
1196   EXPECT_EQ(s2->GetTypeAsPrimitiveType(), Primitive::kPrimChar);
1197   EXPECT_EQ('a', s2->GetChar(statics.Get()));
1198   s2->SetChar<false>(statics.Get(), 'b');
1199 
1200   ArtField* s3 = mirror::Class::FindStaticField(soa.Self(), statics.Get(), "s3", "S");
1201   EXPECT_EQ(s3->GetTypeAsPrimitiveType(), Primitive::kPrimShort);
1202   EXPECT_EQ(-536, s3->GetShort(statics.Get()));
1203   s3->SetShort<false>(statics.Get(), -535);
1204 
1205   ArtField* s4 = mirror::Class::FindStaticField(soa.Self(), statics.Get(), "s4", "I");
1206   EXPECT_EQ(s4->GetTypeAsPrimitiveType(), Primitive::kPrimInt);
1207   EXPECT_EQ(2000000000, s4->GetInt(statics.Get()));
1208   s4->SetInt<false>(statics.Get(), 2000000001);
1209 
1210   ArtField* s5 = mirror::Class::FindStaticField(soa.Self(), statics.Get(), "s5", "J");
1211   EXPECT_EQ(s5->GetTypeAsPrimitiveType(), Primitive::kPrimLong);
1212   EXPECT_EQ(0x1234567890abcdefLL, s5->GetLong(statics.Get()));
1213   s5->SetLong<false>(statics.Get(), INT64_C(0x34567890abcdef12));
1214 
1215   ArtField* s6 = mirror::Class::FindStaticField(soa.Self(), statics.Get(), "s6", "F");
1216   EXPECT_EQ(s6->GetTypeAsPrimitiveType(), Primitive::kPrimFloat);
1217   EXPECT_DOUBLE_EQ(0.5, s6->GetFloat(statics.Get()));
1218   s6->SetFloat<false>(statics.Get(), 0.75);
1219 
1220   ArtField* s7 = mirror::Class::FindStaticField(soa.Self(), statics.Get(), "s7", "D");
1221   EXPECT_EQ(s7->GetTypeAsPrimitiveType(), Primitive::kPrimDouble);
1222   EXPECT_DOUBLE_EQ(16777217.0, s7->GetDouble(statics.Get()));
1223   s7->SetDouble<false>(statics.Get(), 16777219);
1224 
1225   ArtField* s8 = mirror::Class::FindStaticField(
1226       soa.Self(), statics.Get(), "s8", "Ljava/lang/String;");
1227   EXPECT_EQ(s8->GetTypeAsPrimitiveType(), Primitive::kPrimNot);
1228   EXPECT_TRUE(s8->GetObject(statics.Get())->AsString()->Equals("android"));
1229   ObjPtr<mirror::String> str_value = mirror::String::AllocFromModifiedUtf8(soa.Self(), "robot");
1230   s8->SetObject<false>(s8->GetDeclaringClass(), str_value);
1231 
1232   // TODO: Remove EXPECT_FALSE when GCC can handle EXPECT_EQ
1233   // http://code.google.com/p/googletest/issues/detail?id=322
1234   EXPECT_FALSE(s0->GetBoolean(statics.Get()));
1235   EXPECT_EQ(6, s1->GetByte(statics.Get()));
1236   EXPECT_EQ('b', s2->GetChar(statics.Get()));
1237   EXPECT_EQ(-535, s3->GetShort(statics.Get()));
1238   EXPECT_EQ(2000000001, s4->GetInt(statics.Get()));
1239   EXPECT_EQ(INT64_C(0x34567890abcdef12), s5->GetLong(statics.Get()));
1240   EXPECT_FLOAT_EQ(0.75, s6->GetFloat(statics.Get()));
1241   EXPECT_DOUBLE_EQ(16777219.0, s7->GetDouble(statics.Get()));
1242   EXPECT_TRUE(s8->GetObject(statics.Get())->AsString()->Equals("robot"));
1243 }
1244 
TEST_F(ClassLinkerTest,Interfaces)1245 TEST_F(ClassLinkerTest, Interfaces) {
1246   ScopedObjectAccess soa(Thread::Current());
1247   StackHandleScope<6> hs(soa.Self());
1248   Handle<mirror::ClassLoader> class_loader(
1249       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Interfaces"))));
1250   Handle<mirror::Class> I(
1251       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$I;", class_loader)));
1252   Handle<mirror::Class> J(
1253       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$J;", class_loader)));
1254   Handle<mirror::Class> K(
1255       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$K;", class_loader)));
1256   Handle<mirror::Class> A(
1257       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$A;", class_loader)));
1258   Handle<mirror::Class> B(
1259       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LInterfaces$B;", class_loader)));
1260   EXPECT_TRUE(I->IsAssignableFrom(A.Get()));
1261   EXPECT_TRUE(J->IsAssignableFrom(A.Get()));
1262   EXPECT_TRUE(J->IsAssignableFrom(K.Get()));
1263   EXPECT_TRUE(K->IsAssignableFrom(B.Get()));
1264   EXPECT_TRUE(J->IsAssignableFrom(B.Get()));
1265 
1266   const std::string_view void_sig("()V");
1267   ArtMethod* Ii = I->FindClassMethod("i", void_sig, kRuntimePointerSize);
1268   ArtMethod* Jj1 = J->FindClassMethod("j1", void_sig, kRuntimePointerSize);
1269   ArtMethod* Jj2 = J->FindClassMethod("j2", void_sig, kRuntimePointerSize);
1270   ArtMethod* Kj1 = K->FindInterfaceMethod("j1", void_sig, kRuntimePointerSize);
1271   ArtMethod* Kj2 = K->FindInterfaceMethod("j2", void_sig, kRuntimePointerSize);
1272   ArtMethod* Kk = K->FindInterfaceMethod("k", void_sig, kRuntimePointerSize);
1273   ArtMethod* Ai = A->FindClassMethod("i", void_sig, kRuntimePointerSize);
1274   ArtMethod* Aj1 = A->FindClassMethod("j1", void_sig, kRuntimePointerSize);
1275   ArtMethod* Aj2 = A->FindClassMethod("j2", void_sig, kRuntimePointerSize);
1276   ASSERT_TRUE(Ii != nullptr);
1277   ASSERT_FALSE(Ii->IsDirect());
1278   ASSERT_TRUE(Jj1 != nullptr);
1279   ASSERT_FALSE(Jj1->IsDirect());
1280   ASSERT_TRUE(Jj2 != nullptr);
1281   ASSERT_FALSE(Jj2->IsDirect());
1282   ASSERT_TRUE(Kj1 != nullptr);
1283   ASSERT_TRUE(Kj2 != nullptr);
1284   ASSERT_TRUE(Kk != nullptr);
1285   ASSERT_TRUE(Ai != nullptr);
1286   ASSERT_FALSE(Ai->IsDirect());
1287   ASSERT_TRUE(Aj1 != nullptr);
1288   ASSERT_FALSE(Aj1->IsDirect());
1289   ASSERT_TRUE(Aj2 != nullptr);
1290   ASSERT_FALSE(Aj2->IsDirect());
1291   EXPECT_NE(Ii, Ai);
1292   EXPECT_NE(Jj1, Aj1);
1293   EXPECT_NE(Jj2, Aj2);
1294   EXPECT_EQ(Kj1, Jj1);
1295   EXPECT_EQ(Kj2, Jj2);
1296   EXPECT_EQ(Ai, A->FindVirtualMethodForInterface(Ii, kRuntimePointerSize));
1297   EXPECT_EQ(Aj1, A->FindVirtualMethodForInterface(Jj1, kRuntimePointerSize));
1298   EXPECT_EQ(Aj2, A->FindVirtualMethodForInterface(Jj2, kRuntimePointerSize));
1299   EXPECT_EQ(Ai, A->FindVirtualMethodForVirtualOrInterface(Ii, kRuntimePointerSize));
1300   EXPECT_EQ(Aj1, A->FindVirtualMethodForVirtualOrInterface(Jj1, kRuntimePointerSize));
1301   EXPECT_EQ(Aj2, A->FindVirtualMethodForVirtualOrInterface(Jj2, kRuntimePointerSize));
1302 
1303   ArtField* Afoo =
1304       mirror::Class::FindStaticField(soa.Self(), A.Get(), "foo", "Ljava/lang/String;");
1305   ArtField* Bfoo =
1306       mirror::Class::FindStaticField(soa.Self(), B.Get(), "foo", "Ljava/lang/String;");
1307   ArtField* Jfoo =
1308       mirror::Class::FindStaticField(soa.Self(), J.Get(), "foo", "Ljava/lang/String;");
1309   ArtField* Kfoo =
1310       mirror::Class::FindStaticField(soa.Self(), K.Get(), "foo", "Ljava/lang/String;");
1311   ASSERT_TRUE(Afoo != nullptr);
1312   EXPECT_EQ(Afoo, Bfoo);
1313   EXPECT_EQ(Afoo, Jfoo);
1314   EXPECT_EQ(Afoo, Kfoo);
1315 }
1316 
TEST_F(ClassLinkerTest,ResolveVerifyAndClinit)1317 TEST_F(ClassLinkerTest, ResolveVerifyAndClinit) {
1318   // pretend we are trying to get the static storage for the StaticsFromCode class.
1319 
1320   // case 1, get the uninitialized storage from StaticsFromCode.<clinit>
1321   // case 2, get the initialized storage from StaticsFromCode.getS0
1322 
1323   ScopedObjectAccess soa(Thread::Current());
1324   jobject jclass_loader = LoadDex("StaticsFromCode");
1325   const DexFile* dex_file = GetFirstDexFile(jclass_loader);
1326   StackHandleScope<1> hs(soa.Self());
1327   Handle<mirror::ClassLoader> class_loader(
1328       hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
1329   ObjPtr<mirror::Class> klass =
1330       class_linker_->FindClass(soa.Self(), "LStaticsFromCode;", class_loader);
1331   ArtMethod* clinit = klass->FindClassInitializer(kRuntimePointerSize);
1332   ArtMethod* getS0 =
1333       klass->FindClassMethod("getS0", "()Ljava/lang/Object;", kRuntimePointerSize);
1334   ASSERT_TRUE(getS0 != nullptr);
1335   ASSERT_TRUE(getS0->IsStatic());
1336   const dex::TypeId* type_id = dex_file->FindTypeId("LStaticsFromCode;");
1337   ASSERT_TRUE(type_id != nullptr);
1338   dex::TypeIndex type_idx = dex_file->GetIndexForTypeId(*type_id);
1339   ObjPtr<mirror::Class> uninit = ResolveVerifyAndClinit(type_idx,
1340                                                         clinit,
1341                                                         soa.Self(),
1342                                                         /* can_run_clinit= */ true,
1343                                                         /* verify_access= */ false);
1344   EXPECT_TRUE(uninit != nullptr);
1345   EXPECT_FALSE(uninit->IsInitialized());
1346   ObjPtr<mirror::Class> init = ResolveVerifyAndClinit(type_idx,
1347                                                       getS0,
1348                                                       soa.Self(),
1349                                                       /* can_run_clinit= */ true,
1350                                                       /* verify_access= */ false);
1351   EXPECT_TRUE(init != nullptr);
1352   EXPECT_TRUE(init->IsInitialized());
1353 }
1354 
TEST_F(ClassLinkerTest,ErroneousClass)1355 TEST_F(ClassLinkerTest, ErroneousClass) {
1356   ScopedObjectAccess soa(Thread::Current());
1357   jobject jclass_loader = LoadMultiDex("ErroneousA", "ErroneousB");
1358   StackHandleScope<1> hs(soa.Self());
1359   Handle<mirror::ClassLoader> class_loader(
1360       hs.NewHandle(soa.Decode<mirror::ClassLoader>(jclass_loader)));
1361   hs.Self()->AssertNoPendingException();
1362   const char* descriptor = "LErroneous;";
1363   ObjPtr<mirror::Class> klass = class_linker_->FindClass(soa.Self(), descriptor, class_loader);
1364   // Erronenous since we are extending final class.
1365   hs.Self()->AssertPendingException();
1366   EXPECT_TRUE(klass == nullptr);
1367   klass = class_linker_->LookupClass(soa.Self(), descriptor, class_loader.Get());
1368   EXPECT_FALSE(klass == nullptr);
1369   EXPECT_TRUE(klass->IsErroneous());
1370   EXPECT_TRUE(klass->GetIfTable() != nullptr);
1371 }
1372 
TEST_F(ClassLinkerTest,FinalizableBit)1373 TEST_F(ClassLinkerTest, FinalizableBit) {
1374   ScopedObjectAccess soa(Thread::Current());
1375   ObjPtr<mirror::Class> c;
1376 
1377   // Object has a finalize method, but we know it's empty.
1378   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;");
1379   EXPECT_FALSE(c->IsFinalizable());
1380 
1381   // Enum has a finalize method to prevent its subclasses from implementing one.
1382   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Enum;");
1383   EXPECT_FALSE(c->IsFinalizable());
1384 
1385   // RoundingMode is an enum.
1386   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/math/RoundingMode;");
1387   EXPECT_FALSE(c->IsFinalizable());
1388 
1389   // RandomAccessFile extends Object and overrides finalize.
1390   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/io/RandomAccessFile;");
1391   EXPECT_TRUE(c->IsFinalizable());
1392 
1393   // FileInputStream is finalizable and extends InputStream which isn't.
1394   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/io/InputStream;");
1395   EXPECT_FALSE(c->IsFinalizable());
1396   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/io/FileInputStream;");
1397   EXPECT_TRUE(c->IsFinalizable());
1398 
1399   // ScheduledThreadPoolExecutor doesn't have a finalize method but
1400   // extends ThreadPoolExecutor which does.
1401   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/util/concurrent/ThreadPoolExecutor;");
1402   EXPECT_TRUE(c->IsFinalizable());
1403   c = class_linker_->FindSystemClass(soa.Self(), "Ljava/util/concurrent/ScheduledThreadPoolExecutor;");
1404   EXPECT_TRUE(c->IsFinalizable());
1405 }
1406 
TEST_F(ClassLinkerTest,ClassRootDescriptors)1407 TEST_F(ClassLinkerTest, ClassRootDescriptors) {
1408   ScopedObjectAccess soa(Thread::Current());
1409   std::string temp;
1410   for (size_t i = 0; i < static_cast<size_t>(ClassRoot::kMax); i++) {
1411     ObjPtr<mirror::Class> klass = GetClassRoot(ClassRoot(i), class_linker_);
1412     EXPECT_GT(strlen(klass->GetDescriptor(&temp)), 0U);
1413     EXPECT_STREQ(klass->GetDescriptor(&temp), GetClassRootDescriptor(ClassRoot(i))) << " i = " << i;
1414   }
1415 }
1416 
TEST_F(ClassLinkerTest,ValidatePredefinedClassSizes)1417 TEST_F(ClassLinkerTest, ValidatePredefinedClassSizes) {
1418   ScopedObjectAccess soa(Thread::Current());
1419   ScopedNullHandle<mirror::ClassLoader> class_loader;
1420   ObjPtr<mirror::Class> c;
1421 
1422   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Class;", class_loader);
1423   ASSERT_TRUE(c != nullptr);
1424   EXPECT_EQ(c->GetClassSize(), mirror::Class::ClassClassSize(kRuntimePointerSize));
1425 
1426   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/Object;", class_loader);
1427   ASSERT_TRUE(c != nullptr);
1428   EXPECT_EQ(c->GetClassSize(), mirror::Object::ClassSize(kRuntimePointerSize));
1429 
1430   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/String;", class_loader);
1431   ASSERT_TRUE(c != nullptr);
1432   EXPECT_EQ(c->GetClassSize(), mirror::String::ClassSize(kRuntimePointerSize));
1433 
1434   c = class_linker_->FindClass(soa.Self(), "Ljava/lang/DexCache;", class_loader);
1435   ASSERT_TRUE(c != nullptr);
1436   EXPECT_EQ(c->GetClassSize(), mirror::DexCache::ClassSize(kRuntimePointerSize));
1437 }
1438 
CheckMethod(ArtMethod * method,bool verified)1439 static void CheckMethod(ArtMethod* method, bool verified)
1440     REQUIRES_SHARED(Locks::mutator_lock_) {
1441   if (!method->IsNative() && !method->IsAbstract()) {
1442     EXPECT_EQ((method->GetAccessFlags() & kAccSkipAccessChecks) != 0U, verified)
1443         << method->PrettyMethod(true);
1444   }
1445 }
1446 
CheckVerificationAttempted(ObjPtr<mirror::Class> c,bool preverified)1447 static void CheckVerificationAttempted(ObjPtr<mirror::Class> c, bool preverified)
1448     REQUIRES_SHARED(Locks::mutator_lock_) {
1449   EXPECT_EQ((c->GetAccessFlags() & kAccVerificationAttempted) != 0U, preverified)
1450       << "Class " << mirror::Class::PrettyClass(c) << " not as expected";
1451   for (auto& m : c->GetMethods(kRuntimePointerSize)) {
1452     CheckMethod(&m, preverified);
1453   }
1454 }
1455 
TEST_F(ClassLinkerTest,Preverified_InitializedBoot)1456 TEST_F(ClassLinkerTest, Preverified_InitializedBoot) {
1457   ScopedObjectAccess soa(Thread::Current());
1458 
1459   ObjPtr<mirror::Class> JavaLangObject =
1460       class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;");
1461   ASSERT_TRUE(JavaLangObject != nullptr);
1462   EXPECT_TRUE(JavaLangObject->IsInitialized()) << "Not testing already initialized class from the "
1463                                                   "core";
1464   CheckVerificationAttempted(JavaLangObject, true);
1465 }
1466 
TEST_F(ClassLinkerTest,Preverified_UninitializedBoot)1467 TEST_F(ClassLinkerTest, Preverified_UninitializedBoot) {
1468   ScopedObjectAccess soa(Thread::Current());
1469 
1470   StackHandleScope<1> hs(soa.Self());
1471 
1472   Handle<mirror::Class> security_manager(hs.NewHandle(class_linker_->FindSystemClass(
1473       soa.Self(), "Ljava/lang/SecurityManager;")));
1474   EXPECT_FALSE(security_manager->IsInitialized()) << "Not testing uninitialized class from the "
1475                                                      "core";
1476 
1477   CheckVerificationAttempted(security_manager.Get(), false);
1478 
1479   class_linker_->EnsureInitialized(soa.Self(), security_manager, true, true);
1480   CheckVerificationAttempted(security_manager.Get(), true);
1481 }
1482 
TEST_F(ClassLinkerTest,Preverified_App)1483 TEST_F(ClassLinkerTest, Preverified_App) {
1484   ScopedObjectAccess soa(Thread::Current());
1485 
1486   StackHandleScope<2> hs(soa.Self());
1487   Handle<mirror::ClassLoader> class_loader(
1488       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Statics"))));
1489   Handle<mirror::Class> statics(
1490       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LStatics;", class_loader)));
1491 
1492   CheckVerificationAttempted(statics.Get(), false);
1493 
1494   class_linker_->EnsureInitialized(soa.Self(), statics, true, true);
1495   CheckVerificationAttempted(statics.Get(), true);
1496 }
1497 
TEST_F(ClassLinkerTest,IsBootStrapClassLoaded)1498 TEST_F(ClassLinkerTest, IsBootStrapClassLoaded) {
1499   ScopedObjectAccess soa(Thread::Current());
1500 
1501   StackHandleScope<3> hs(soa.Self());
1502   Handle<mirror::ClassLoader> class_loader(
1503       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("Statics"))));
1504 
1505   // java.lang.Object is a bootstrap class.
1506   Handle<mirror::Class> jlo_class(
1507       hs.NewHandle(class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/Object;")));
1508   ASSERT_TRUE(jlo_class != nullptr);
1509   EXPECT_TRUE(jlo_class->IsBootStrapClassLoaded());
1510 
1511   // Statics is not a bootstrap class.
1512   Handle<mirror::Class> statics(
1513       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LStatics;", class_loader)));
1514   ASSERT_TRUE(statics != nullptr);
1515   EXPECT_FALSE(statics->IsBootStrapClassLoaded());
1516 }
1517 
1518 // Regression test for b/26799552.
TEST_F(ClassLinkerTest,RegisterDexFileName)1519 TEST_F(ClassLinkerTest, RegisterDexFileName) {
1520   ScopedObjectAccess soa(Thread::Current());
1521   StackHandleScope<2> hs(soa.Self());
1522   ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1523   MutableHandle<mirror::DexCache> dex_cache(hs.NewHandle<mirror::DexCache>(nullptr));
1524   {
1525     ReaderMutexLock mu(soa.Self(), *Locks::dex_lock_);
1526     for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1527       dex_cache.Assign(soa.Self()->DecodeJObject(data.weak_root)->AsDexCache());
1528       if (dex_cache != nullptr) {
1529         break;
1530       }
1531     }
1532     ASSERT_TRUE(dex_cache != nullptr);
1533   }
1534   const uint16_t data[] = { 0x20AC, 0x20A1 };
1535   Handle<mirror::String> location(hs.NewHandle(mirror::String::AllocFromUtf16(soa.Self(),
1536                                                                               arraysize(data),
1537                                                                               data)));
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   // Make a copy of the dex cache with changed name.
1547   LinearAlloc* alloc = Runtime::Current()->GetLinearAlloc();
1548   dex_cache.Assign(class_linker->AllocAndInitializeDexCache(Thread::Current(), *dex_file, alloc));
1549   DCHECK_EQ(dex_cache->GetLocation()->CompareTo(location.Get()), 0);
1550   {
1551     WriterMutexLock mu(soa.Self(), *Locks::dex_lock_);
1552     // Check that inserting with a UTF16 name works.
1553     class_linker->RegisterDexFileLocked(*dex_file, dex_cache.Get(), /* class_loader= */ nullptr);
1554   }
1555 }
1556 
TEST_F(ClassLinkerMethodHandlesTest,TestResolveMethodTypes)1557 TEST_F(ClassLinkerMethodHandlesTest, TestResolveMethodTypes) {
1558   ScopedObjectAccess soa(Thread::Current());
1559   StackHandleScope<7> hs(soa.Self());
1560 
1561   Handle<mirror::ClassLoader> class_loader(
1562       hs.NewHandle(soa.Decode<mirror::ClassLoader>(LoadDex("MethodTypes"))));
1563   Handle<mirror::Class> method_types(
1564       hs.NewHandle(class_linker_->FindClass(soa.Self(), "LMethodTypes;", class_loader)));
1565   class_linker_->EnsureInitialized(soa.Self(), method_types, true, true);
1566 
1567   ArtMethod* method1 = method_types->FindClassMethod(
1568       "method1",
1569       "(Ljava/lang/String;)Ljava/lang/String;",
1570       kRuntimePointerSize);
1571   ASSERT_TRUE(method1 != nullptr);
1572   ASSERT_FALSE(method1->IsDirect());
1573 
1574   const DexFile& dex_file = *(method1->GetDexFile());
1575   Handle<mirror::DexCache> dex_cache = hs.NewHandle(
1576       class_linker_->FindDexCache(soa.Self(), dex_file));
1577 
1578   const dex::MethodId& method1_id = dex_file.GetMethodId(method1->GetDexMethodIndex());
1579 
1580   // This is the MethodType corresponding to the prototype of
1581   // String MethodTypes# method1(String).
1582   // Its RType = Ljava/lang/String;
1583   // Its PTypes = { Ljava/lang/String; }
1584   Handle<mirror::MethodType> method1_type = hs.NewHandle(
1585       class_linker_->ResolveMethodType(soa.Self(), method1_id.proto_idx_, dex_cache, class_loader));
1586 
1587   // Assert that the method type was resolved successfully.
1588   ASSERT_TRUE(method1_type != nullptr);
1589 
1590   // Assert that the return type and the method arguments are as we expect.
1591   Handle<mirror::Class> string_class(hs.NewHandle(class_linker_->FindClass(soa.Self(),
1592                                                                            "Ljava/lang/String;",
1593                                                                            class_loader)));
1594   ASSERT_OBJ_PTR_EQ(string_class.Get(), method1_type->GetRType());
1595   ASSERT_OBJ_PTR_EQ(string_class.Get(), method1_type->GetPTypes()->Get(0));
1596 
1597   // Resolve the method type again and assert that we get back the same value.
1598   Handle<mirror::MethodType> method1_type2 = hs.NewHandle(
1599       class_linker_->ResolveMethodType(soa.Self(), method1_id.proto_idx_, dex_cache, class_loader));
1600   ASSERT_OBJ_PTR_EQ(method1_type.Get(), method1_type2.Get());
1601 
1602   // Resolve the MethodType associated with a different method signature
1603   // and assert it's different.
1604   ArtMethod* method2 = method_types->FindClassMethod(
1605       "method2",
1606       "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
1607       kRuntimePointerSize);
1608   ASSERT_TRUE(method2 != nullptr);
1609   ASSERT_FALSE(method2->IsDirect());
1610   const dex::MethodId& method2_id = dex_file.GetMethodId(method2->GetDexMethodIndex());
1611   Handle<mirror::MethodType> method2_type = hs.NewHandle(
1612       class_linker_->ResolveMethodType(soa.Self(), method2_id.proto_idx_, dex_cache, class_loader));
1613   ASSERT_OBJ_PTR_NE(method1_type.Get(), method2_type.Get());
1614 }
1615 
1616 // Verify that ClassLinker's CreateWellknownClassLoader works as expected
1617 // by creating a chain of class loaders with various dex files.
TEST_F(ClassLinkerTest,CreateWellKnownClassLoader)1618 TEST_F(ClassLinkerTest, CreateWellKnownClassLoader) {
1619   // LoadDexIn*ClassLoader methods already assert that the parent loader is the expected one.
1620   // No need to check again.
1621   jobject class_loader_a = LoadDexInPathClassLoader("MyClass", nullptr);
1622   jobject class_loader_b = LoadDexInDelegateLastClassLoader("Nested", class_loader_a);
1623   jobject class_loader_c = LoadDexInPathClassLoader("MultiDex", class_loader_b);
1624   LoadDexInDelegateLastClassLoader("Interfaces", class_loader_c);
1625 }
1626 
TEST_F(ClassLinkerTest,PrettyClass)1627 TEST_F(ClassLinkerTest, PrettyClass) {
1628   ScopedObjectAccess soa(Thread::Current());
1629   EXPECT_EQ("null", mirror::Class::PrettyClass(nullptr));
1630   ObjPtr<mirror::Class> c = class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/String;");
1631   ASSERT_TRUE(c != nullptr);
1632   ObjPtr<mirror::Object> o = mirror::ObjectArray<mirror::String>::Alloc(soa.Self(), c, 0);
1633   EXPECT_EQ("java.lang.Class<java.lang.String[]>", mirror::Class::PrettyClass(o->GetClass()));
1634 }
1635 
TEST_F(ClassLinkerTest,PrettyClassAndClassLoader)1636 TEST_F(ClassLinkerTest, PrettyClassAndClassLoader) {
1637   ScopedObjectAccess soa(Thread::Current());
1638   EXPECT_EQ("null", mirror::Class::PrettyClassAndClassLoader(nullptr));
1639   ObjPtr<mirror::Class> c = class_linker_->FindSystemClass(soa.Self(), "[Ljava/lang/String;");
1640   ASSERT_TRUE(c != nullptr);
1641   ObjPtr<mirror::Object> o = mirror::ObjectArray<mirror::String>::Alloc(soa.Self(), c, 0);
1642   EXPECT_EQ("java.lang.Class<java.lang.String[],null>",
1643             mirror::Class::PrettyClassAndClassLoader(o->GetClass()));
1644 }
1645 
TEST_F(ClassLinkerTest,PrettyField)1646 TEST_F(ClassLinkerTest, PrettyField) {
1647   ScopedObjectAccess soa(Thread::Current());
1648   EXPECT_EQ("null", ArtField::PrettyField(nullptr));
1649 
1650   ObjPtr<mirror::Class> java_lang_String = class_linker_->FindSystemClass(soa.Self(),
1651                                                                           "Ljava/lang/String;");
1652 
1653   ArtField* f;
1654   f = java_lang_String->FindDeclaredInstanceField("count", "I");
1655   EXPECT_EQ("int java.lang.String.count", f->PrettyField());
1656   EXPECT_EQ("java.lang.String.count", f->PrettyField(false));
1657 }
1658 
TEST_F(ClassLinkerTest,JniShortName_JniLongName)1659 TEST_F(ClassLinkerTest, JniShortName_JniLongName) {
1660   ScopedObjectAccess soa(Thread::Current());
1661   ObjPtr<mirror::Class> c = class_linker_->FindSystemClass(soa.Self(), "Ljava/lang/String;");
1662   ASSERT_TRUE(c != nullptr);
1663   ArtMethod* m;
1664 
1665   m = c->FindClassMethod("charAt", "(I)C", kRuntimePointerSize);
1666   ASSERT_TRUE(m != nullptr);
1667   ASSERT_FALSE(m->IsDirect());
1668   EXPECT_EQ("Java_java_lang_String_charAt", m->JniShortName());
1669   EXPECT_EQ("Java_java_lang_String_charAt__I", m->JniLongName());
1670 
1671   m = c->FindClassMethod("indexOf", "(Ljava/lang/String;I)I", kRuntimePointerSize);
1672   ASSERT_TRUE(m != nullptr);
1673   ASSERT_FALSE(m->IsDirect());
1674   EXPECT_EQ("Java_java_lang_String_indexOf", m->JniShortName());
1675   EXPECT_EQ("Java_java_lang_String_indexOf__Ljava_lang_String_2I", m->JniLongName());
1676 
1677   m = c->FindClassMethod("copyValueOf", "([CII)Ljava/lang/String;", kRuntimePointerSize);
1678   ASSERT_TRUE(m != nullptr);
1679   ASSERT_TRUE(m->IsStatic());
1680   EXPECT_EQ("Java_java_lang_String_copyValueOf", m->JniShortName());
1681   EXPECT_EQ("Java_java_lang_String_copyValueOf___3CII", m->JniLongName());
1682 }
1683 
1684 class ClassLinkerClassLoaderTest : public ClassLinkerTest {
1685  protected:
1686   // Verifies that the class identified by the given descriptor is loaded with
1687   // the expected_class_loader_obj when search from class_loader_to_search_obj.
1688   // 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)1689   void VerifyClassResolution(const std::string& descriptor,
1690                              jobject class_loader_to_search_obj,
1691                              jobject expected_class_loader_obj,
1692                              bool should_find = true) {
1693     Thread* self = Thread::Current();
1694     ScopedObjectAccess soa(self);
1695     StackHandleScope<3> hs(self);
1696     Handle<mirror::ClassLoader> class_loader_to_search(
1697         hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader_to_search_obj)));
1698 
1699     Handle<mirror::Class> klass = hs.NewHandle(
1700         class_linker_->FindClass(soa.Self(), descriptor.c_str(), class_loader_to_search));
1701 
1702     if (!should_find) {
1703       if (self->IsExceptionPending()) {
1704         self->ClearException();
1705       }
1706       ASSERT_TRUE(klass == nullptr);
1707     } else if (expected_class_loader_obj == nullptr) {
1708       ASSERT_TRUE(ClassLinker::IsBootClassLoader(soa, klass->GetClassLoader()));
1709     } else {
1710       ASSERT_TRUE(klass != nullptr) << descriptor;
1711       Handle<mirror::ClassLoader> expected_class_loader(
1712           hs.NewHandle(soa.Decode<mirror::ClassLoader>(expected_class_loader_obj)));
1713       ASSERT_OBJ_PTR_EQ(klass->GetClassLoader(), expected_class_loader.Get());
1714     }
1715   }
1716 };
1717 
TEST_F(ClassLinkerClassLoaderTest,CreatePathClassLoader)1718 TEST_F(ClassLinkerClassLoaderTest, CreatePathClassLoader) {
1719   jobject class_loader_a = LoadDexInPathClassLoader("ForClassLoaderA", nullptr);
1720   VerifyClassResolution("LDefinedInA;", class_loader_a, class_loader_a);
1721   VerifyClassResolution("Ljava/lang/String;", class_loader_a, nullptr);
1722   VerifyClassResolution("LDefinedInB;", class_loader_a, nullptr, /*should_find=*/ false);
1723 }
1724 
TEST_F(ClassLinkerClassLoaderTest,CreateDelegateLastClassLoader)1725 TEST_F(ClassLinkerClassLoaderTest, CreateDelegateLastClassLoader) {
1726   jobject class_loader_a = LoadDexInDelegateLastClassLoader("ForClassLoaderA", nullptr);
1727   VerifyClassResolution("LDefinedInA;", class_loader_a, class_loader_a);
1728   VerifyClassResolution("Ljava/lang/String;", class_loader_a, nullptr);
1729   VerifyClassResolution("LDefinedInB;", class_loader_a, nullptr, /*should_find=*/ false);
1730 }
1731 
TEST_F(ClassLinkerClassLoaderTest,CreateClassLoaderChain)1732 TEST_F(ClassLinkerClassLoaderTest, CreateClassLoaderChain) {
1733   // The chain is
1734   //    ClassLoaderA (PathClassLoader, defines: A, AB, AC, AD)
1735   //       ^
1736   //       |
1737   //    ClassLoaderB (DelegateLastClassLoader, defines: B, AB, BC, BD)
1738   //       ^
1739   //       |
1740   //    ClassLoaderC (PathClassLoader, defines: C, AC, BC, CD)
1741   //       ^
1742   //       |
1743   //    ClassLoaderD (DelegateLastClassLoader, defines: D, AD, BD, CD)
1744 
1745   jobject class_loader_a = LoadDexInPathClassLoader("ForClassLoaderA", nullptr);
1746   jobject class_loader_b = LoadDexInDelegateLastClassLoader("ForClassLoaderB", class_loader_a);
1747   jobject class_loader_c = LoadDexInPathClassLoader("ForClassLoaderC", class_loader_b);
1748   jobject class_loader_d = LoadDexInDelegateLastClassLoader("ForClassLoaderD", class_loader_c);
1749 
1750   // Verify exclusive classes (present in only one class loader).
1751   VerifyClassResolution("LDefinedInD;", class_loader_d, class_loader_d);
1752   VerifyClassResolution("LDefinedInC;", class_loader_d, class_loader_c);
1753   VerifyClassResolution("LDefinedInB;", class_loader_d, class_loader_b);
1754   VerifyClassResolution("LDefinedInA;", class_loader_d, class_loader_a);
1755 
1756   // Verify classes that are defined in multiple classloader.
1757 
1758   // Classes defined in B should be found in B even if they are defined in A or C because
1759   // B is a DelegateLastClassLoader.
1760   VerifyClassResolution("LDefinedInAB;", class_loader_d, class_loader_b);
1761   VerifyClassResolution("LDefinedInABC;", class_loader_d, class_loader_b);
1762   VerifyClassResolution("LDefinedInBC;", class_loader_d, class_loader_b);
1763 
1764   // Classes defined in D should be found in D even if they are defined in parent class loaders
1765   // as well because D is a DelegateLastClassLoader.
1766   VerifyClassResolution("LDefinedInAD;", class_loader_d, class_loader_d);
1767   VerifyClassResolution("LDefinedInBD;", class_loader_d, class_loader_d);
1768   VerifyClassResolution("LDefinedInCD;", class_loader_d, class_loader_d);
1769 
1770 
1771   // Classes not defined in the DelegateLastClassLoaders (i.e. D or B) should be found
1772   // in the top parent.
1773   VerifyClassResolution("LDefinedInAC;", class_loader_d, class_loader_a);
1774 
1775   // Check that we don't find an undefined class.
1776   VerifyClassResolution("LNotDefined;", class_loader_d, nullptr, /*should_find=*/ false);
1777 }
1778 
1779 }  // namespace art
1780