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