• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <fcntl.h>
20 #include <sys/file.h>
21 #include <sys/stat.h>
22 #include <deque>
23 #include <memory>
24 #include <string>
25 #include <utility>
26 #include <vector>
27 
28 #include "base/casts.h"
29 #include "base/logging.h"
30 #include "base/scoped_flock.h"
31 #include "base/stl_util.h"
32 #include "base/unix_file/fd_file.h"
33 #include "class_linker-inl.h"
34 #include "compiler_callbacks.h"
35 #include "debugger.h"
36 #include "dex_file-inl.h"
37 #include "gc_root-inl.h"
38 #include "gc/accounting/card_table-inl.h"
39 #include "gc/accounting/heap_bitmap.h"
40 #include "gc/heap.h"
41 #include "gc/space/image_space.h"
42 #include "handle_scope.h"
43 #include "intern_table.h"
44 #include "interpreter/interpreter.h"
45 #include "leb128.h"
46 #include "method_helper-inl.h"
47 #include "oat.h"
48 #include "oat_file.h"
49 #include "object_lock.h"
50 #include "mirror/art_field-inl.h"
51 #include "mirror/art_method-inl.h"
52 #include "mirror/class.h"
53 #include "mirror/class-inl.h"
54 #include "mirror/class_loader.h"
55 #include "mirror/dex_cache-inl.h"
56 #include "mirror/iftable-inl.h"
57 #include "mirror/object-inl.h"
58 #include "mirror/object_array-inl.h"
59 #include "mirror/proxy.h"
60 #include "mirror/reference-inl.h"
61 #include "mirror/stack_trace_element.h"
62 #include "mirror/string-inl.h"
63 #include "os.h"
64 #include "runtime.h"
65 #include "entrypoints/entrypoint_utils.h"
66 #include "ScopedLocalRef.h"
67 #include "scoped_thread_state_change.h"
68 #include "handle_scope-inl.h"
69 #include "thread.h"
70 #include "utils.h"
71 #include "verifier/method_verifier.h"
72 #include "well_known_classes.h"
73 
74 namespace art {
75 
76 static void ThrowNoClassDefFoundError(const char* fmt, ...)
77     __attribute__((__format__(__printf__, 1, 2)))
78     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
ThrowNoClassDefFoundError(const char * fmt,...)79 static void ThrowNoClassDefFoundError(const char* fmt, ...) {
80   va_list args;
81   va_start(args, fmt);
82   Thread* self = Thread::Current();
83   ThrowLocation throw_location = self->GetCurrentLocationForThrow();
84   self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
85   va_end(args);
86 }
87 
ThrowEarlierClassFailure(mirror::Class * c)88 static void ThrowEarlierClassFailure(mirror::Class* c)
89     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
90   // The class failed to initialize on a previous attempt, so we want to throw
91   // a NoClassDefFoundError (v2 2.17.5).  The exception to this rule is if we
92   // failed in verification, in which case v2 5.4.1 says we need to re-throw
93   // the previous error.
94   if (!Runtime::Current()->IsCompiler()) {  // Give info if this occurs at runtime.
95     LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
96   }
97 
98   CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
99   Thread* self = Thread::Current();
100   ThrowLocation throw_location = self->GetCurrentLocationForThrow();
101   if (c->GetVerifyErrorClass() != nullptr) {
102     // TODO: change the verifier to store an _instance_, with a useful detail message?
103     std::string temp;
104     self->ThrowNewException(throw_location, c->GetVerifyErrorClass()->GetDescriptor(&temp),
105                             PrettyDescriptor(c).c_str());
106   } else {
107     self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
108                             PrettyDescriptor(c).c_str());
109   }
110 }
111 
WrapExceptionInInitializer()112 static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
113   Thread* self = Thread::Current();
114   JNIEnv* env = self->GetJniEnv();
115 
116   ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
117   CHECK(cause.get() != nullptr);
118 
119   env->ExceptionClear();
120   bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
121   env->Throw(cause.get());
122 
123   // We only wrap non-Error exceptions; an Error can just be used as-is.
124   if (!is_error) {
125     ThrowLocation throw_location = self->GetCurrentLocationForThrow();
126     self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;",
127                                    nullptr);
128   }
129 }
130 
Hash(const char * s)131 static size_t Hash(const char* s) {
132   // This is the java.lang.String hashcode for convenience, not interoperability.
133   size_t hash = 0;
134   for (; *s != '\0'; ++s) {
135     hash = hash * 31 + *s;
136   }
137   return hash;
138 }
139 
140 const char* ClassLinker::class_roots_descriptors_[] = {
141   "Ljava/lang/Class;",
142   "Ljava/lang/Object;",
143   "[Ljava/lang/Class;",
144   "[Ljava/lang/Object;",
145   "Ljava/lang/String;",
146   "Ljava/lang/DexCache;",
147   "Ljava/lang/ref/Reference;",
148   "Ljava/lang/reflect/ArtField;",
149   "Ljava/lang/reflect/ArtMethod;",
150   "Ljava/lang/reflect/Proxy;",
151   "[Ljava/lang/String;",
152   "[Ljava/lang/reflect/ArtField;",
153   "[Ljava/lang/reflect/ArtMethod;",
154   "Ljava/lang/ClassLoader;",
155   "Ljava/lang/Throwable;",
156   "Ljava/lang/ClassNotFoundException;",
157   "Ljava/lang/StackTraceElement;",
158   "Z",
159   "B",
160   "C",
161   "D",
162   "F",
163   "I",
164   "J",
165   "S",
166   "V",
167   "[Z",
168   "[B",
169   "[C",
170   "[D",
171   "[F",
172   "[I",
173   "[J",
174   "[S",
175   "[Ljava/lang/StackTraceElement;",
176 };
177 
ClassLinker(InternTable * intern_table)178 ClassLinker::ClassLinker(InternTable* intern_table)
179     // dex_lock_ is recursive as it may be used in stack dumping.
180     : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
181       dex_cache_image_class_lookup_required_(false),
182       failed_dex_cache_class_lookups_(0),
183       class_roots_(nullptr),
184       array_iftable_(nullptr),
185       find_array_class_cache_next_victim_(0),
186       init_done_(false),
187       log_new_dex_caches_roots_(false),
188       log_new_class_table_roots_(false),
189       intern_table_(intern_table),
190       portable_resolution_trampoline_(nullptr),
191       quick_resolution_trampoline_(nullptr),
192       portable_imt_conflict_trampoline_(nullptr),
193       quick_imt_conflict_trampoline_(nullptr),
194       quick_generic_jni_trampoline_(nullptr),
195       quick_to_interpreter_bridge_trampoline_(nullptr) {
196   CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
197   memset(find_array_class_cache_, 0, kFindArrayCacheSize * sizeof(mirror::Class*));
198 }
199 
200 // To set a value for generic JNI. May be necessary in compiler tests.
201 extern "C" void art_quick_generic_jni_trampoline(mirror::ArtMethod*);
202 extern "C" void art_quick_resolution_trampoline(mirror::ArtMethod*);
203 extern "C" void art_quick_imt_conflict_trampoline(mirror::ArtMethod*);
204 extern "C" void art_quick_to_interpreter_bridge(mirror::ArtMethod*);
205 
InitWithoutImage(const std::vector<const DexFile * > & boot_class_path)206 void ClassLinker::InitWithoutImage(const std::vector<const DexFile*>& boot_class_path) {
207   VLOG(startup) << "ClassLinker::Init";
208   CHECK(!Runtime::Current()->GetHeap()->HasImageSpace()) << "Runtime has image. We should use it.";
209 
210   CHECK(!init_done_);
211 
212   // java_lang_Class comes first, it's needed for AllocClass
213   Thread* self = Thread::Current();
214   gc::Heap* heap = Runtime::Current()->GetHeap();
215   // The GC can't handle an object with a null class since we can't get the size of this object.
216   heap->IncrementDisableMovingGC(self);
217   StackHandleScope<64> hs(self);  // 64 is picked arbitrarily.
218   Handle<mirror::Class> java_lang_Class(hs.NewHandle(down_cast<mirror::Class*>(
219       heap->AllocNonMovableObject<true>(self, nullptr,
220                                         mirror::Class::ClassClassSize(),
221                                         VoidFunctor()))));
222   CHECK(java_lang_Class.Get() != nullptr);
223   mirror::Class::SetClassClass(java_lang_Class.Get());
224   java_lang_Class->SetClass(java_lang_Class.Get());
225   if (kUseBakerOrBrooksReadBarrier) {
226     java_lang_Class->AssertReadBarrierPointer();
227   }
228   java_lang_Class->SetClassSize(mirror::Class::ClassClassSize());
229   heap->DecrementDisableMovingGC(self);
230   // AllocClass(mirror::Class*) can now be used
231 
232   // Class[] is used for reflection support.
233   Handle<mirror::Class> class_array_class(hs.NewHandle(
234      AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Class>::ClassSize())));
235   class_array_class->SetComponentType(java_lang_Class.Get());
236 
237   // java_lang_Object comes next so that object_array_class can be created.
238   Handle<mirror::Class> java_lang_Object(hs.NewHandle(
239       AllocClass(self, java_lang_Class.Get(), mirror::Object::ClassSize())));
240   CHECK(java_lang_Object.Get() != nullptr);
241   // backfill Object as the super class of Class.
242   java_lang_Class->SetSuperClass(java_lang_Object.Get());
243   java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
244 
245   // Object[] next to hold class roots.
246   Handle<mirror::Class> object_array_class(hs.NewHandle(
247       AllocClass(self, java_lang_Class.Get(), mirror::ObjectArray<mirror::Object>::ClassSize())));
248   object_array_class->SetComponentType(java_lang_Object.Get());
249 
250   // Setup the char (primitive) class to be used for char[].
251   Handle<mirror::Class> char_class(hs.NewHandle(
252       AllocClass(self, java_lang_Class.Get(), mirror::Class::PrimitiveClassSize())));
253 
254   // Setup the char[] class to be used for String.
255   Handle<mirror::Class> char_array_class(hs.NewHandle(
256       AllocClass(self, java_lang_Class.Get(),
257                  mirror::Array::ClassSize())));
258   char_array_class->SetComponentType(char_class.Get());
259   mirror::CharArray::SetArrayClass(char_array_class.Get());
260 
261   // Setup String.
262   Handle<mirror::Class> java_lang_String(hs.NewHandle(
263       AllocClass(self, java_lang_Class.Get(), mirror::String::ClassSize())));
264   mirror::String::SetClass(java_lang_String.Get());
265   java_lang_String->SetObjectSize(mirror::String::InstanceSize());
266   java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
267 
268   // Setup Reference.
269   Handle<mirror::Class> java_lang_ref_Reference(hs.NewHandle(
270       AllocClass(self, java_lang_Class.Get(), mirror::Reference::ClassSize())));
271   mirror::Reference::SetClass(java_lang_ref_Reference.Get());
272   java_lang_ref_Reference->SetObjectSize(mirror::Reference::InstanceSize());
273   java_lang_ref_Reference->SetStatus(mirror::Class::kStatusResolved, self);
274 
275   // Create storage for root classes, save away our work so far (requires descriptors).
276   class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class> >(
277       mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.Get(),
278                                                 kClassRootsMax));
279   CHECK(!class_roots_.IsNull());
280   SetClassRoot(kJavaLangClass, java_lang_Class.Get());
281   SetClassRoot(kJavaLangObject, java_lang_Object.Get());
282   SetClassRoot(kClassArrayClass, class_array_class.Get());
283   SetClassRoot(kObjectArrayClass, object_array_class.Get());
284   SetClassRoot(kCharArrayClass, char_array_class.Get());
285   SetClassRoot(kJavaLangString, java_lang_String.Get());
286   SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference.Get());
287 
288   // Setup the primitive type classes.
289   SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
290   SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
291   SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
292   SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
293   SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
294   SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
295   SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
296   SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
297 
298   // Create array interface entries to populate once we can load system classes.
299   array_iftable_ = GcRoot<mirror::IfTable>(AllocIfTable(self, 2));
300 
301   // Create int array type for AllocDexCache (done in AppendToBootClassPath).
302   Handle<mirror::Class> int_array_class(hs.NewHandle(
303       AllocClass(self, java_lang_Class.Get(), mirror::Array::ClassSize())));
304   int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
305   mirror::IntArray::SetArrayClass(int_array_class.Get());
306   SetClassRoot(kIntArrayClass, int_array_class.Get());
307 
308   // now that these are registered, we can use AllocClass() and AllocObjectArray
309 
310   // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
311   Handle<mirror::Class> java_lang_DexCache(hs.NewHandle(
312       AllocClass(self, java_lang_Class.Get(), mirror::DexCache::ClassSize())));
313   SetClassRoot(kJavaLangDexCache, java_lang_DexCache.Get());
314   java_lang_DexCache->SetObjectSize(mirror::DexCache::InstanceSize());
315   java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
316 
317   // Constructor, Field, Method, and AbstractMethod are necessary so
318   // that FindClass can link members.
319   Handle<mirror::Class> java_lang_reflect_ArtField(hs.NewHandle(
320       AllocClass(self, java_lang_Class.Get(), mirror::ArtField::ClassSize())));
321   CHECK(java_lang_reflect_ArtField.Get() != nullptr);
322   java_lang_reflect_ArtField->SetObjectSize(mirror::ArtField::InstanceSize());
323   SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.Get());
324   java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
325   mirror::ArtField::SetClass(java_lang_reflect_ArtField.Get());
326 
327   Handle<mirror::Class> java_lang_reflect_ArtMethod(hs.NewHandle(
328     AllocClass(self, java_lang_Class.Get(), mirror::ArtMethod::ClassSize())));
329   CHECK(java_lang_reflect_ArtMethod.Get() != nullptr);
330   java_lang_reflect_ArtMethod->SetObjectSize(mirror::ArtMethod::InstanceSize());
331   SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.Get());
332   java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
333 
334   mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.Get());
335 
336   // Set up array classes for string, field, method
337   Handle<mirror::Class> object_array_string(hs.NewHandle(
338       AllocClass(self, java_lang_Class.Get(),
339                  mirror::ObjectArray<mirror::String>::ClassSize())));
340   object_array_string->SetComponentType(java_lang_String.Get());
341   SetClassRoot(kJavaLangStringArrayClass, object_array_string.Get());
342 
343   Handle<mirror::Class> object_array_art_method(hs.NewHandle(
344       AllocClass(self, java_lang_Class.Get(),
345                  mirror::ObjectArray<mirror::ArtMethod>::ClassSize())));
346   object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.Get());
347   SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.Get());
348 
349   Handle<mirror::Class> object_array_art_field(hs.NewHandle(
350       AllocClass(self, java_lang_Class.Get(),
351                  mirror::ObjectArray<mirror::ArtField>::ClassSize())));
352   object_array_art_field->SetComponentType(java_lang_reflect_ArtField.Get());
353   SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.Get());
354 
355   // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
356   // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
357   // these roots.
358   CHECK_NE(0U, boot_class_path.size());
359   for (size_t i = 0; i != boot_class_path.size(); ++i) {
360     const DexFile* dex_file = boot_class_path[i];
361     CHECK(dex_file != nullptr);
362     AppendToBootClassPath(*dex_file);
363   }
364 
365   // now we can use FindSystemClass
366 
367   // run char class through InitializePrimitiveClass to finish init
368   InitializePrimitiveClass(char_class.Get(), Primitive::kPrimChar);
369   SetClassRoot(kPrimitiveChar, char_class.Get());  // needs descriptor
370 
371   // Create runtime resolution and imt conflict methods. Also setup the default imt.
372   Runtime* runtime = Runtime::Current();
373   runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
374   runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
375   runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
376 
377   // Set up GenericJNI entrypoint. That is mainly a hack for common_compiler_test.h so that
378   // we do not need friend classes or a publicly exposed setter.
379   quick_generic_jni_trampoline_ = reinterpret_cast<void*>(art_quick_generic_jni_trampoline);
380   if (!runtime->IsCompiler()) {
381     // We need to set up the generic trampolines since we don't have an image.
382     quick_resolution_trampoline_ = reinterpret_cast<void*>(art_quick_resolution_trampoline);
383     quick_imt_conflict_trampoline_ = reinterpret_cast<void*>(art_quick_imt_conflict_trampoline);
384     quick_to_interpreter_bridge_trampoline_ = reinterpret_cast<void*>(art_quick_to_interpreter_bridge);
385   }
386 
387   // Object, String and DexCache need to be rerun through FindSystemClass to finish init
388   java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
389   mirror::Class* Object_class = FindSystemClass(self, "Ljava/lang/Object;");
390   CHECK_EQ(java_lang_Object.Get(), Object_class);
391   CHECK_EQ(java_lang_Object->GetObjectSize(), mirror::Object::InstanceSize());
392   java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
393   mirror::Class* String_class = FindSystemClass(self, "Ljava/lang/String;");
394   std::ostringstream os1, os2;
395   java_lang_String->DumpClass(os1, mirror::Class::kDumpClassFullDetail);
396   String_class->DumpClass(os2, mirror::Class::kDumpClassFullDetail);
397   CHECK_EQ(java_lang_String.Get(), String_class) << os1.str() << "\n\n" << os2.str();
398   CHECK_EQ(java_lang_String->GetObjectSize(), mirror::String::InstanceSize());
399   java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
400   mirror::Class* DexCache_class = FindSystemClass(self, "Ljava/lang/DexCache;");
401   CHECK_EQ(java_lang_String.Get(), String_class);
402   CHECK_EQ(java_lang_DexCache.Get(), DexCache_class);
403   CHECK_EQ(java_lang_DexCache->GetObjectSize(), mirror::DexCache::InstanceSize());
404 
405   // Setup the primitive array type classes - can't be done until Object has a vtable.
406   SetClassRoot(kBooleanArrayClass, FindSystemClass(self, "[Z"));
407   mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
408 
409   SetClassRoot(kByteArrayClass, FindSystemClass(self, "[B"));
410   mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
411 
412   mirror::Class* found_char_array_class = FindSystemClass(self, "[C");
413   CHECK_EQ(char_array_class.Get(), found_char_array_class);
414 
415   SetClassRoot(kShortArrayClass, FindSystemClass(self, "[S"));
416   mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
417 
418   mirror::Class* found_int_array_class = FindSystemClass(self, "[I");
419   CHECK_EQ(int_array_class.Get(), found_int_array_class);
420 
421   SetClassRoot(kLongArrayClass, FindSystemClass(self, "[J"));
422   mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
423 
424   SetClassRoot(kFloatArrayClass, FindSystemClass(self, "[F"));
425   mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
426 
427   SetClassRoot(kDoubleArrayClass, FindSystemClass(self, "[D"));
428   mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
429 
430   mirror::Class* found_class_array_class = FindSystemClass(self, "[Ljava/lang/Class;");
431   CHECK_EQ(class_array_class.Get(), found_class_array_class);
432 
433   mirror::Class* found_object_array_class = FindSystemClass(self, "[Ljava/lang/Object;");
434   CHECK_EQ(object_array_class.Get(), found_object_array_class);
435 
436   // Setup the single, global copy of "iftable".
437   mirror::Class* java_lang_Cloneable = FindSystemClass(self, "Ljava/lang/Cloneable;");
438   CHECK(java_lang_Cloneable != nullptr);
439   mirror::Class* java_io_Serializable = FindSystemClass(self, "Ljava/io/Serializable;");
440   CHECK(java_io_Serializable != nullptr);
441   // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
442   // crawl up and explicitly list all of the supers as well.
443   {
444     mirror::IfTable* array_iftable = array_iftable_.Read();
445     array_iftable->SetInterface(0, java_lang_Cloneable);
446     array_iftable->SetInterface(1, java_io_Serializable);
447   }
448 
449   // Sanity check Class[] and Object[]'s interfaces.
450   CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, class_array_class, 0));
451   CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, class_array_class, 1));
452   CHECK_EQ(java_lang_Cloneable, mirror::Class::GetDirectInterface(self, object_array_class, 0));
453   CHECK_EQ(java_io_Serializable, mirror::Class::GetDirectInterface(self, object_array_class, 1));
454   // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
455   // dex_cache_ fields and register them in class_table_.
456   mirror::Class* Class_class = FindSystemClass(self, "Ljava/lang/Class;");
457   CHECK_EQ(java_lang_Class.Get(), Class_class);
458 
459   java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
460   mirror::Class* Art_method_class = FindSystemClass(self, "Ljava/lang/reflect/ArtMethod;");
461   CHECK_EQ(java_lang_reflect_ArtMethod.Get(), Art_method_class);
462 
463   java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
464   mirror::Class* Art_field_class = FindSystemClass(self, "Ljava/lang/reflect/ArtField;");
465   CHECK_EQ(java_lang_reflect_ArtField.Get(), Art_field_class);
466 
467   mirror::Class* String_array_class =
468       FindSystemClass(self, class_roots_descriptors_[kJavaLangStringArrayClass]);
469   CHECK_EQ(object_array_string.Get(), String_array_class);
470 
471   mirror::Class* Art_method_array_class =
472       FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
473   CHECK_EQ(object_array_art_method.Get(), Art_method_array_class);
474 
475   mirror::Class* Art_field_array_class =
476       FindSystemClass(self, class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
477   CHECK_EQ(object_array_art_field.Get(), Art_field_array_class);
478 
479   // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
480 
481   // Create java.lang.reflect.Proxy root.
482   mirror::Class* java_lang_reflect_Proxy = FindSystemClass(self, "Ljava/lang/reflect/Proxy;");
483   SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
484 
485   // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
486   // finish initializing Reference class
487   java_lang_ref_Reference->SetStatus(mirror::Class::kStatusNotReady, self);
488   mirror::Class* Reference_class = FindSystemClass(self, "Ljava/lang/ref/Reference;");
489   CHECK_EQ(java_lang_ref_Reference.Get(), Reference_class);
490   CHECK_EQ(java_lang_ref_Reference->GetObjectSize(), mirror::Reference::InstanceSize());
491   CHECK_EQ(java_lang_ref_Reference->GetClassSize(), mirror::Reference::ClassSize());
492   mirror::Class* java_lang_ref_FinalizerReference =
493       FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
494   java_lang_ref_FinalizerReference->SetAccessFlags(
495       java_lang_ref_FinalizerReference->GetAccessFlags() |
496           kAccClassIsReference | kAccClassIsFinalizerReference);
497   mirror::Class* java_lang_ref_PhantomReference =
498       FindSystemClass(self, "Ljava/lang/ref/PhantomReference;");
499   java_lang_ref_PhantomReference->SetAccessFlags(
500       java_lang_ref_PhantomReference->GetAccessFlags() |
501           kAccClassIsReference | kAccClassIsPhantomReference);
502   mirror::Class* java_lang_ref_SoftReference =
503       FindSystemClass(self, "Ljava/lang/ref/SoftReference;");
504   java_lang_ref_SoftReference->SetAccessFlags(
505       java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
506   mirror::Class* java_lang_ref_WeakReference =
507       FindSystemClass(self, "Ljava/lang/ref/WeakReference;");
508   java_lang_ref_WeakReference->SetAccessFlags(
509       java_lang_ref_WeakReference->GetAccessFlags() |
510           kAccClassIsReference | kAccClassIsWeakReference);
511 
512   // Setup the ClassLoader, verifying the object_size_.
513   mirror::Class* java_lang_ClassLoader = FindSystemClass(self, "Ljava/lang/ClassLoader;");
514   CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), mirror::ClassLoader::InstanceSize());
515   SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
516 
517   // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
518   // java.lang.StackTraceElement as a convenience.
519   SetClassRoot(kJavaLangThrowable, FindSystemClass(self, "Ljava/lang/Throwable;"));
520   mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
521   SetClassRoot(kJavaLangClassNotFoundException,
522                FindSystemClass(self, "Ljava/lang/ClassNotFoundException;"));
523   SetClassRoot(kJavaLangStackTraceElement, FindSystemClass(self, "Ljava/lang/StackTraceElement;"));
524   SetClassRoot(kJavaLangStackTraceElementArrayClass,
525                FindSystemClass(self, "[Ljava/lang/StackTraceElement;"));
526   mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
527 
528   FinishInit(self);
529 
530   VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
531 }
532 
FinishInit(Thread * self)533 void ClassLinker::FinishInit(Thread* self) {
534   VLOG(startup) << "ClassLinker::FinishInit entering";
535 
536   // Let the heap know some key offsets into java.lang.ref instances
537   // Note: we hard code the field indexes here rather than using FindInstanceField
538   // as the types of the field can't be resolved prior to the runtime being
539   // fully initialized
540   mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
541   mirror::Class* java_lang_ref_FinalizerReference =
542       FindSystemClass(self, "Ljava/lang/ref/FinalizerReference;");
543 
544   mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
545   CHECK_STREQ(pendingNext->GetName(), "pendingNext");
546   CHECK_STREQ(pendingNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
547 
548   mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
549   CHECK_STREQ(queue->GetName(), "queue");
550   CHECK_STREQ(queue->GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
551 
552   mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
553   CHECK_STREQ(queueNext->GetName(), "queueNext");
554   CHECK_STREQ(queueNext->GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
555 
556   mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
557   CHECK_STREQ(referent->GetName(), "referent");
558   CHECK_STREQ(referent->GetTypeDescriptor(), "Ljava/lang/Object;");
559 
560   mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
561   CHECK_STREQ(zombie->GetName(), "zombie");
562   CHECK_STREQ(zombie->GetTypeDescriptor(), "Ljava/lang/Object;");
563 
564   // ensure all class_roots_ are initialized
565   for (size_t i = 0; i < kClassRootsMax; i++) {
566     ClassRoot class_root = static_cast<ClassRoot>(i);
567     mirror::Class* klass = GetClassRoot(class_root);
568     CHECK(klass != nullptr);
569     DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != nullptr);
570     // note SetClassRoot does additional validation.
571     // if possible add new checks there to catch errors early
572   }
573 
574   CHECK(!array_iftable_.IsNull());
575 
576   // disable the slow paths in FindClass and CreatePrimitiveClass now
577   // that Object, Class, and Object[] are setup
578   init_done_ = true;
579 
580   VLOG(startup) << "ClassLinker::FinishInit exiting";
581 }
582 
RunRootClinits()583 void ClassLinker::RunRootClinits() {
584   Thread* self = Thread::Current();
585   for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
586     mirror::Class* c = GetClassRoot(ClassRoot(i));
587     if (!c->IsArrayClass() && !c->IsPrimitive()) {
588       StackHandleScope<1> hs(self);
589       Handle<mirror::Class> h_class(hs.NewHandle(GetClassRoot(ClassRoot(i))));
590       EnsureInitialized(h_class, true, true);
591       self->AssertNoPendingException();
592     }
593   }
594 }
595 
GenerateOatFile(const char * dex_filename,int oat_fd,const char * oat_cache_filename,std::string * error_msg)596 bool ClassLinker::GenerateOatFile(const char* dex_filename,
597                                   int oat_fd,
598                                   const char* oat_cache_filename,
599                                   std::string* error_msg) {
600   Locks::mutator_lock_->AssertNotHeld(Thread::Current());  // Avoid starving GC.
601   std::string dex2oat(Runtime::Current()->GetCompilerExecutable());
602 
603   gc::Heap* heap = Runtime::Current()->GetHeap();
604   std::string boot_image_option("--boot-image=");
605   if (heap->GetImageSpace() == nullptr) {
606     // TODO If we get a dex2dex compiler working we could maybe use that, OTOH since we are likely
607     // out of space anyway it might not matter.
608     *error_msg = StringPrintf("Cannot create oat file for '%s' because we are running "
609                               "without an image.", dex_filename);
610     return false;
611   }
612   boot_image_option += heap->GetImageSpace()->GetImageLocation();
613 
614   std::string dex_file_option("--dex-file=");
615   dex_file_option += dex_filename;
616 
617   std::string oat_fd_option("--oat-fd=");
618   StringAppendF(&oat_fd_option, "%d", oat_fd);
619 
620   std::string oat_location_option("--oat-location=");
621   oat_location_option += oat_cache_filename;
622 
623   std::vector<std::string> argv;
624   argv.push_back(dex2oat);
625   argv.push_back("--runtime-arg");
626   argv.push_back("-classpath");
627   argv.push_back("--runtime-arg");
628   argv.push_back(Runtime::Current()->GetClassPathString());
629 
630   Runtime::Current()->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
631 
632   if (!Runtime::Current()->IsVerificationEnabled()) {
633     argv.push_back("--compiler-filter=verify-none");
634   }
635 
636   if (Runtime::Current()->MustRelocateIfPossible()) {
637     argv.push_back("--runtime-arg");
638     argv.push_back("-Xrelocate");
639   } else {
640     argv.push_back("--runtime-arg");
641     argv.push_back("-Xnorelocate");
642   }
643 
644   if (!kIsTargetBuild) {
645     argv.push_back("--host");
646   }
647 
648   argv.push_back(boot_image_option);
649   argv.push_back(dex_file_option);
650   argv.push_back(oat_fd_option);
651   argv.push_back(oat_location_option);
652   const std::vector<std::string>& compiler_options = Runtime::Current()->GetCompilerOptions();
653   for (size_t i = 0; i < compiler_options.size(); ++i) {
654     argv.push_back(compiler_options[i].c_str());
655   }
656 
657   return Exec(argv, error_msg);
658 }
659 
RegisterOatFile(const OatFile * oat_file)660 const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
661   WriterMutexLock mu(Thread::Current(), dex_lock_);
662   if (kIsDebugBuild) {
663     for (size_t i = 0; i < oat_files_.size(); ++i) {
664       CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
665     }
666   }
667   VLOG(class_linker) << "Registering " << oat_file->GetLocation();
668   oat_files_.push_back(oat_file);
669   return oat_file;
670 }
671 
GetImageOatFile(gc::space::ImageSpace * space)672 OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
673   VLOG(startup) << "ClassLinker::GetImageOatFile entering";
674   OatFile* oat_file = space->ReleaseOatFile();
675   CHECK_EQ(RegisterOatFile(oat_file), oat_file);
676   VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
677   return *oat_file;
678 }
679 
FindOpenedOatDexFileForDexFile(const DexFile & dex_file)680 const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFileForDexFile(const DexFile& dex_file) {
681   const char* dex_location = dex_file.GetLocation().c_str();
682   uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
683   return FindOpenedOatDexFile(nullptr, dex_location, &dex_location_checksum);
684 }
685 
FindOpenedOatDexFile(const char * oat_location,const char * dex_location,const uint32_t * dex_location_checksum)686 const OatFile::OatDexFile* ClassLinker::FindOpenedOatDexFile(const char* oat_location,
687                                                              const char* dex_location,
688                                                              const uint32_t* dex_location_checksum) {
689   ReaderMutexLock mu(Thread::Current(), dex_lock_);
690   for (const OatFile* oat_file : oat_files_) {
691     DCHECK(oat_file != nullptr);
692 
693     if (oat_location != nullptr) {
694       if (oat_file->GetLocation() != oat_location) {
695         continue;
696       }
697     }
698 
699     const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
700                                                                       dex_location_checksum,
701                                                                       false);
702     if (oat_dex_file != nullptr) {
703       return oat_dex_file;
704     }
705   }
706   return nullptr;
707 }
708 
709 
710 // Loads all multi dex files from the given oat file returning true on success.
711 //
712 // Parameters:
713 //   oat_file - the oat file to load from
714 //   dex_location - the dex location used to generate the oat file
715 //   dex_location_checksum - the checksum of the dex_location (may be null for pre-opted files)
716 //   generated - whether or not the oat_file existed before or was just (re)generated
717 //   error_msgs - any error messages will be appended here
718 //   dex_files - the loaded dex_files will be appended here (only if the loading succeeds)
LoadMultiDexFilesFromOatFile(const OatFile * oat_file,const char * dex_location,const uint32_t * dex_location_checksum,bool generated,std::vector<std::string> * error_msgs,std::vector<const DexFile * > * dex_files)719 static bool LoadMultiDexFilesFromOatFile(const OatFile* oat_file,
720                                          const char* dex_location,
721                                          const uint32_t* dex_location_checksum,
722                                          bool generated,
723                                          std::vector<std::string>* error_msgs,
724                                          std::vector<const DexFile*>* dex_files) {
725   if (oat_file == nullptr) {
726     return false;
727   }
728 
729   size_t old_size = dex_files->size();  // To rollback on error.
730 
731   bool success = true;
732   for (size_t i = 0; success; ++i) {
733     std::string next_name_str = DexFile::GetMultiDexClassesDexName(i, dex_location);
734     const char* next_name = next_name_str.c_str();
735 
736     uint32_t next_location_checksum;
737     uint32_t* next_location_checksum_pointer = &next_location_checksum;
738     std::string error_msg;
739     if ((i == 0) && (strcmp(next_name, dex_location) == 0)) {
740       // When i=0 the multidex name should be the same as the location name. We already have the
741       // checksum it so we don't need to recompute it.
742       if (dex_location_checksum == nullptr) {
743         next_location_checksum_pointer = nullptr;
744       } else {
745         next_location_checksum = *dex_location_checksum;
746       }
747     } else if (!DexFile::GetChecksum(next_name, next_location_checksum_pointer, &error_msg)) {
748       DCHECK_EQ(false, i == 0 && generated);
749       next_location_checksum_pointer = nullptr;
750     }
751 
752     const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(next_name, nullptr, false);
753 
754     if (oat_dex_file == nullptr) {
755       if (i == 0 && generated) {
756         std::string error_msg;
757         error_msg = StringPrintf("\nFailed to find dex file '%s' (checksum 0x%x) in generated out "
758                                  " file'%s'", dex_location, next_location_checksum,
759                                  oat_file->GetLocation().c_str());
760         error_msgs->push_back(error_msg);
761       }
762       break;  // Not found, done.
763     }
764 
765     // Checksum test. Test must succeed when generated.
766     success = !generated;
767     if (next_location_checksum_pointer != nullptr) {
768       success = next_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
769     }
770 
771     if (success) {
772       const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
773       if (dex_file == nullptr) {
774         success = false;
775         error_msgs->push_back(error_msg);
776       } else {
777         dex_files->push_back(dex_file);
778       }
779     }
780 
781     // When we generated the file, we expect success, or something is terribly wrong.
782     CHECK_EQ(false, generated && !success)
783         << "dex_location=" << next_name << " oat_location=" << oat_file->GetLocation().c_str()
784         << std::hex << " dex_location_checksum=" << next_location_checksum
785         << " OatDexFile::GetLocationChecksum()=" << oat_dex_file->GetDexFileLocationChecksum();
786   }
787 
788   if (dex_files->size() == old_size) {
789     success = false;  // We did not even find classes.dex
790   }
791 
792   if (success) {
793     return true;
794   } else {
795     // Free all the dex files we have loaded.
796     auto it = dex_files->begin() + old_size;
797     auto it_end = dex_files->end();
798     for (; it != it_end; it++) {
799       delete *it;
800     }
801     dex_files->erase(dex_files->begin() + old_size, it_end);
802 
803     return false;
804   }
805 }
806 
807 // Multidex files make it possible that some, but not all, dex files can be broken/outdated. This
808 // complicates the loading process, as we should not use an iterative loading process, because that
809 // would register the oat file and dex files that come before the broken one. Instead, check all
810 // multidex ahead of time.
OpenDexFilesFromOat(const char * dex_location,const char * oat_location,std::vector<std::string> * error_msgs,std::vector<const DexFile * > * dex_files)811 bool ClassLinker::OpenDexFilesFromOat(const char* dex_location, const char* oat_location,
812                                       std::vector<std::string>* error_msgs,
813                                       std::vector<const DexFile*>* dex_files) {
814   // 1) Check whether we have an open oat file.
815   // This requires a dex checksum, use the "primary" one.
816   uint32_t dex_location_checksum;
817   uint32_t* dex_location_checksum_pointer = &dex_location_checksum;
818   bool have_checksum = true;
819   std::string checksum_error_msg;
820   if (!DexFile::GetChecksum(dex_location, dex_location_checksum_pointer, &checksum_error_msg)) {
821     // This happens for pre-opted files since the corresponding dex files are no longer on disk.
822     dex_location_checksum_pointer = nullptr;
823     have_checksum = false;
824   }
825 
826   bool needs_registering = false;
827 
828   const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFile(oat_location, dex_location,
829                                                                  dex_location_checksum_pointer);
830   std::unique_ptr<const OatFile> open_oat_file(
831       oat_dex_file != nullptr ? oat_dex_file->GetOatFile() : nullptr);
832 
833   // 2) If we do not have an open one, maybe there's one on disk already.
834 
835   // In case the oat file is not open, we play a locking game here so
836   // that if two different processes race to load and register or generate
837   // (or worse, one tries to open a partial generated file) we will be okay.
838   // This is actually common with apps that use DexClassLoader to work
839   // around the dex method reference limit and that have a background
840   // service running in a separate process.
841   ScopedFlock scoped_flock;
842 
843   if (open_oat_file.get() == nullptr) {
844     if (oat_location != nullptr) {
845       // Can only do this if we have a checksum, else error.
846       if (!have_checksum) {
847         error_msgs->push_back(checksum_error_msg);
848         return false;
849       }
850 
851       std::string error_msg;
852 
853       // We are loading or creating one in the future. Time to set up the file lock.
854       if (!scoped_flock.Init(oat_location, &error_msg)) {
855         error_msgs->push_back(error_msg);
856         return false;
857       }
858 
859       // TODO Caller specifically asks for this oat_location. We should honor it. Probably?
860       open_oat_file.reset(FindOatFileInOatLocationForDexFile(dex_location, dex_location_checksum,
861                                                              oat_location, &error_msg));
862 
863       if (open_oat_file.get() == nullptr) {
864         std::string compound_msg = StringPrintf("Failed to find dex file '%s' in oat location '%s': %s",
865                                                 dex_location, oat_location, error_msg.c_str());
866         VLOG(class_linker) << compound_msg;
867         error_msgs->push_back(compound_msg);
868       }
869     } else {
870       // TODO: What to lock here?
871       bool obsolete_file_cleanup_failed;
872       open_oat_file.reset(FindOatFileContainingDexFileFromDexLocation(dex_location,
873                                                                       dex_location_checksum_pointer,
874                                                                       kRuntimeISA, error_msgs,
875                                                                       &obsolete_file_cleanup_failed));
876       // There's no point in going forward and eventually try to regenerate the
877       // file if we couldn't remove the obsolete one. Mostly likely we will fail
878       // with the same error when trying to write the new file.
879       // TODO: should we maybe do this only when we get permission issues? (i.e. EACCESS).
880       if (obsolete_file_cleanup_failed) {
881         return false;
882       }
883     }
884     needs_registering = true;
885   }
886 
887   // 3) If we have an oat file, check all contained multidex files for our dex_location.
888   // Note: LoadMultiDexFilesFromOatFile will check for nullptr in the first argument.
889   bool success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
890                                               dex_location_checksum_pointer,
891                                               false, error_msgs, dex_files);
892   if (success) {
893     const OatFile* oat_file = open_oat_file.release();  // Avoid deleting it.
894     if (needs_registering) {
895       // We opened the oat file, so we must register it.
896       RegisterOatFile(oat_file);
897     }
898     // If the file isn't executable we failed patchoat but did manage to get the dex files.
899     return oat_file->IsExecutable();
900   } else {
901     if (needs_registering) {
902       // We opened it, delete it.
903       open_oat_file.reset();
904     } else {
905       open_oat_file.release();  // Do not delete open oat files.
906     }
907   }
908 
909   // 4) If it's not the case (either no oat file or mismatches), regenerate and load.
910 
911   // Need a checksum, fail else.
912   if (!have_checksum) {
913     error_msgs->push_back(checksum_error_msg);
914     return false;
915   }
916 
917   // Look in cache location if no oat_location is given.
918   std::string cache_location;
919   if (oat_location == nullptr) {
920     // Use the dalvik cache.
921     const std::string dalvik_cache(GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA)));
922     cache_location = GetDalvikCacheFilenameOrDie(dex_location, dalvik_cache.c_str());
923     oat_location = cache_location.c_str();
924   }
925 
926   bool has_flock = true;
927   // Definitely need to lock now.
928   if (!scoped_flock.HasFile()) {
929     std::string error_msg;
930     if (!scoped_flock.Init(oat_location, &error_msg)) {
931       error_msgs->push_back(error_msg);
932       has_flock = false;
933     }
934   }
935 
936   if (Runtime::Current()->IsDex2OatEnabled() && has_flock && scoped_flock.HasFile()) {
937     // Create the oat file.
938     open_oat_file.reset(CreateOatFileForDexLocation(dex_location, scoped_flock.GetFile()->Fd(),
939                                                     oat_location, error_msgs));
940   }
941 
942   // Failed, bail.
943   if (open_oat_file.get() == nullptr) {
944     std::string error_msg;
945     // dex2oat was disabled or crashed. Add the dex file in the list of dex_files to make progress.
946     DexFile::Open(dex_location, dex_location, &error_msg, dex_files);
947     error_msgs->push_back(error_msg);
948     return false;
949   }
950 
951   // Try to load again, but stronger checks.
952   success = LoadMultiDexFilesFromOatFile(open_oat_file.get(), dex_location,
953                                          dex_location_checksum_pointer,
954                                          true, error_msgs, dex_files);
955   if (success) {
956     RegisterOatFile(open_oat_file.release());
957     return true;
958   } else {
959     return false;
960   }
961 }
962 
FindOatFileInOatLocationForDexFile(const char * dex_location,uint32_t dex_location_checksum,const char * oat_location,std::string * error_msg)963 const OatFile* ClassLinker::FindOatFileInOatLocationForDexFile(const char* dex_location,
964                                                                uint32_t dex_location_checksum,
965                                                                const char* oat_location,
966                                                                std::string* error_msg) {
967   std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
968                                             !Runtime::Current()->IsCompiler(),
969                                             error_msg));
970   if (oat_file.get() == nullptr) {
971     *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
972                               error_msg->c_str());
973     return nullptr;
974   }
975   Runtime* runtime = Runtime::Current();
976   const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
977   if (image_space != nullptr) {
978     const ImageHeader& image_header = image_space->GetImageHeader();
979     uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
980     uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
981     if (expected_image_oat_checksum != actual_image_oat_checksum) {
982       *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
983                                 "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
984                                 actual_image_oat_checksum);
985       return nullptr;
986     }
987 
988     uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
989     uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
990     if (expected_image_oat_offset != actual_image_oat_offset) {
991       *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
992                                 PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
993                                 actual_image_oat_offset);
994       return nullptr;
995     }
996     int32_t expected_patch_delta = image_header.GetPatchDelta();
997     int32_t actual_patch_delta = oat_file->GetOatHeader().GetImagePatchDelta();
998     if (expected_patch_delta != actual_patch_delta) {
999       *error_msg = StringPrintf("Failed to find oat file at '%s' with expected patch delta %d, "
1000                                 " found %d", oat_location, expected_patch_delta, actual_patch_delta);
1001       return nullptr;
1002     }
1003   }
1004 
1005   const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1006                                                                     &dex_location_checksum);
1007   if (oat_dex_file == nullptr) {
1008     *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
1009                               dex_location);
1010     return nullptr;
1011   }
1012   uint32_t expected_dex_checksum = dex_location_checksum;
1013   uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
1014   if (expected_dex_checksum != actual_dex_checksum) {
1015     *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
1016                               "found 0x%x", oat_location, expected_dex_checksum,
1017                               actual_dex_checksum);
1018     return nullptr;
1019   }
1020   std::unique_ptr<const DexFile> dex_file(oat_dex_file->OpenDexFile(error_msg));
1021   if (dex_file.get() != nullptr) {
1022     return oat_file.release();
1023   } else {
1024     return nullptr;
1025   }
1026 }
1027 
CreateOatFileForDexLocation(const char * dex_location,int fd,const char * oat_location,std::vector<std::string> * error_msgs)1028 const OatFile* ClassLinker::CreateOatFileForDexLocation(const char* dex_location,
1029                                                         int fd, const char* oat_location,
1030                                                         std::vector<std::string>* error_msgs) {
1031   // Generate the output oat file for the dex file
1032   VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
1033   std::string error_msg;
1034   if (!GenerateOatFile(dex_location, fd, oat_location, &error_msg)) {
1035     CHECK(!error_msg.empty());
1036     error_msgs->push_back(error_msg);
1037     return nullptr;
1038   }
1039   std::unique_ptr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, nullptr,
1040                                             !Runtime::Current()->IsCompiler(),
1041                                             &error_msg));
1042   if (oat_file.get() == nullptr) {
1043     std::string compound_msg = StringPrintf("\nFailed to open generated oat file '%s': %s",
1044                                             oat_location, error_msg.c_str());
1045     error_msgs->push_back(compound_msg);
1046     return nullptr;
1047   }
1048 
1049   return oat_file.release();
1050 }
1051 
VerifyOatImageChecksum(const OatFile * oat_file,const InstructionSet instruction_set)1052 bool ClassLinker::VerifyOatImageChecksum(const OatFile* oat_file,
1053                                          const InstructionSet instruction_set) {
1054   Runtime* runtime = Runtime::Current();
1055   const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1056   if (image_space == nullptr) {
1057     return false;
1058   }
1059   uint32_t image_oat_checksum = 0;
1060   if (instruction_set == kRuntimeISA) {
1061     const ImageHeader& image_header = image_space->GetImageHeader();
1062     image_oat_checksum = image_header.GetOatChecksum();
1063   } else {
1064     std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1065         image_space->GetImageLocation().c_str(), instruction_set));
1066     image_oat_checksum = image_header->GetOatChecksum();
1067   }
1068   return oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum;
1069 }
1070 
VerifyOatChecksums(const OatFile * oat_file,const InstructionSet instruction_set,std::string * error_msg)1071 bool ClassLinker::VerifyOatChecksums(const OatFile* oat_file,
1072                                      const InstructionSet instruction_set,
1073                                      std::string* error_msg) {
1074   Runtime* runtime = Runtime::Current();
1075   const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1076   if (image_space == nullptr) {
1077     *error_msg = "No image space for verification against";
1078     return false;
1079   }
1080 
1081   // If the requested instruction set is the same as the current runtime,
1082   // we can use the checksums directly. If it isn't, we'll have to read the
1083   // image header from the image for the right instruction set.
1084   uint32_t image_oat_checksum = 0;
1085   uintptr_t image_oat_data_begin = 0;
1086   int32_t image_patch_delta = 0;
1087   if (instruction_set == runtime->GetInstructionSet()) {
1088     const ImageHeader& image_header = image_space->GetImageHeader();
1089     image_oat_checksum = image_header.GetOatChecksum();
1090     image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
1091     image_patch_delta = image_header.GetPatchDelta();
1092   } else {
1093     std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1094         image_space->GetImageLocation().c_str(), instruction_set));
1095     image_oat_checksum = image_header->GetOatChecksum();
1096     image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
1097     image_patch_delta = image_header->GetPatchDelta();
1098   }
1099   const OatHeader& oat_header = oat_file->GetOatHeader();
1100   bool ret = ((oat_header.GetImageFileLocationOatChecksum() == image_oat_checksum)
1101               && (oat_header.GetImagePatchDelta() == image_patch_delta)
1102               && (oat_header.GetImageFileLocationOatDataBegin() == image_oat_data_begin));
1103   if (!ret) {
1104     *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d, %d) with (0x%x, %" PRIdPTR ", %d)",
1105                               oat_file->GetLocation().c_str(),
1106                               oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
1107                               oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
1108                               oat_file->GetOatHeader().GetImagePatchDelta(),
1109                               image_oat_checksum, image_oat_data_begin, image_patch_delta);
1110   }
1111   return ret;
1112 }
1113 
VerifyOatAndDexFileChecksums(const OatFile * oat_file,const char * dex_location,uint32_t dex_location_checksum,const InstructionSet instruction_set,std::string * error_msg)1114 bool ClassLinker::VerifyOatAndDexFileChecksums(const OatFile* oat_file,
1115                                                const char* dex_location,
1116                                                uint32_t dex_location_checksum,
1117                                                const InstructionSet instruction_set,
1118                                                std::string* error_msg) {
1119   if (!VerifyOatChecksums(oat_file, instruction_set, error_msg)) {
1120     return false;
1121   }
1122 
1123   const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
1124                                                                     &dex_location_checksum);
1125   if (oat_dex_file == nullptr) {
1126     *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
1127                               oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
1128     for (const OatFile::OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
1129       *error_msg  += StringPrintf("\noat file '%s' contains contents for '%s' with checksum 0x%x",
1130                                   oat_file->GetLocation().c_str(),
1131                                   oat_dex_file->GetDexFileLocation().c_str(),
1132                                   oat_dex_file->GetDexFileLocationChecksum());
1133     }
1134     return false;
1135   }
1136 
1137   if (dex_location_checksum != oat_dex_file->GetDexFileLocationChecksum()) {
1138     *error_msg = StringPrintf("oat file '%s' mismatch (0x%x) with '%s' (0x%x)",
1139                               oat_file->GetLocation().c_str(),
1140                               oat_dex_file->GetDexFileLocationChecksum(),
1141                               dex_location, dex_location_checksum);
1142     return false;
1143   }
1144   return true;
1145 }
1146 
VerifyOatWithDexFile(const OatFile * oat_file,const char * dex_location,const uint32_t * dex_location_checksum,std::string * error_msg)1147 bool ClassLinker::VerifyOatWithDexFile(const OatFile* oat_file,
1148                                        const char* dex_location,
1149                                        const uint32_t* dex_location_checksum,
1150                                        std::string* error_msg) {
1151   CHECK(oat_file != nullptr);
1152   CHECK(dex_location != nullptr);
1153   std::unique_ptr<const DexFile> dex_file;
1154   if (dex_location_checksum == nullptr) {
1155     // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
1156     // up-to-date. This is the common case in user builds for jar's and apk's in the /system
1157     // directory.
1158     const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, nullptr);
1159     if (oat_dex_file == nullptr) {
1160       *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
1161                                 "dex file '%s': %s", oat_file->GetLocation().c_str(), dex_location,
1162                                 error_msg->c_str());
1163       return false;
1164     }
1165     dex_file.reset(oat_dex_file->OpenDexFile(error_msg));
1166   } else {
1167     bool verified = VerifyOatAndDexFileChecksums(oat_file, dex_location, *dex_location_checksum,
1168                                                  kRuntimeISA, error_msg);
1169     if (!verified) {
1170       return false;
1171     }
1172     dex_file.reset(oat_file->GetOatDexFile(dex_location,
1173                                            dex_location_checksum)->OpenDexFile(error_msg));
1174   }
1175   return dex_file.get() != nullptr;
1176 }
1177 
FindOatFileContainingDexFileFromDexLocation(const char * dex_location,const uint32_t * dex_location_checksum,InstructionSet isa,std::vector<std::string> * error_msgs,bool * obsolete_file_cleanup_failed)1178 const OatFile* ClassLinker::FindOatFileContainingDexFileFromDexLocation(
1179     const char* dex_location,
1180     const uint32_t* dex_location_checksum,
1181     InstructionSet isa,
1182     std::vector<std::string>* error_msgs,
1183     bool* obsolete_file_cleanup_failed) {
1184   *obsolete_file_cleanup_failed = false;
1185   bool already_opened = false;
1186   std::string dex_location_str(dex_location);
1187   std::unique_ptr<const OatFile> oat_file(OpenOatFileFromDexLocation(dex_location_str, isa,
1188                                                                      &already_opened,
1189                                                                      obsolete_file_cleanup_failed,
1190                                                                      error_msgs));
1191   std::string error_msg;
1192   if (oat_file.get() == nullptr) {
1193     error_msgs->push_back(StringPrintf("Failed to open oat file from dex location '%s'",
1194                                        dex_location));
1195     return nullptr;
1196   } else if (oat_file->IsExecutable() &&
1197              !VerifyOatWithDexFile(oat_file.get(), dex_location,
1198                                    dex_location_checksum, &error_msg)) {
1199     error_msgs->push_back(StringPrintf("Failed to verify oat file '%s' found for dex location "
1200                                        "'%s': %s", oat_file->GetLocation().c_str(), dex_location,
1201                                        error_msg.c_str()));
1202     return nullptr;
1203   } else if (!oat_file->IsExecutable() &&
1204              Runtime::Current()->GetHeap()->HasImageSpace() &&
1205              !VerifyOatImageChecksum(oat_file.get(), isa)) {
1206     error_msgs->push_back(StringPrintf("Failed to verify non-executable oat file '%s' found for "
1207                                        "dex location '%s'. Image checksum incorrect.",
1208                                        oat_file->GetLocation().c_str(), dex_location));
1209     return nullptr;
1210   } else {
1211     return oat_file.release();
1212   }
1213 }
1214 
FindOpenedOatFileFromOatLocation(const std::string & oat_location)1215 const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
1216   ReaderMutexLock mu(Thread::Current(), dex_lock_);
1217   for (size_t i = 0; i < oat_files_.size(); i++) {
1218     const OatFile* oat_file = oat_files_[i];
1219     DCHECK(oat_file != nullptr);
1220     if (oat_file->GetLocation() == oat_location) {
1221       return oat_file;
1222     }
1223   }
1224   return nullptr;
1225 }
1226 
OpenOatFileFromDexLocation(const std::string & dex_location,InstructionSet isa,bool * already_opened,bool * obsolete_file_cleanup_failed,std::vector<std::string> * error_msgs)1227 const OatFile* ClassLinker::OpenOatFileFromDexLocation(const std::string& dex_location,
1228                                                        InstructionSet isa,
1229                                                        bool *already_opened,
1230                                                        bool *obsolete_file_cleanup_failed,
1231                                                        std::vector<std::string>* error_msgs) {
1232   // Find out if we've already opened the file
1233   const OatFile* ret = nullptr;
1234   std::string odex_filename(DexFilenameToOdexFilename(dex_location, isa));
1235   ret = FindOpenedOatFileFromOatLocation(odex_filename);
1236   if (ret != nullptr) {
1237     *already_opened = true;
1238     return ret;
1239   }
1240 
1241   std::string dalvik_cache;
1242   bool have_android_data = false;
1243   bool have_dalvik_cache = false;
1244   bool is_global_cache = false;
1245   GetDalvikCache(GetInstructionSetString(kRuntimeISA), false, &dalvik_cache,
1246                  &have_android_data, &have_dalvik_cache, &is_global_cache);
1247   std::string cache_filename;
1248   if (have_dalvik_cache) {
1249     cache_filename = GetDalvikCacheFilenameOrDie(dex_location.c_str(), dalvik_cache.c_str());
1250     ret = FindOpenedOatFileFromOatLocation(cache_filename);
1251     if (ret != nullptr) {
1252       *already_opened = true;
1253       return ret;
1254     }
1255   } else {
1256     // If we need to relocate we should just place odex back where it started.
1257     cache_filename = odex_filename;
1258   }
1259 
1260   ret = nullptr;
1261 
1262   // We know that neither the odex nor the cache'd version is already in use, if it even exists.
1263   //
1264   // Now we do the following:
1265   // 1) Try and open the odex version
1266   // 2) If present, checksum-verified & relocated correctly return it
1267   // 3) Close the odex version to free up its address space.
1268   // 4) Try and open the cache version
1269   // 5) If present, checksum-verified & relocated correctly return it
1270   // 6) Close the cache version to free up its address space.
1271   // 7) If we should relocate:
1272   //   a) If we have opened and checksum-verified the odex version relocate it to
1273   //      'cache_filename' and return it
1274   //   b) If we have opened and checksum-verified the cache version relocate it in place and return
1275   //      it. This should not happen often (I think only the run-test's will hit this case).
1276   // 8) If the cache-version was present we should delete it since it must be obsolete if we get to
1277   //    this point.
1278   // 9) Return nullptr
1279 
1280   *already_opened = false;
1281   const Runtime* runtime = Runtime::Current();
1282   CHECK(runtime != nullptr);
1283   bool executable = !runtime->IsCompiler();
1284 
1285   std::string odex_error_msg;
1286   bool should_patch_system = false;
1287   bool odex_checksum_verified = false;
1288   bool have_system_odex = false;
1289   {
1290     // There is a high probability that these both these oat files map similar/the same address
1291     // spaces so we must scope them like this so they each gets its turn.
1292     std::unique_ptr<OatFile> odex_oat_file(OatFile::Open(odex_filename, odex_filename, nullptr,
1293                                                          executable, &odex_error_msg));
1294     if (odex_oat_file.get() != nullptr && CheckOatFile(odex_oat_file.get(), isa,
1295                                                        &odex_checksum_verified,
1296                                                        &odex_error_msg)) {
1297       error_msgs->push_back(odex_error_msg);
1298       return odex_oat_file.release();
1299     } else {
1300       if (odex_checksum_verified) {
1301         // We can just relocate
1302         should_patch_system = true;
1303         odex_error_msg = "Image Patches are incorrect";
1304       }
1305       if (odex_oat_file.get() != nullptr) {
1306         have_system_odex = true;
1307       }
1308     }
1309   }
1310 
1311   std::string cache_error_msg;
1312   bool should_patch_cache = false;
1313   bool cache_checksum_verified = false;
1314   if (have_dalvik_cache) {
1315     std::unique_ptr<OatFile> cache_oat_file(OatFile::Open(cache_filename, cache_filename, nullptr,
1316                                                           executable, &cache_error_msg));
1317     if (cache_oat_file.get() != nullptr && CheckOatFile(cache_oat_file.get(), isa,
1318                                                         &cache_checksum_verified,
1319                                                         &cache_error_msg)) {
1320       error_msgs->push_back(cache_error_msg);
1321       return cache_oat_file.release();
1322     } else if (cache_checksum_verified) {
1323       // We can just relocate
1324       should_patch_cache = true;
1325       cache_error_msg = "Image Patches are incorrect";
1326     }
1327   } else if (have_android_data) {
1328     // dalvik_cache does not exist but android data does. This means we should be able to create
1329     // it, so we should try.
1330     GetDalvikCacheOrDie(GetInstructionSetString(kRuntimeISA), true);
1331   }
1332 
1333   ret = nullptr;
1334   std::string error_msg;
1335   if (runtime->CanRelocate()) {
1336     // Run relocation
1337     gc::space::ImageSpace* space = Runtime::Current()->GetHeap()->GetImageSpace();
1338     if (space != nullptr) {
1339       const std::string& image_location = space->GetImageLocation();
1340       if (odex_checksum_verified && should_patch_system) {
1341         ret = PatchAndRetrieveOat(odex_filename, cache_filename, image_location, isa, &error_msg);
1342       } else if (cache_checksum_verified && should_patch_cache) {
1343         CHECK(have_dalvik_cache);
1344         ret = PatchAndRetrieveOat(cache_filename, cache_filename, image_location, isa, &error_msg);
1345       }
1346     } else if (have_system_odex) {
1347       ret = GetInterpretedOnlyOat(odex_filename, isa, &error_msg);
1348     }
1349   }
1350   if (ret == nullptr && have_dalvik_cache && OS::FileExists(cache_filename.c_str())) {
1351     // implicitly: were able to fine where the cached version is but we were unable to use it,
1352     // either as a destination for relocation or to open a file. We should delete it if it is
1353     // there.
1354     if (TEMP_FAILURE_RETRY(unlink(cache_filename.c_str())) != 0) {
1355       std::string rm_error_msg = StringPrintf("Failed to remove obsolete file from %s when "
1356                                               "searching for dex file %s: %s",
1357                                               cache_filename.c_str(), dex_location.c_str(),
1358                                               strerror(errno));
1359       error_msgs->push_back(rm_error_msg);
1360       VLOG(class_linker) << rm_error_msg;
1361       // Let the caller know that we couldn't remove the obsolete file.
1362       // This is a good indication that further writes may fail as well.
1363       *obsolete_file_cleanup_failed = true;
1364     }
1365   }
1366   if (ret == nullptr) {
1367     VLOG(class_linker) << error_msg;
1368     error_msgs->push_back(error_msg);
1369     std::string relocation_msg;
1370     if (runtime->CanRelocate()) {
1371       relocation_msg = StringPrintf(" and relocation failed");
1372     }
1373     if (have_dalvik_cache && cache_checksum_verified) {
1374       error_msg = StringPrintf("Failed to open oat file from %s (error %s) or %s "
1375                                 "(error %s)%s.", odex_filename.c_str(), odex_error_msg.c_str(),
1376                                 cache_filename.c_str(), cache_error_msg.c_str(),
1377                                 relocation_msg.c_str());
1378     } else {
1379       error_msg = StringPrintf("Failed to open oat file from %s (error %s) (no "
1380                                "dalvik_cache availible)%s.", odex_filename.c_str(),
1381                                odex_error_msg.c_str(), relocation_msg.c_str());
1382     }
1383     VLOG(class_linker) << error_msg;
1384     error_msgs->push_back(error_msg);
1385   }
1386   return ret;
1387 }
1388 
GetInterpretedOnlyOat(const std::string & oat_path,InstructionSet isa,std::string * error_msg)1389 const OatFile* ClassLinker::GetInterpretedOnlyOat(const std::string& oat_path,
1390                                                   InstructionSet isa,
1391                                                   std::string* error_msg) {
1392   // We open it non-executable
1393   std::unique_ptr<OatFile> output(OatFile::Open(oat_path, oat_path, nullptr, false, error_msg));
1394   if (output.get() == nullptr) {
1395     return nullptr;
1396   }
1397   if (!Runtime::Current()->GetHeap()->HasImageSpace() ||
1398       VerifyOatImageChecksum(output.get(), isa)) {
1399     return output.release();
1400   } else {
1401     *error_msg = StringPrintf("Could not use oat file '%s', image checksum failed to verify.",
1402                               oat_path.c_str());
1403     return nullptr;
1404   }
1405 }
1406 
PatchAndRetrieveOat(const std::string & input_oat,const std::string & output_oat,const std::string & image_location,InstructionSet isa,std::string * error_msg)1407 const OatFile* ClassLinker::PatchAndRetrieveOat(const std::string& input_oat,
1408                                                 const std::string& output_oat,
1409                                                 const std::string& image_location,
1410                                                 InstructionSet isa,
1411                                                 std::string* error_msg) {
1412   if (!Runtime::Current()->GetHeap()->HasImageSpace()) {
1413     // We don't have an image space so there is no point in trying to patchoat.
1414     LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted because we are "
1415                  << "running without an image. Attempting to use oat file for interpretation.";
1416     return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1417   }
1418   if (!Runtime::Current()->IsDex2OatEnabled()) {
1419     // We don't have dex2oat so we can assume we don't have patchoat either. We should just use the
1420     // input_oat but make sure we only do interpretation on it's dex files.
1421     LOG(WARNING) << "Patching of oat file '" << input_oat << "' not attempted due to dex2oat being "
1422                  << "disabled. Attempting to use oat file for interpretation";
1423     return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1424   }
1425   Locks::mutator_lock_->AssertNotHeld(Thread::Current());  // Avoid starving GC.
1426   std::string patchoat(Runtime::Current()->GetPatchoatExecutable());
1427 
1428   std::string isa_arg("--instruction-set=");
1429   isa_arg += GetInstructionSetString(isa);
1430   std::string input_oat_filename_arg("--input-oat-file=");
1431   input_oat_filename_arg += input_oat;
1432   std::string output_oat_filename_arg("--output-oat-file=");
1433   output_oat_filename_arg += output_oat;
1434   std::string patched_image_arg("--patched-image-location=");
1435   patched_image_arg += image_location;
1436 
1437   std::vector<std::string> argv;
1438   argv.push_back(patchoat);
1439   argv.push_back(isa_arg);
1440   argv.push_back(input_oat_filename_arg);
1441   argv.push_back(output_oat_filename_arg);
1442   argv.push_back(patched_image_arg);
1443 
1444   std::string command_line(Join(argv, ' '));
1445   LOG(INFO) << "Relocate Oat File: " << command_line;
1446   bool success = Exec(argv, error_msg);
1447   if (success) {
1448     std::unique_ptr<OatFile> output(OatFile::Open(output_oat, output_oat, nullptr,
1449                                                   !Runtime::Current()->IsCompiler(), error_msg));
1450     bool checksum_verified = false;
1451     if (output.get() != nullptr && CheckOatFile(output.get(), isa, &checksum_verified, error_msg)) {
1452       return output.release();
1453     } else if (output.get() != nullptr) {
1454       *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1455                                 "but output file '%s' failed verifcation: %s",
1456                                 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1457     } else {
1458       *error_msg = StringPrintf("Patching of oat file '%s' succeeded "
1459                                 "but was unable to open output file '%s': %s",
1460                                 input_oat.c_str(), output_oat.c_str(), error_msg->c_str());
1461     }
1462   } else if (!Runtime::Current()->IsCompiler()) {
1463     // patchoat failed which means we probably don't have enough room to place the output oat file,
1464     // instead of failing we should just run the interpreter from the dex files in the input oat.
1465     LOG(WARNING) << "Patching of oat file '" << input_oat << "' failed. Attempting to use oat file "
1466                  << "for interpretation. patchoat failure was: " << *error_msg;
1467     return GetInterpretedOnlyOat(input_oat, isa, error_msg);
1468   } else {
1469     *error_msg = StringPrintf("Patching of oat file '%s to '%s' "
1470                               "failed: %s", input_oat.c_str(), output_oat.c_str(),
1471                               error_msg->c_str());
1472   }
1473   return nullptr;
1474 }
1475 
GetRequiredDelta(const OatFile * oat_file,InstructionSet isa)1476 int32_t ClassLinker::GetRequiredDelta(const OatFile* oat_file, InstructionSet isa) {
1477   Runtime* runtime = Runtime::Current();
1478   int32_t real_patch_delta;
1479   const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1480   CHECK(image_space != nullptr);
1481   if (isa == Runtime::Current()->GetInstructionSet()) {
1482     const ImageHeader& image_header = image_space->GetImageHeader();
1483     real_patch_delta = image_header.GetPatchDelta();
1484   } else {
1485     std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1486         image_space->GetImageLocation().c_str(), isa));
1487     real_patch_delta = image_header->GetPatchDelta();
1488   }
1489   const OatHeader& oat_header = oat_file->GetOatHeader();
1490   return real_patch_delta - oat_header.GetImagePatchDelta();
1491 }
1492 
CheckOatFile(const OatFile * oat_file,InstructionSet isa,bool * checksum_verified,std::string * error_msg)1493 bool ClassLinker::CheckOatFile(const OatFile* oat_file, InstructionSet isa,
1494                                bool* checksum_verified,
1495                                std::string* error_msg) {
1496   std::string compound_msg("Oat file failed to verify: ");
1497   Runtime* runtime = Runtime::Current();
1498   uint32_t real_image_checksum;
1499   void* real_image_oat_offset;
1500   int32_t real_patch_delta;
1501   const gc::space::ImageSpace* image_space = runtime->GetHeap()->GetImageSpace();
1502   if (image_space == nullptr) {
1503     *error_msg = "No image space present";
1504     return false;
1505   }
1506   if (isa == Runtime::Current()->GetInstructionSet()) {
1507     const ImageHeader& image_header = image_space->GetImageHeader();
1508     real_image_checksum = image_header.GetOatChecksum();
1509     real_image_oat_offset = image_header.GetOatDataBegin();
1510     real_patch_delta = image_header.GetPatchDelta();
1511   } else {
1512     std::unique_ptr<ImageHeader> image_header(gc::space::ImageSpace::ReadImageHeaderOrDie(
1513         image_space->GetImageLocation().c_str(), isa));
1514     real_image_checksum = image_header->GetOatChecksum();
1515     real_image_oat_offset = image_header->GetOatDataBegin();
1516     real_patch_delta = image_header->GetPatchDelta();
1517   }
1518 
1519   const OatHeader& oat_header = oat_file->GetOatHeader();
1520 
1521   uint32_t oat_image_checksum = oat_header.GetImageFileLocationOatChecksum();
1522   *checksum_verified = oat_image_checksum == real_image_checksum;
1523   if (!*checksum_verified) {
1524     compound_msg += StringPrintf(" Oat Image Checksum Incorrect (expected 0x%x, recieved 0x%x)",
1525                                  real_image_checksum, oat_image_checksum);
1526   }
1527 
1528   void* oat_image_oat_offset =
1529       reinterpret_cast<void*>(oat_header.GetImageFileLocationOatDataBegin());
1530   bool offset_verified = oat_image_oat_offset == real_image_oat_offset;
1531   if (!offset_verified) {
1532     compound_msg += StringPrintf(" Oat Image oat offset incorrect (expected 0x%p, recieved 0x%p)",
1533                                  real_image_oat_offset, oat_image_oat_offset);
1534   }
1535 
1536   int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
1537   bool patch_delta_verified = oat_patch_delta == real_patch_delta;
1538   if (!patch_delta_verified) {
1539     compound_msg += StringPrintf(" Oat image patch delta incorrect (expected 0x%x, recieved 0x%x)",
1540                                  real_patch_delta, oat_patch_delta);
1541   }
1542 
1543   bool ret = (*checksum_verified && offset_verified && patch_delta_verified);
1544   if (ret) {
1545     *error_msg = compound_msg;
1546   }
1547   return ret;
1548 }
1549 
FindOatFileFromOatLocation(const std::string & oat_location,std::string * error_msg)1550 const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1551                                                        std::string* error_msg) {
1552   const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
1553   if (oat_file != nullptr) {
1554     return oat_file;
1555   }
1556 
1557   return OatFile::Open(oat_location, oat_location, nullptr, !Runtime::Current()->IsCompiler(),
1558                        error_msg);
1559 }
1560 
InitFromImageInterpretOnlyCallback(mirror::Object * obj,void * arg)1561 static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
1562     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1563   ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1564 
1565   DCHECK(obj != nullptr);
1566   DCHECK(class_linker != nullptr);
1567 
1568   if (obj->IsArtMethod()) {
1569     mirror::ArtMethod* method = obj->AsArtMethod();
1570     if (!method->IsNative()) {
1571       method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1572       if (method != Runtime::Current()->GetResolutionMethod()) {
1573         method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1574 #if defined(ART_USE_PORTABLE_COMPILER)
1575         method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
1576 #endif
1577       }
1578     }
1579   }
1580 }
1581 
InitFromImage()1582 void ClassLinker::InitFromImage() {
1583   VLOG(startup) << "ClassLinker::InitFromImage entering";
1584   CHECK(!init_done_);
1585 
1586   Thread* self = Thread::Current();
1587   gc::Heap* heap = Runtime::Current()->GetHeap();
1588   gc::space::ImageSpace* space = heap->GetImageSpace();
1589   dex_cache_image_class_lookup_required_ = true;
1590   CHECK(space != nullptr);
1591   OatFile& oat_file = GetImageOatFile(space);
1592   CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1593   CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
1594   const char* image_file_location = oat_file.GetOatHeader().
1595       GetStoreValueByKey(OatHeader::kImageLocationKey);
1596   CHECK(image_file_location == nullptr || *image_file_location == 0);
1597   portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1598   quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
1599   portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1600   quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
1601   quick_generic_jni_trampoline_ = oat_file.GetOatHeader().GetQuickGenericJniTrampoline();
1602   quick_to_interpreter_bridge_trampoline_ = oat_file.GetOatHeader().GetQuickToInterpreterBridge();
1603   mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1604   mirror::ObjectArray<mirror::DexCache>* dex_caches =
1605       dex_caches_object->AsObjectArray<mirror::DexCache>();
1606 
1607   StackHandleScope<1> hs(self);
1608   Handle<mirror::ObjectArray<mirror::Class>> class_roots(hs.NewHandle(
1609           space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->
1610           AsObjectArray<mirror::Class>()));
1611   class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
1612 
1613   // Special case of setting up the String class early so that we can test arbitrary objects
1614   // as being Strings or not
1615   mirror::String::SetClass(GetClassRoot(kJavaLangString));
1616 
1617   CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
1618            static_cast<uint32_t>(dex_caches->GetLength()));
1619   for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1620     StackHandleScope<1> hs(self);
1621     Handle<mirror::DexCache> dex_cache(hs.NewHandle(dex_caches->Get(i)));
1622     const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1623     const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1624                                                                      nullptr);
1625     CHECK(oat_dex_file != nullptr) << oat_file.GetLocation() << " " << dex_file_location;
1626     std::string error_msg;
1627     const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
1628     if (dex_file == nullptr) {
1629       LOG(FATAL) << "Failed to open dex file " << dex_file_location
1630                  << " from within oat file " << oat_file.GetLocation()
1631                  << " error '" << error_msg << "'";
1632     }
1633 
1634     CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1635 
1636     AppendToBootClassPath(*dex_file, dex_cache);
1637   }
1638 
1639   // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1640   // bitmap walk.
1641   mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
1642 
1643   // Set entry point to interpreter if in InterpretOnly mode.
1644   if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
1645     ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1646     heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
1647   }
1648 
1649   // reinit class_roots_
1650   mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
1651   class_roots_ = GcRoot<mirror::ObjectArray<mirror::Class>>(class_roots.Get());
1652 
1653   // reinit array_iftable_ from any array class instance, they should be ==
1654   array_iftable_ = GcRoot<mirror::IfTable>(GetClassRoot(kObjectArrayClass)->GetIfTable());
1655   DCHECK(array_iftable_.Read() == GetClassRoot(kBooleanArrayClass)->GetIfTable());
1656   // String class root was set above
1657   mirror::Reference::SetClass(GetClassRoot(kJavaLangRefReference));
1658   mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
1659   mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1660   mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1661   mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1662   mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1663   mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1664   mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1665   mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1666   mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1667   mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1668   mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
1669 
1670   FinishInit(self);
1671 
1672   VLOG(startup) << "ClassLinker::InitFromImage exiting";
1673 }
1674 
VisitClassRoots(RootCallback * callback,void * arg,VisitRootFlags flags)1675 void ClassLinker::VisitClassRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1676   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1677   if ((flags & kVisitRootFlagAllRoots) != 0) {
1678     for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1679       it.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1680     }
1681   } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1682     for (auto& pair : new_class_roots_) {
1683       mirror::Class* old_ref = pair.second.Read<kWithoutReadBarrier>();
1684       pair.second.VisitRoot(callback, arg, 0, kRootStickyClass);
1685       mirror::Class* new_ref = pair.second.Read<kWithoutReadBarrier>();
1686       if (UNLIKELY(new_ref != old_ref)) {
1687         // Uh ohes, GC moved a root in the log. Need to search the class_table and update the
1688         // corresponding object. This is slow, but luckily for us, this may only happen with a
1689         // concurrent moving GC.
1690         for (auto it = class_table_.lower_bound(pair.first), end = class_table_.end();
1691             it != end && it->first == pair.first; ++it) {
1692           // If the class stored matches the old class, update it to the new value.
1693           if (old_ref == it->second.Read<kWithoutReadBarrier>()) {
1694             it->second = GcRoot<mirror::Class>(new_ref);
1695           }
1696         }
1697       }
1698     }
1699   }
1700   if ((flags & kVisitRootFlagClearRootLog) != 0) {
1701     new_class_roots_.clear();
1702   }
1703   if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1704     log_new_class_table_roots_ = true;
1705   } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1706     log_new_class_table_roots_ = false;
1707   }
1708   // We deliberately ignore the class roots in the image since we
1709   // handle image roots by using the MS/CMS rescanning of dirty cards.
1710 }
1711 
1712 // Keep in sync with InitCallback. Anything we visit, we need to
1713 // reinit references to when reinitializing a ClassLinker from a
1714 // mapped image.
VisitRoots(RootCallback * callback,void * arg,VisitRootFlags flags)1715 void ClassLinker::VisitRoots(RootCallback* callback, void* arg, VisitRootFlags flags) {
1716   class_roots_.VisitRoot(callback, arg, 0, kRootVMInternal);
1717   Thread* self = Thread::Current();
1718   {
1719     ReaderMutexLock mu(self, dex_lock_);
1720     if ((flags & kVisitRootFlagAllRoots) != 0) {
1721       for (GcRoot<mirror::DexCache>& dex_cache : dex_caches_) {
1722         dex_cache.VisitRoot(callback, arg, 0, kRootVMInternal);
1723       }
1724     } else if ((flags & kVisitRootFlagNewRoots) != 0) {
1725       for (size_t index : new_dex_cache_roots_) {
1726         dex_caches_[index].VisitRoot(callback, arg, 0, kRootVMInternal);
1727       }
1728     }
1729     if ((flags & kVisitRootFlagClearRootLog) != 0) {
1730       new_dex_cache_roots_.clear();
1731     }
1732     if ((flags & kVisitRootFlagStartLoggingNewRoots) != 0) {
1733       log_new_dex_caches_roots_ = true;
1734     } else if ((flags & kVisitRootFlagStopLoggingNewRoots) != 0) {
1735       log_new_dex_caches_roots_ = false;
1736     }
1737   }
1738   VisitClassRoots(callback, arg, flags);
1739   array_iftable_.VisitRoot(callback, arg, 0, kRootVMInternal);
1740   DCHECK(!array_iftable_.IsNull());
1741   for (size_t i = 0; i < kFindArrayCacheSize; ++i) {
1742     if (!find_array_class_cache_[i].IsNull()) {
1743       find_array_class_cache_[i].VisitRoot(callback, arg, 0, kRootVMInternal);
1744     }
1745   }
1746 }
1747 
VisitClasses(ClassVisitor * visitor,void * arg)1748 void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1749   if (dex_cache_image_class_lookup_required_) {
1750     MoveImageClassesToClassTable();
1751   }
1752   // TODO: why isn't this a ReaderMutexLock?
1753   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1754   for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
1755     mirror::Class* c = it.second.Read();
1756     if (!visitor(c, arg)) {
1757       return;
1758     }
1759   }
1760 }
1761 
GetClassesVisitorSet(mirror::Class * c,void * arg)1762 static bool GetClassesVisitorSet(mirror::Class* c, void* arg) {
1763   std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
1764   classes->insert(c);
1765   return true;
1766 }
1767 
1768 struct GetClassesVisitorArrayArg {
1769   Handle<mirror::ObjectArray<mirror::Class>>* classes;
1770   int32_t index;
1771   bool success;
1772 };
1773 
GetClassesVisitorArray(mirror::Class * c,void * varg)1774 static bool GetClassesVisitorArray(mirror::Class* c, void* varg)
1775     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1776   GetClassesVisitorArrayArg* arg = reinterpret_cast<GetClassesVisitorArrayArg*>(varg);
1777   if (arg->index < (*arg->classes)->GetLength()) {
1778     (*arg->classes)->Set(arg->index, c);
1779     arg->index++;
1780     return true;
1781   } else {
1782     arg->success = false;
1783     return false;
1784   }
1785 }
1786 
VisitClassesWithoutClassesLock(ClassVisitor * visitor,void * arg)1787 void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
1788   // TODO: it may be possible to avoid secondary storage if we iterate over dex caches. The problem
1789   // is avoiding duplicates.
1790   if (!kMovingClasses) {
1791     std::set<mirror::Class*> classes;
1792     VisitClasses(GetClassesVisitorSet, &classes);
1793     for (mirror::Class* klass : classes) {
1794       if (!visitor(klass, arg)) {
1795         return;
1796       }
1797     }
1798   } else {
1799     Thread* self = Thread::Current();
1800     StackHandleScope<1> hs(self);
1801     Handle<mirror::ObjectArray<mirror::Class>> classes =
1802         hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
1803     GetClassesVisitorArrayArg local_arg;
1804     local_arg.classes = &classes;
1805     local_arg.success = false;
1806     // We size the array assuming classes won't be added to the class table during the visit.
1807     // If this assumption fails we iterate again.
1808     while (!local_arg.success) {
1809       size_t class_table_size;
1810       {
1811         ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1812         class_table_size = class_table_.size();
1813       }
1814       mirror::Class* class_type = mirror::Class::GetJavaLangClass();
1815       mirror::Class* array_of_class = FindArrayClass(self, &class_type);
1816       classes.Assign(
1817           mirror::ObjectArray<mirror::Class>::Alloc(self, array_of_class, class_table_size));
1818       CHECK(classes.Get() != nullptr);  // OOME.
1819       local_arg.index = 0;
1820       local_arg.success = true;
1821       VisitClasses(GetClassesVisitorArray, &local_arg);
1822     }
1823     for (int32_t i = 0; i < classes->GetLength(); ++i) {
1824       // If the class table shrank during creation of the clases array we expect null elements. If
1825       // the class table grew then the loop repeats. If classes are created after the loop has
1826       // finished then we don't visit.
1827       mirror::Class* klass = classes->Get(i);
1828       if (klass != nullptr && !visitor(klass, arg)) {
1829         return;
1830       }
1831     }
1832   }
1833 }
1834 
~ClassLinker()1835 ClassLinker::~ClassLinker() {
1836   mirror::Class::ResetClass();
1837   mirror::String::ResetClass();
1838   mirror::Reference::ResetClass();
1839   mirror::ArtField::ResetClass();
1840   mirror::ArtMethod::ResetClass();
1841   mirror::BooleanArray::ResetArrayClass();
1842   mirror::ByteArray::ResetArrayClass();
1843   mirror::CharArray::ResetArrayClass();
1844   mirror::DoubleArray::ResetArrayClass();
1845   mirror::FloatArray::ResetArrayClass();
1846   mirror::IntArray::ResetArrayClass();
1847   mirror::LongArray::ResetArrayClass();
1848   mirror::ShortArray::ResetArrayClass();
1849   mirror::Throwable::ResetClass();
1850   mirror::StackTraceElement::ResetClass();
1851   STLDeleteElements(&boot_class_path_);
1852   STLDeleteElements(&oat_files_);
1853 }
1854 
AllocDexCache(Thread * self,const DexFile & dex_file)1855 mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
1856   gc::Heap* heap = Runtime::Current()->GetHeap();
1857   StackHandleScope<16> hs(self);
1858   Handle<mirror::Class> dex_cache_class(hs.NewHandle(GetClassRoot(kJavaLangDexCache)));
1859   Handle<mirror::DexCache> dex_cache(
1860       hs.NewHandle(down_cast<mirror::DexCache*>(
1861           heap->AllocObject<true>(self, dex_cache_class.Get(), dex_cache_class->GetObjectSize(),
1862                                   VoidFunctor()))));
1863   if (dex_cache.Get() == nullptr) {
1864     return nullptr;
1865   }
1866   Handle<mirror::String>
1867       location(hs.NewHandle(intern_table_->InternStrong(dex_file.GetLocation().c_str())));
1868   if (location.Get() == nullptr) {
1869     return nullptr;
1870   }
1871   Handle<mirror::ObjectArray<mirror::String>>
1872       strings(hs.NewHandle(AllocStringArray(self, dex_file.NumStringIds())));
1873   if (strings.Get() == nullptr) {
1874     return nullptr;
1875   }
1876   Handle<mirror::ObjectArray<mirror::Class>>
1877       types(hs.NewHandle(AllocClassArray(self, dex_file.NumTypeIds())));
1878   if (types.Get() == nullptr) {
1879     return nullptr;
1880   }
1881   Handle<mirror::ObjectArray<mirror::ArtMethod>>
1882       methods(hs.NewHandle(AllocArtMethodArray(self, dex_file.NumMethodIds())));
1883   if (methods.Get() == nullptr) {
1884     return nullptr;
1885   }
1886   Handle<mirror::ObjectArray<mirror::ArtField>>
1887       fields(hs.NewHandle(AllocArtFieldArray(self, dex_file.NumFieldIds())));
1888   if (fields.Get() == nullptr) {
1889     return nullptr;
1890   }
1891   dex_cache->Init(&dex_file, location.Get(), strings.Get(), types.Get(), methods.Get(),
1892                   fields.Get());
1893   return dex_cache.Get();
1894 }
1895 
AllocClass(Thread * self,mirror::Class * java_lang_Class,uint32_t class_size)1896 mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
1897                                        uint32_t class_size) {
1898   DCHECK_GE(class_size, sizeof(mirror::Class));
1899   gc::Heap* heap = Runtime::Current()->GetHeap();
1900   mirror::Class::InitializeClassVisitor visitor(class_size);
1901   mirror::Object* k = kMovingClasses ?
1902       heap->AllocObject<true>(self, java_lang_Class, class_size, visitor) :
1903       heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size, visitor);
1904   if (UNLIKELY(k == nullptr)) {
1905     CHECK(self->IsExceptionPending());  // OOME.
1906     return nullptr;
1907   }
1908   return k->AsClass();
1909 }
1910 
AllocClass(Thread * self,uint32_t class_size)1911 mirror::Class* ClassLinker::AllocClass(Thread* self, uint32_t class_size) {
1912   return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
1913 }
1914 
AllocArtField(Thread * self)1915 mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
1916   return down_cast<mirror::ArtField*>(
1917       GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
1918 }
1919 
AllocArtMethod(Thread * self)1920 mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
1921   return down_cast<mirror::ArtMethod*>(
1922       GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
1923 }
1924 
AllocStackTraceElementArray(Thread * self,size_t length)1925 mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1926     Thread* self, size_t length) {
1927   return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1928       self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
1929 }
1930 
EnsureResolved(Thread * self,const char * descriptor,mirror::Class * klass)1931 mirror::Class* ClassLinker::EnsureResolved(Thread* self, const char* descriptor,
1932                                            mirror::Class* klass) {
1933   DCHECK(klass != nullptr);
1934 
1935   // For temporary classes we must wait for them to be retired.
1936   if (init_done_ && klass->IsTemp()) {
1937     CHECK(!klass->IsResolved());
1938     if (klass->IsErroneous()) {
1939       ThrowEarlierClassFailure(klass);
1940       return nullptr;
1941     }
1942     StackHandleScope<1> hs(self);
1943     Handle<mirror::Class> h_class(hs.NewHandle(klass));
1944     ObjectLock<mirror::Class> lock(self, h_class);
1945     // Loop and wait for the resolving thread to retire this class.
1946     while (!h_class->IsRetired() && !h_class->IsErroneous()) {
1947       lock.WaitIgnoringInterrupts();
1948     }
1949     if (h_class->IsErroneous()) {
1950       ThrowEarlierClassFailure(h_class.Get());
1951       return nullptr;
1952     }
1953     CHECK(h_class->IsRetired());
1954     // Get the updated class from class table.
1955     klass = LookupClass(descriptor, h_class.Get()->GetClassLoader());
1956   }
1957 
1958   // Wait for the class if it has not already been linked.
1959   if (!klass->IsResolved() && !klass->IsErroneous()) {
1960     StackHandleScope<1> hs(self);
1961     HandleWrapper<mirror::Class> h_class(hs.NewHandleWrapper(&klass));
1962     ObjectLock<mirror::Class> lock(self, h_class);
1963     // Check for circular dependencies between classes.
1964     if (!h_class->IsResolved() && h_class->GetClinitThreadId() == self->GetTid()) {
1965       ThrowClassCircularityError(h_class.Get());
1966       h_class->SetStatus(mirror::Class::kStatusError, self);
1967       return nullptr;
1968     }
1969     // Wait for the pending initialization to complete.
1970     while (!h_class->IsResolved() && !h_class->IsErroneous()) {
1971       lock.WaitIgnoringInterrupts();
1972     }
1973   }
1974 
1975   if (klass->IsErroneous()) {
1976     ThrowEarlierClassFailure(klass);
1977     return nullptr;
1978   }
1979   // Return the loaded class.  No exceptions should be pending.
1980   CHECK(klass->IsResolved()) << PrettyClass(klass);
1981   self->AssertNoPendingException();
1982   return klass;
1983 }
1984 
1985 typedef std::pair<const DexFile*, const DexFile::ClassDef*> ClassPathEntry;
1986 
1987 // Search a collection of DexFiles for a descriptor
FindInClassPath(const char * descriptor,const std::vector<const DexFile * > & class_path)1988 ClassPathEntry FindInClassPath(const char* descriptor,
1989                                const std::vector<const DexFile*>& class_path) {
1990   for (size_t i = 0; i != class_path.size(); ++i) {
1991     const DexFile* dex_file = class_path[i];
1992     const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
1993     if (dex_class_def != nullptr) {
1994       return ClassPathEntry(dex_file, dex_class_def);
1995     }
1996   }
1997   // TODO: remove reinterpret_cast when issue with -std=gnu++0x host issue resolved
1998   return ClassPathEntry(static_cast<const DexFile*>(nullptr),
1999                         static_cast<const DexFile::ClassDef*>(nullptr));
2000 }
2001 
FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable & soa,Thread * self,const char * descriptor,Handle<mirror::ClassLoader> class_loader)2002 mirror::Class* ClassLinker::FindClassInPathClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
2003                                                        Thread* self, const char* descriptor,
2004                                                        Handle<mirror::ClassLoader> class_loader) {
2005   if (class_loader->GetClass() !=
2006       soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2007       class_loader->GetParent()->GetClass() !=
2008           soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2009     return nullptr;
2010   }
2011   ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2012   // Check if this would be found in the parent boot class loader.
2013   if (pair.second != nullptr) {
2014     mirror::Class* klass = LookupClass(descriptor, nullptr);
2015     if (klass != nullptr) {
2016       return EnsureResolved(self, descriptor, klass);
2017     }
2018     klass = DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first,
2019                         *pair.second);
2020     if (klass != nullptr) {
2021       return klass;
2022     }
2023     CHECK(self->IsExceptionPending()) << descriptor;
2024     self->ClearException();
2025   } else {
2026     // RegisterDexFile may allocate dex caches (and cause thread suspension).
2027     StackHandleScope<3> hs(self);
2028     // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2029     // We need to get the DexPathList and loop through it.
2030     Handle<mirror::ArtField> cookie_field =
2031         hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2032     Handle<mirror::ArtField> dex_file_field =
2033         hs.NewHandle(
2034             soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList$Element_dexFile));
2035     mirror::Object* dex_path_list =
2036         soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2037         GetObject(class_loader.Get());
2038     if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2039         cookie_field.Get() != nullptr) {
2040       // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2041       mirror::Object* dex_elements_obj =
2042           soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2043           GetObject(dex_path_list);
2044       // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2045       // at the mCookie which is a DexFile vector.
2046       if (dex_elements_obj != nullptr) {
2047         Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2048             hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2049         for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2050           mirror::Object* element = dex_elements->GetWithoutChecks(i);
2051           if (element == nullptr) {
2052             // Should never happen, fall back to java code to throw a NPE.
2053             break;
2054           }
2055           mirror::Object* dex_file = dex_file_field->GetObject(element);
2056           if (dex_file != nullptr) {
2057             const uint64_t cookie = cookie_field->GetLong(dex_file);
2058             auto* dex_files =
2059                 reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2060             if (dex_files == nullptr) {
2061               // This should never happen so log a warning.
2062               LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2063               break;
2064             }
2065             for (const DexFile* dex_file : *dex_files) {
2066               const DexFile::ClassDef* dex_class_def = dex_file->FindClassDef(descriptor);
2067               if (dex_class_def != nullptr) {
2068                 RegisterDexFile(*dex_file);
2069                 mirror::Class* klass =
2070                     DefineClass(descriptor, class_loader, *dex_file, *dex_class_def);
2071                 if (klass == nullptr) {
2072                   CHECK(self->IsExceptionPending()) << descriptor;
2073                   self->ClearException();
2074                   return nullptr;
2075                 }
2076                 return klass;
2077               }
2078             }
2079           }
2080         }
2081       }
2082     }
2083   }
2084   return nullptr;
2085 }
2086 
FindClass(Thread * self,const char * descriptor,Handle<mirror::ClassLoader> class_loader)2087 mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
2088                                       Handle<mirror::ClassLoader> class_loader) {
2089   DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
2090   DCHECK(self != nullptr);
2091   self->AssertNoPendingException();
2092   if (descriptor[1] == '\0') {
2093     // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2094     // for primitive classes that aren't backed by dex files.
2095     return FindPrimitiveClass(descriptor[0]);
2096   }
2097   // Find the class in the loaded classes table.
2098   mirror::Class* klass = LookupClass(descriptor, class_loader.Get());
2099   if (klass != nullptr) {
2100     return EnsureResolved(self, descriptor, klass);
2101   }
2102   // Class is not yet loaded.
2103   if (descriptor[0] == '[') {
2104     return CreateArrayClass(self, descriptor, class_loader);
2105   } else if (class_loader.Get() == nullptr) {
2106     // The boot class loader, search the boot class path.
2107     ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2108     if (pair.second != nullptr) {
2109       return DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first, *pair.second);
2110     } else {
2111       // The boot class loader is searched ahead of the application class loader, failures are
2112       // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2113       // trigger the chaining with a proper stack trace.
2114       mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2115       self->SetException(ThrowLocation(), pre_allocated);
2116       return nullptr;
2117     }
2118   } else if (Runtime::Current()->UseCompileTimeClassPath()) {
2119     // First try with the bootstrap class loader.
2120     if (class_loader.Get() != nullptr) {
2121       klass = LookupClass(descriptor, nullptr);
2122       if (klass != nullptr) {
2123         return EnsureResolved(self, descriptor, klass);
2124       }
2125     }
2126     // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2127     // a NoClassDefFoundError being allocated.
2128     ClassPathEntry pair = FindInClassPath(descriptor, boot_class_path_);
2129     if (pair.second != nullptr) {
2130       return DefineClass(descriptor, NullHandle<mirror::ClassLoader>(), *pair.first, *pair.second);
2131     }
2132     // Next try the compile time class path.
2133     const std::vector<const DexFile*>* class_path;
2134     {
2135       ScopedObjectAccessUnchecked soa(self);
2136       ScopedLocalRef<jobject> jclass_loader(soa.Env(),
2137                                             soa.AddLocalReference<jobject>(class_loader.Get()));
2138       class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2139     }
2140     pair = FindInClassPath(descriptor, *class_path);
2141     if (pair.second != nullptr) {
2142       return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
2143     }
2144   } else {
2145     ScopedObjectAccessUnchecked soa(self);
2146     mirror::Class* klass = FindClassInPathClassLoader(soa, self, descriptor, class_loader);
2147     if (klass != nullptr) {
2148       return klass;
2149     }
2150     ScopedLocalRef<jobject> class_loader_object(soa.Env(),
2151                                                 soa.AddLocalReference<jobject>(class_loader.Get()));
2152     std::string class_name_string(DescriptorToDot(descriptor));
2153     ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2154     {
2155       ScopedThreadStateChange tsc(self, kNative);
2156       ScopedLocalRef<jobject> class_name_object(soa.Env(),
2157                                                 soa.Env()->NewStringUTF(class_name_string.c_str()));
2158       if (class_name_object.get() == nullptr) {
2159         DCHECK(self->IsExceptionPending());  // OOME.
2160         return nullptr;
2161       }
2162       CHECK(class_loader_object.get() != nullptr);
2163       result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2164                                                WellKnownClasses::java_lang_ClassLoader_loadClass,
2165                                                class_name_object.get()));
2166     }
2167     if (self->IsExceptionPending()) {
2168       // If the ClassLoader threw, pass that exception up.
2169       return nullptr;
2170     } else if (result.get() == nullptr) {
2171       // broken loader - throw NPE to be compatible with Dalvik
2172       ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
2173                                                       class_name_string.c_str()).c_str());
2174       return nullptr;
2175     } else {
2176       // success, return mirror::Class*
2177       return soa.Decode<mirror::Class*>(result.get());
2178     }
2179   }
2180 
2181   ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
2182   return nullptr;
2183 }
2184 
DefineClass(const char * descriptor,Handle<mirror::ClassLoader> class_loader,const DexFile & dex_file,const DexFile::ClassDef & dex_class_def)2185 mirror::Class* ClassLinker::DefineClass(const char* descriptor,
2186                                         Handle<mirror::ClassLoader> class_loader,
2187                                         const DexFile& dex_file,
2188                                         const DexFile::ClassDef& dex_class_def) {
2189   Thread* self = Thread::Current();
2190   StackHandleScope<3> hs(self);
2191   auto klass = hs.NewHandle<mirror::Class>(nullptr);
2192   bool should_allocate = false;
2193 
2194   // Load the class from the dex file.
2195   if (UNLIKELY(!init_done_)) {
2196     // finish up init of hand crafted class_roots_
2197     if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
2198       klass.Assign(GetClassRoot(kJavaLangObject));
2199     } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
2200       klass.Assign(GetClassRoot(kJavaLangClass));
2201     } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2202       klass.Assign(GetClassRoot(kJavaLangString));
2203     } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2204       klass.Assign(GetClassRoot(kJavaLangRefReference));
2205     } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
2206       klass.Assign(GetClassRoot(kJavaLangDexCache));
2207     } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
2208       klass.Assign(GetClassRoot(kJavaLangReflectArtField));
2209     } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
2210       klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
2211     } else {
2212       should_allocate = true;
2213     }
2214   } else {
2215     should_allocate = true;
2216   }
2217 
2218   if (should_allocate) {
2219     // Allocate a class with the status of not ready.
2220     // Interface object should get the right size here. Regular class will
2221     // figure out the right size later and be replaced with one of the right
2222     // size when the class becomes resolved.
2223     klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
2224   }
2225   if (UNLIKELY(klass.Get() == nullptr)) {
2226     CHECK(self->IsExceptionPending());  // Expect an OOME.
2227     return nullptr;
2228   }
2229   klass->SetDexCache(FindDexCache(dex_file));
2230   LoadClass(dex_file, dex_class_def, klass, class_loader.Get());
2231   ObjectLock<mirror::Class> lock(self, klass);
2232   if (self->IsExceptionPending()) {
2233     // An exception occured during load, set status to erroneous while holding klass' lock in case
2234     // notification is necessary.
2235     if (!klass->IsErroneous()) {
2236       klass->SetStatus(mirror::Class::kStatusError, self);
2237     }
2238     return nullptr;
2239   }
2240   klass->SetClinitThreadId(self->GetTid());
2241 
2242   // Add the newly loaded class to the loaded classes table.
2243   mirror::Class* existing = InsertClass(descriptor, klass.Get(), Hash(descriptor));
2244   if (existing != nullptr) {
2245     // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2246     // this thread to block.
2247     return EnsureResolved(self, descriptor, existing);
2248   }
2249 
2250   // Finish loading (if necessary) by finding parents
2251   CHECK(!klass->IsLoaded());
2252   if (!LoadSuperAndInterfaces(klass, dex_file)) {
2253     // Loading failed.
2254     if (!klass->IsErroneous()) {
2255       klass->SetStatus(mirror::Class::kStatusError, self);
2256     }
2257     return nullptr;
2258   }
2259   CHECK(klass->IsLoaded());
2260   // Link the class (if necessary)
2261   CHECK(!klass->IsResolved());
2262   // TODO: Use fast jobjects?
2263   auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
2264 
2265   mirror::Class* new_class = nullptr;
2266   if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
2267     // Linking failed.
2268     if (!klass->IsErroneous()) {
2269       klass->SetStatus(mirror::Class::kStatusError, self);
2270     }
2271     return nullptr;
2272   }
2273   self->AssertNoPendingException();
2274   CHECK(new_class != nullptr) << descriptor;
2275   CHECK(new_class->IsResolved()) << descriptor;
2276 
2277   Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
2278 
2279   /*
2280    * We send CLASS_PREPARE events to the debugger from here.  The
2281    * definition of "preparation" is creating the static fields for a
2282    * class and initializing them to the standard default values, but not
2283    * executing any code (that comes later, during "initialization").
2284    *
2285    * We did the static preparation in LinkClass.
2286    *
2287    * The class has been prepared and resolved but possibly not yet verified
2288    * at this point.
2289    */
2290   Dbg::PostClassPrepare(new_class_h.Get());
2291 
2292   return new_class_h.Get();
2293 }
2294 
SizeOfClassWithoutEmbeddedTables(const DexFile & dex_file,const DexFile::ClassDef & dex_class_def)2295 uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2296                                                        const DexFile::ClassDef& dex_class_def) {
2297   const byte* class_data = dex_file.GetClassData(dex_class_def);
2298   size_t num_ref = 0;
2299   size_t num_32 = 0;
2300   size_t num_64 = 0;
2301   if (class_data != nullptr) {
2302     for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2303       const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
2304       const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
2305       char c = descriptor[0];
2306       if (c == 'L' || c == '[') {
2307         num_ref++;
2308       } else if (c == 'J' || c == 'D') {
2309         num_64++;
2310       } else {
2311         num_32++;
2312       }
2313     }
2314   }
2315   return mirror::Class::ComputeClassSize(false, 0, num_32, num_64, num_ref);
2316 }
2317 
FindOatClass(const DexFile & dex_file,uint16_t class_def_idx,OatFile::OatClass * oat_class)2318 bool ClassLinker::FindOatClass(const DexFile& dex_file,
2319                                uint16_t class_def_idx,
2320                                OatFile::OatClass* oat_class) {
2321   DCHECK(oat_class != nullptr);
2322   DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
2323   const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2324   if (oat_dex_file == nullptr) {
2325     return false;
2326   }
2327   *oat_class = oat_dex_file->GetOatClass(class_def_idx);
2328   return true;
2329 }
2330 
GetOatMethodIndexFromMethodIndex(const DexFile & dex_file,uint16_t class_def_idx,uint32_t method_idx)2331 static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2332                                                  uint32_t method_idx) {
2333   const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2334   const byte* class_data = dex_file.GetClassData(class_def);
2335   CHECK(class_data != nullptr);
2336   ClassDataItemIterator it(dex_file, class_data);
2337   // Skip fields
2338   while (it.HasNextStaticField()) {
2339     it.Next();
2340   }
2341   while (it.HasNextInstanceField()) {
2342     it.Next();
2343   }
2344   // Process methods
2345   size_t class_def_method_index = 0;
2346   while (it.HasNextDirectMethod()) {
2347     if (it.GetMemberIndex() == method_idx) {
2348       return class_def_method_index;
2349     }
2350     class_def_method_index++;
2351     it.Next();
2352   }
2353   while (it.HasNextVirtualMethod()) {
2354     if (it.GetMemberIndex() == method_idx) {
2355       return class_def_method_index;
2356     }
2357     class_def_method_index++;
2358     it.Next();
2359   }
2360   DCHECK(!it.HasNext());
2361   LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2362   return 0;
2363 }
2364 
FindOatMethodFor(mirror::ArtMethod * method,OatFile::OatMethod * oat_method)2365 bool ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, OatFile::OatMethod* oat_method) {
2366   DCHECK(oat_method != nullptr);
2367   // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
2368   // method for direct methods (or virtual methods made direct).
2369   mirror::Class* declaring_class = method->GetDeclaringClass();
2370   size_t oat_method_index;
2371   if (method->IsStatic() || method->IsDirect()) {
2372     // Simple case where the oat method index was stashed at load time.
2373     oat_method_index = method->GetMethodIndex();
2374   } else {
2375     // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2376     // by search for its position in the declared virtual methods.
2377     oat_method_index = declaring_class->NumDirectMethods();
2378     size_t end = declaring_class->NumVirtualMethods();
2379     bool found = false;
2380     for (size_t i = 0; i < end; i++) {
2381       // Check method index instead of identity in case of duplicate method definitions.
2382       if (method->GetDexMethodIndex() ==
2383           declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
2384         found = true;
2385         break;
2386       }
2387       oat_method_index++;
2388     }
2389     CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
2390   }
2391   DCHECK_EQ(oat_method_index,
2392             GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
2393                                              method->GetDeclaringClass()->GetDexClassDefIndex(),
2394                                              method->GetDexMethodIndex()));
2395   OatFile::OatClass oat_class;
2396   if (!FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2397                     declaring_class->GetDexClassDefIndex(),
2398                     &oat_class)) {
2399     return false;
2400   }
2401 
2402   *oat_method = oat_class.GetOatMethod(oat_method_index);
2403   return true;
2404 }
2405 
2406 // Special case to get oat code without overwriting a trampoline.
GetQuickOatCodeFor(mirror::ArtMethod * method)2407 const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
2408   CHECK(!method->IsAbstract()) << PrettyMethod(method);
2409   if (method->IsProxyMethod()) {
2410     return GetQuickProxyInvokeHandler();
2411   }
2412   OatFile::OatMethod oat_method;
2413   const void* result = nullptr;
2414   if (FindOatMethodFor(method, &oat_method)) {
2415     result = oat_method.GetQuickCode();
2416   }
2417 
2418   if (result == nullptr) {
2419     if (method->IsNative()) {
2420       // No code and native? Use generic trampoline.
2421       result = GetQuickGenericJniTrampoline();
2422 #if defined(ART_USE_PORTABLE_COMPILER)
2423     } else if (method->IsPortableCompiled()) {
2424       // No code? Do we expect portable code?
2425       result = GetQuickToPortableBridge();
2426 #endif
2427     } else {
2428       // No code? You must mean to go into the interpreter.
2429       result = GetQuickToInterpreterBridge();
2430     }
2431   }
2432   return result;
2433 }
2434 
2435 #if defined(ART_USE_PORTABLE_COMPILER)
GetPortableOatCodeFor(mirror::ArtMethod * method,bool * have_portable_code)2436 const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2437                                                bool* have_portable_code) {
2438   CHECK(!method->IsAbstract()) << PrettyMethod(method);
2439   *have_portable_code = false;
2440   if (method->IsProxyMethod()) {
2441     return GetPortableProxyInvokeHandler();
2442   }
2443   OatFile::OatMethod oat_method;
2444   const void* result = nullptr;
2445   const void* quick_code = nullptr;
2446   if (FindOatMethodFor(method, &oat_method)) {
2447     result = oat_method.GetPortableCode();
2448     quick_code = oat_method.GetQuickCode();
2449   }
2450 
2451   if (result == nullptr) {
2452     if (quick_code == nullptr) {
2453       // No code? You must mean to go into the interpreter.
2454       result = GetPortableToInterpreterBridge();
2455     } else {
2456       // No code? But there's quick code, so use a bridge.
2457       result = GetPortableToQuickBridge();
2458     }
2459   } else {
2460     *have_portable_code = true;
2461   }
2462   return result;
2463 }
2464 #endif
2465 
GetQuickOatCodeFor(const DexFile & dex_file,uint16_t class_def_idx,uint32_t method_idx)2466 const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2467                                             uint32_t method_idx) {
2468   OatFile::OatClass oat_class;
2469   if (!FindOatClass(dex_file, class_def_idx, &oat_class)) {
2470     return nullptr;
2471   }
2472   uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
2473   return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
2474 }
2475 
2476 #if defined(ART_USE_PORTABLE_COMPILER)
GetPortableOatCodeFor(const DexFile & dex_file,uint16_t class_def_idx,uint32_t method_idx)2477 const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2478                                                uint32_t method_idx) {
2479   OatFile::OatClass oat_class;
2480   if (!FindOatClass(dex_file, class_def_idx, &oat_class)) {
2481     return nullptr;
2482   }
2483   uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
2484   return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
2485 }
2486 #endif
2487 
2488 // Returns true if the method must run with interpreter, false otherwise.
NeedsInterpreter(mirror::ArtMethod * method,const void * quick_code,const void * portable_code)2489 static bool NeedsInterpreter(
2490     mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2491     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2492   if ((quick_code == nullptr) && (portable_code == nullptr)) {
2493     // No code: need interpreter.
2494     // May return true for native code, in the case of generic JNI
2495     // DCHECK(!method->IsNative());
2496     return true;
2497   }
2498 #ifdef ART_SEA_IR_MODE
2499   ScopedObjectAccess soa(Thread::Current());
2500   if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2501     LOG(INFO) << "Found " << PrettyMethod(method);
2502     return false;
2503   }
2504 #endif
2505   // If interpreter mode is enabled, every method (except native and proxy) must
2506   // be run with interpreter.
2507   return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2508          !method->IsNative() && !method->IsProxyMethod();
2509 }
2510 
FixupStaticTrampolines(mirror::Class * klass)2511 void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
2512   DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
2513   if (klass->NumDirectMethods() == 0) {
2514     return;  // No direct methods => no static methods.
2515   }
2516   Runtime* runtime = Runtime::Current();
2517   if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
2518     if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2519       return;  // OAT file unavailable.
2520     }
2521   }
2522 
2523   const DexFile& dex_file = klass->GetDexFile();
2524   const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
2525   CHECK(dex_class_def != nullptr);
2526   const byte* class_data = dex_file.GetClassData(*dex_class_def);
2527   // There should always be class data if there were direct methods.
2528   CHECK(class_data != nullptr) << PrettyDescriptor(klass);
2529   ClassDataItemIterator it(dex_file, class_data);
2530   // Skip fields
2531   while (it.HasNextStaticField()) {
2532     it.Next();
2533   }
2534   while (it.HasNextInstanceField()) {
2535     it.Next();
2536   }
2537   OatFile::OatClass oat_class;
2538   bool has_oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class);
2539   // Link the code of methods skipped by LinkCode.
2540   for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
2541     mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
2542     if (!method->IsStatic()) {
2543       // Only update static methods.
2544       continue;
2545     }
2546     const void* portable_code = nullptr;
2547     const void* quick_code = nullptr;
2548     if (has_oat_class) {
2549       OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2550       portable_code = oat_method.GetPortableCode();
2551       quick_code = oat_method.GetQuickCode();
2552     }
2553     const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2554     bool have_portable_code = false;
2555     if (enter_interpreter) {
2556       // Use interpreter entry point.
2557       // Check whether the method is native, in which case it's generic JNI.
2558       if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2559         quick_code = GetQuickGenericJniTrampoline();
2560 #if defined(ART_USE_PORTABLE_COMPILER)
2561         portable_code = GetPortableToQuickBridge();
2562 #endif
2563       } else {
2564 #if defined(ART_USE_PORTABLE_COMPILER)
2565         portable_code = GetPortableToInterpreterBridge();
2566 #endif
2567         quick_code = GetQuickToInterpreterBridge();
2568       }
2569     } else {
2570 #if defined(ART_USE_PORTABLE_COMPILER)
2571       if (portable_code == nullptr) {
2572         portable_code = GetPortableToQuickBridge();
2573       } else {
2574         have_portable_code = true;
2575       }
2576       if (quick_code == nullptr) {
2577         quick_code = GetQuickToPortableBridge();
2578       }
2579 #else
2580       if (quick_code == nullptr) {
2581         quick_code = GetQuickToInterpreterBridge();
2582       }
2583 #endif
2584     }
2585     runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2586                                                      have_portable_code);
2587   }
2588   // Ignore virtual methods on the iterator.
2589 }
2590 
LinkCode(Handle<mirror::ArtMethod> method,const OatFile::OatClass * oat_class,const DexFile & dex_file,uint32_t dex_method_index,uint32_t method_index)2591 void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method, const OatFile::OatClass* oat_class,
2592                            const DexFile& dex_file, uint32_t dex_method_index,
2593                            uint32_t method_index) {
2594   if (Runtime::Current()->IsCompiler()) {
2595     // The following code only applies to a non-compiler runtime.
2596     return;
2597   }
2598   // Method shouldn't have already been linked.
2599   DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2600 #if defined(ART_USE_PORTABLE_COMPILER)
2601   DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
2602 #endif
2603   if (oat_class != nullptr) {
2604     // Every kind of method should at least get an invoke stub from the oat_method.
2605     // non-abstract methods also get their code pointers.
2606     const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
2607     oat_method.LinkMethod(method.Get());
2608   }
2609 
2610   // Install entry point from interpreter.
2611   bool enter_interpreter = NeedsInterpreter(method.Get(),
2612                                             method->GetEntryPointFromQuickCompiledCode(),
2613 #if defined(ART_USE_PORTABLE_COMPILER)
2614                                             method->GetEntryPointFromPortableCompiledCode());
2615 #else
2616                                             nullptr);
2617 #endif
2618   if (enter_interpreter && !method->IsNative()) {
2619     method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
2620   } else {
2621     method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
2622   }
2623 
2624   if (method->IsAbstract()) {
2625     method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2626 #if defined(ART_USE_PORTABLE_COMPILER)
2627     method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2628 #endif
2629     return;
2630   }
2631 
2632   bool have_portable_code = false;
2633   if (method->IsStatic() && !method->IsConstructor()) {
2634     // For static methods excluding the class initializer, install the trampoline.
2635     // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2636     // after initializing class (see ClassLinker::InitializeClass method).
2637     method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline());
2638 #if defined(ART_USE_PORTABLE_COMPILER)
2639     method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline());
2640 #endif
2641   } else if (enter_interpreter) {
2642     if (!method->IsNative()) {
2643       // Set entry point from compiled code if there's no code or in interpreter only mode.
2644       method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2645 #if defined(ART_USE_PORTABLE_COMPILER)
2646       method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2647 #endif
2648     } else {
2649       method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniTrampoline());
2650 #if defined(ART_USE_PORTABLE_COMPILER)
2651       method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2652 #endif
2653     }
2654 #if defined(ART_USE_PORTABLE_COMPILER)
2655   } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2656     DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2657     have_portable_code = true;
2658     method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2659 #endif
2660   } else {
2661     DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2662 #if defined(ART_USE_PORTABLE_COMPILER)
2663     method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2664 #endif
2665   }
2666 
2667   if (method->IsNative()) {
2668     // Unregistering restores the dlsym lookup stub.
2669     method->UnregisterNative(Thread::Current());
2670 
2671     if (enter_interpreter) {
2672       // We have a native method here without code. Then it should have either the GenericJni
2673       // trampoline as entrypoint (non-static), or the Resolution trampoline (static).
2674       DCHECK(method->GetEntryPointFromQuickCompiledCode() == GetQuickResolutionTrampoline()
2675           || method->GetEntryPointFromQuickCompiledCode() == GetQuickGenericJniTrampoline());
2676     }
2677   }
2678 
2679   // Allow instrumentation its chance to hijack code.
2680   Runtime* runtime = Runtime::Current();
2681   runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
2682                                                    method->GetEntryPointFromQuickCompiledCode(),
2683 #if defined(ART_USE_PORTABLE_COMPILER)
2684                                                    method->GetEntryPointFromPortableCompiledCode(),
2685 #else
2686                                                    nullptr,
2687 #endif
2688                                                    have_portable_code);
2689 }
2690 
LoadClass(const DexFile & dex_file,const DexFile::ClassDef & dex_class_def,Handle<mirror::Class> klass,mirror::ClassLoader * class_loader)2691 void ClassLinker::LoadClass(const DexFile& dex_file,
2692                             const DexFile::ClassDef& dex_class_def,
2693                             Handle<mirror::Class> klass,
2694                             mirror::ClassLoader* class_loader) {
2695   CHECK(klass.Get() != nullptr);
2696   CHECK(klass->GetDexCache() != nullptr);
2697   CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
2698   const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
2699   CHECK(descriptor != nullptr);
2700 
2701   klass->SetClass(GetClassRoot(kJavaLangClass));
2702   if (kUseBakerOrBrooksReadBarrier) {
2703     klass->AssertReadBarrierPointer();
2704   }
2705   uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
2706   CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
2707   klass->SetAccessFlags(access_flags);
2708   klass->SetClassLoader(class_loader);
2709   DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
2710   klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
2711 
2712   klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
2713   klass->SetDexTypeIndex(dex_class_def.class_idx_);
2714 
2715   const byte* class_data = dex_file.GetClassData(dex_class_def);
2716   if (class_data == nullptr) {
2717     return;  // no fields or methods - for example a marker interface
2718   }
2719 
2720   OatFile::OatClass oat_class;
2721   if (Runtime::Current()->IsStarted()
2722       && !Runtime::Current()->UseCompileTimeClassPath()
2723       && FindOatClass(dex_file, klass->GetDexClassDefIndex(), &oat_class)) {
2724     LoadClassMembers(dex_file, class_data, klass, class_loader, &oat_class);
2725   } else {
2726     LoadClassMembers(dex_file, class_data, klass, class_loader, nullptr);
2727   }
2728 }
2729 
LoadClassMembers(const DexFile & dex_file,const byte * class_data,Handle<mirror::Class> klass,mirror::ClassLoader * class_loader,const OatFile::OatClass * oat_class)2730 void ClassLinker::LoadClassMembers(const DexFile& dex_file,
2731                                    const byte* class_data,
2732                                    Handle<mirror::Class> klass,
2733                                    mirror::ClassLoader* class_loader,
2734                                    const OatFile::OatClass* oat_class) {
2735   // Load fields.
2736   ClassDataItemIterator it(dex_file, class_data);
2737   Thread* self = Thread::Current();
2738   if (it.NumStaticFields() != 0) {
2739     mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
2740     if (UNLIKELY(statics == nullptr)) {
2741       CHECK(self->IsExceptionPending());  // OOME.
2742       return;
2743     }
2744     klass->SetSFields(statics);
2745   }
2746   if (it.NumInstanceFields() != 0) {
2747     mirror::ObjectArray<mirror::ArtField>* fields =
2748         AllocArtFieldArray(self, it.NumInstanceFields());
2749     if (UNLIKELY(fields == nullptr)) {
2750       CHECK(self->IsExceptionPending());  // OOME.
2751       return;
2752     }
2753     klass->SetIFields(fields);
2754   }
2755   for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2756     StackHandleScope<1> hs(self);
2757     Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
2758     if (UNLIKELY(sfield.Get() == nullptr)) {
2759       CHECK(self->IsExceptionPending());  // OOME.
2760       return;
2761     }
2762     klass->SetStaticField(i, sfield.Get());
2763     LoadField(dex_file, it, klass, sfield);
2764   }
2765   for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
2766     StackHandleScope<1> hs(self);
2767     Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
2768     if (UNLIKELY(ifield.Get() == nullptr)) {
2769       CHECK(self->IsExceptionPending());  // OOME.
2770       return;
2771     }
2772     klass->SetInstanceField(i, ifield.Get());
2773     LoadField(dex_file, it, klass, ifield);
2774   }
2775 
2776   // Load methods.
2777   if (it.NumDirectMethods() != 0) {
2778     // TODO: append direct methods to class object
2779     mirror::ObjectArray<mirror::ArtMethod>* directs =
2780          AllocArtMethodArray(self, it.NumDirectMethods());
2781     if (UNLIKELY(directs == nullptr)) {
2782       CHECK(self->IsExceptionPending());  // OOME.
2783       return;
2784     }
2785     klass->SetDirectMethods(directs);
2786   }
2787   if (it.NumVirtualMethods() != 0) {
2788     // TODO: append direct methods to class object
2789     mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2790         AllocArtMethodArray(self, it.NumVirtualMethods());
2791     if (UNLIKELY(virtuals == nullptr)) {
2792       CHECK(self->IsExceptionPending());  // OOME.
2793       return;
2794     }
2795     klass->SetVirtualMethods(virtuals);
2796   }
2797   size_t class_def_method_index = 0;
2798   uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2799   size_t last_class_def_method_index = 0;
2800   for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
2801     StackHandleScope<1> hs(self);
2802     Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2803     if (UNLIKELY(method.Get() == nullptr)) {
2804       CHECK(self->IsExceptionPending());  // OOME.
2805       return;
2806     }
2807     klass->SetDirectMethod(i, method.Get());
2808     LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
2809     uint32_t it_method_index = it.GetMemberIndex();
2810     if (last_dex_method_index == it_method_index) {
2811       // duplicate case
2812       method->SetMethodIndex(last_class_def_method_index);
2813     } else {
2814       method->SetMethodIndex(class_def_method_index);
2815       last_dex_method_index = it_method_index;
2816       last_class_def_method_index = class_def_method_index;
2817     }
2818     class_def_method_index++;
2819   }
2820   for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
2821     StackHandleScope<1> hs(self);
2822     Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2823     if (UNLIKELY(method.Get() == nullptr)) {
2824       CHECK(self->IsExceptionPending());  // OOME.
2825       return;
2826     }
2827     klass->SetVirtualMethod(i, method.Get());
2828     DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
2829     LinkCode(method, oat_class, dex_file, it.GetMemberIndex(), class_def_method_index);
2830     class_def_method_index++;
2831   }
2832   DCHECK(!it.HasNext());
2833 }
2834 
LoadField(const DexFile &,const ClassDataItemIterator & it,Handle<mirror::Class> klass,Handle<mirror::ArtField> dst)2835 void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
2836                             Handle<mirror::Class> klass, Handle<mirror::ArtField> dst) {
2837   uint32_t field_idx = it.GetMemberIndex();
2838   dst->SetDexFieldIndex(field_idx);
2839   dst->SetDeclaringClass(klass.Get());
2840   dst->SetAccessFlags(it.GetFieldAccessFlags());
2841 }
2842 
LoadMethod(Thread * self,const DexFile & dex_file,const ClassDataItemIterator & it,Handle<mirror::Class> klass)2843 mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
2844                                            const ClassDataItemIterator& it,
2845                                            Handle<mirror::Class> klass) {
2846   uint32_t dex_method_idx = it.GetMemberIndex();
2847   const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
2848   const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
2849 
2850   mirror::ArtMethod* dst = AllocArtMethod(self);
2851   if (UNLIKELY(dst == nullptr)) {
2852     CHECK(self->IsExceptionPending());  // OOME.
2853     return nullptr;
2854   }
2855   DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
2856 
2857   const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
2858   dst->SetDexMethodIndex(dex_method_idx);
2859   dst->SetDeclaringClass(klass.Get());
2860   dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
2861 
2862   dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
2863   dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
2864   dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
2865 
2866   uint32_t access_flags = it.GetMethodAccessFlags();
2867 
2868   if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
2869     // Set finalizable flag on declaring class.
2870     if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2871       // Void return type.
2872       if (klass->GetClassLoader() != nullptr) {  // All non-boot finalizer methods are flagged.
2873         klass->SetFinalizable();
2874       } else {
2875         std::string temp;
2876         const char* klass_descriptor = klass->GetDescriptor(&temp);
2877         // The Enum class declares a "final" finalize() method to prevent subclasses from
2878         // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2879         // subclasses, so we exclude it here.
2880         // We also want to avoid setting the flag on Object, where we know that finalize() is
2881         // empty.
2882         if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2883             strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
2884           klass->SetFinalizable();
2885         }
2886       }
2887     }
2888   } else if (method_name[0] == '<') {
2889     // Fix broken access flags for initializers. Bug 11157540.
2890     bool is_init = (strcmp("<init>", method_name) == 0);
2891     bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
2892     if (UNLIKELY(!is_init && !is_clinit)) {
2893       LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2894     } else {
2895       if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2896         LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
2897             << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
2898         access_flags |= kAccConstructor;
2899       }
2900     }
2901   }
2902   dst->SetAccessFlags(access_flags);
2903 
2904   self->EndAssertNoThreadSuspension(old_cause);
2905   return dst;
2906 }
2907 
AppendToBootClassPath(const DexFile & dex_file)2908 void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
2909   Thread* self = Thread::Current();
2910   StackHandleScope<1> hs(self);
2911   Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2912   CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2913                                     << dex_file.GetLocation();
2914   AppendToBootClassPath(dex_file, dex_cache);
2915 }
2916 
AppendToBootClassPath(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)2917 void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
2918                                         Handle<mirror::DexCache> dex_cache) {
2919   CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
2920   boot_class_path_.push_back(&dex_file);
2921   RegisterDexFile(dex_file, dex_cache);
2922 }
2923 
IsDexFileRegisteredLocked(const DexFile & dex_file)2924 bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
2925   dex_lock_.AssertSharedHeld(Thread::Current());
2926   for (size_t i = 0; i != dex_caches_.size(); ++i) {
2927     mirror::DexCache* dex_cache = GetDexCache(i);
2928     if (dex_cache->GetDexFile() == &dex_file) {
2929       return true;
2930     }
2931   }
2932   return false;
2933 }
2934 
IsDexFileRegistered(const DexFile & dex_file)2935 bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
2936   ReaderMutexLock mu(Thread::Current(), dex_lock_);
2937   return IsDexFileRegisteredLocked(dex_file);
2938 }
2939 
RegisterDexFileLocked(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)2940 void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
2941                                         Handle<mirror::DexCache> dex_cache) {
2942   dex_lock_.AssertExclusiveHeld(Thread::Current());
2943   CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
2944   CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2945       << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
2946   dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
2947   dex_cache->SetDexFile(&dex_file);
2948   if (log_new_dex_caches_roots_) {
2949     // TODO: This is not safe if we can remove dex caches.
2950     new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
2951   }
2952 }
2953 
RegisterDexFile(const DexFile & dex_file)2954 void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
2955   Thread* self = Thread::Current();
2956   {
2957     ReaderMutexLock mu(self, dex_lock_);
2958     if (IsDexFileRegisteredLocked(dex_file)) {
2959       return;
2960     }
2961   }
2962   // Don't alloc while holding the lock, since allocation may need to
2963   // suspend all threads and another thread may need the dex_lock_ to
2964   // get to a suspend point.
2965   StackHandleScope<1> hs(self);
2966   Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2967   CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2968                                     << dex_file.GetLocation();
2969   {
2970     WriterMutexLock mu(self, dex_lock_);
2971     if (IsDexFileRegisteredLocked(dex_file)) {
2972       return;
2973     }
2974     RegisterDexFileLocked(dex_file, dex_cache);
2975   }
2976 }
2977 
RegisterDexFile(const DexFile & dex_file,Handle<mirror::DexCache> dex_cache)2978 void ClassLinker::RegisterDexFile(const DexFile& dex_file,
2979                                   Handle<mirror::DexCache> dex_cache) {
2980   WriterMutexLock mu(Thread::Current(), dex_lock_);
2981   RegisterDexFileLocked(dex_file, dex_cache);
2982 }
2983 
FindDexCache(const DexFile & dex_file)2984 mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
2985   ReaderMutexLock mu(Thread::Current(), dex_lock_);
2986   // Search assuming unique-ness of dex file.
2987   for (size_t i = 0; i != dex_caches_.size(); ++i) {
2988     mirror::DexCache* dex_cache = GetDexCache(i);
2989     if (dex_cache->GetDexFile() == &dex_file) {
2990       return dex_cache;
2991     }
2992   }
2993   // Search matching by location name.
2994   std::string location(dex_file.GetLocation());
2995   for (size_t i = 0; i != dex_caches_.size(); ++i) {
2996     mirror::DexCache* dex_cache = GetDexCache(i);
2997     if (dex_cache->GetDexFile()->GetLocation() == location) {
2998       return dex_cache;
2999     }
3000   }
3001   // Failure, dump diagnostic and abort.
3002   for (size_t i = 0; i != dex_caches_.size(); ++i) {
3003     mirror::DexCache* dex_cache = GetDexCache(i);
3004     LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3005   }
3006   LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
3007   return nullptr;
3008 }
3009 
FixupDexCaches(mirror::ArtMethod * resolution_method)3010 void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
3011   ReaderMutexLock mu(Thread::Current(), dex_lock_);
3012   for (size_t i = 0; i != dex_caches_.size(); ++i) {
3013     mirror::DexCache* dex_cache = GetDexCache(i);
3014     dex_cache->Fixup(resolution_method);
3015   }
3016 }
3017 
CreatePrimitiveClass(Thread * self,Primitive::Type type)3018 mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
3019   mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
3020   if (UNLIKELY(klass == nullptr)) {
3021     return nullptr;
3022   }
3023   return InitializePrimitiveClass(klass, type);
3024 }
3025 
InitializePrimitiveClass(mirror::Class * primitive_class,Primitive::Type type)3026 mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3027                                                      Primitive::Type type) {
3028   CHECK(primitive_class != nullptr);
3029   // Must hold lock on object when initializing.
3030   Thread* self = Thread::Current();
3031   StackHandleScope<1> hs(self);
3032   Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
3033   ObjectLock<mirror::Class> lock(self, h_class);
3034   primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3035   primitive_class->SetPrimitiveType(type);
3036   primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3037   const char* descriptor = Primitive::Descriptor(type);
3038   mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
3039   CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
3040   return primitive_class;
3041 }
3042 
3043 // Create an array class (i.e. the class object for the array, not the
3044 // array itself).  "descriptor" looks like "[C" or "[[[[B" or
3045 // "[Ljava/lang/String;".
3046 //
3047 // If "descriptor" refers to an array of primitives, look up the
3048 // primitive type's internally-generated class object.
3049 //
3050 // "class_loader" is the class loader of the class that's referring to
3051 // us.  It's used to ensure that we're looking for the element type in
3052 // the right context.  It does NOT become the class loader for the
3053 // array class; that always comes from the base element class.
3054 //
3055 // Returns nullptr with an exception raised on failure.
CreateArrayClass(Thread * self,const char * descriptor,Handle<mirror::ClassLoader> class_loader)3056 mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor,
3057                                              Handle<mirror::ClassLoader> class_loader) {
3058   // Identify the underlying component type
3059   CHECK_EQ('[', descriptor[0]);
3060   StackHandleScope<2> hs(self);
3061   Handle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1, class_loader)));
3062   if (component_type.Get() == nullptr) {
3063     DCHECK(self->IsExceptionPending());
3064     // We need to accept erroneous classes as component types.
3065     component_type.Assign(LookupClass(descriptor + 1, class_loader.Get()));
3066     if (component_type.Get() == nullptr) {
3067       DCHECK(self->IsExceptionPending());
3068       return nullptr;
3069     } else {
3070       self->ClearException();
3071     }
3072   }
3073   if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3074     ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3075     return nullptr;
3076   }
3077   // See if the component type is already loaded.  Array classes are
3078   // always associated with the class loader of their underlying
3079   // element type -- an array of Strings goes with the loader for
3080   // java/lang/String -- so we need to look for it there.  (The
3081   // caller should have checked for the existence of the class
3082   // before calling here, but they did so with *their* class loader,
3083   // not the component type's loader.)
3084   //
3085   // If we find it, the caller adds "loader" to the class' initiating
3086   // loader list, which should prevent us from going through this again.
3087   //
3088   // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
3089   // are the same, because our caller (FindClass) just did the
3090   // lookup.  (Even if we get this wrong we still have correct behavior,
3091   // because we effectively do this lookup again when we add the new
3092   // class to the hash table --- necessary because of possible races with
3093   // other threads.)
3094   if (class_loader.Get() != component_type->GetClassLoader()) {
3095     mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
3096     if (new_class != nullptr) {
3097       return new_class;
3098     }
3099   }
3100 
3101   // Fill out the fields in the Class.
3102   //
3103   // It is possible to execute some methods against arrays, because
3104   // all arrays are subclasses of java_lang_Object_, so we need to set
3105   // up a vtable.  We can just point at the one in java_lang_Object_.
3106   //
3107   // Array classes are simple enough that we don't need to do a full
3108   // link step.
3109   auto new_class = hs.NewHandle<mirror::Class>(nullptr);
3110   if (UNLIKELY(!init_done_)) {
3111     // Classes that were hand created, ie not by FindSystemClass
3112     if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
3113       new_class.Assign(GetClassRoot(kClassArrayClass));
3114     } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
3115       new_class.Assign(GetClassRoot(kObjectArrayClass));
3116     } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
3117       new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
3118     } else if (strcmp(descriptor,
3119                       class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
3120       new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
3121     } else if (strcmp(descriptor,
3122                       class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
3123       new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
3124     } else if (strcmp(descriptor, "[C") == 0) {
3125       new_class.Assign(GetClassRoot(kCharArrayClass));
3126     } else if (strcmp(descriptor, "[I") == 0) {
3127       new_class.Assign(GetClassRoot(kIntArrayClass));
3128     }
3129   }
3130   if (new_class.Get() == nullptr) {
3131     new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
3132     if (new_class.Get() == nullptr) {
3133       return nullptr;
3134     }
3135     new_class->SetComponentType(component_type.Get());
3136   }
3137   ObjectLock<mirror::Class> lock(self, new_class);  // Must hold lock on object when initializing.
3138   DCHECK(new_class->GetComponentType() != nullptr);
3139   mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
3140   new_class->SetSuperClass(java_lang_Object);
3141   new_class->SetVTable(java_lang_Object->GetVTable());
3142   new_class->SetPrimitiveType(Primitive::kPrimNot);
3143   new_class->SetClassLoader(component_type->GetClassLoader());
3144   new_class->SetStatus(mirror::Class::kStatusLoaded, self);
3145   new_class->PopulateEmbeddedImtAndVTable();
3146   new_class->SetStatus(mirror::Class::kStatusInitialized, self);
3147   // don't need to set new_class->SetObjectSize(..)
3148   // because Object::SizeOf delegates to Array::SizeOf
3149 
3150 
3151   // All arrays have java/lang/Cloneable and java/io/Serializable as
3152   // interfaces.  We need to set that up here, so that stuff like
3153   // "instanceof" works right.
3154   //
3155   // Note: The GC could run during the call to FindSystemClass,
3156   // so we need to make sure the class object is GC-valid while we're in
3157   // there.  Do this by clearing the interface list so the GC will just
3158   // think that the entries are null.
3159 
3160 
3161   // Use the single, global copies of "interfaces" and "iftable"
3162   // (remember not to free them for arrays).
3163   {
3164     mirror::IfTable* array_iftable = array_iftable_.Read();
3165     CHECK(array_iftable != nullptr);
3166     new_class->SetIfTable(array_iftable);
3167   }
3168 
3169   // Inherit access flags from the component type.
3170   int access_flags = new_class->GetComponentType()->GetAccessFlags();
3171   // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3172   access_flags &= kAccJavaFlagsMask;
3173   // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
3174   // and remove "interface".
3175   access_flags |= kAccAbstract | kAccFinal;
3176   access_flags &= ~kAccInterface;
3177 
3178   new_class->SetAccessFlags(access_flags);
3179 
3180   mirror::Class* existing = InsertClass(descriptor, new_class.Get(), Hash(descriptor));
3181   if (existing == nullptr) {
3182     return new_class.Get();
3183   }
3184   // Another thread must have loaded the class after we
3185   // started but before we finished.  Abandon what we've
3186   // done.
3187   //
3188   // (Yes, this happens.)
3189 
3190   return existing;
3191 }
3192 
FindPrimitiveClass(char type)3193 mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
3194   switch (type) {
3195     case 'B':
3196       return GetClassRoot(kPrimitiveByte);
3197     case 'C':
3198       return GetClassRoot(kPrimitiveChar);
3199     case 'D':
3200       return GetClassRoot(kPrimitiveDouble);
3201     case 'F':
3202       return GetClassRoot(kPrimitiveFloat);
3203     case 'I':
3204       return GetClassRoot(kPrimitiveInt);
3205     case 'J':
3206       return GetClassRoot(kPrimitiveLong);
3207     case 'S':
3208       return GetClassRoot(kPrimitiveShort);
3209     case 'Z':
3210       return GetClassRoot(kPrimitiveBoolean);
3211     case 'V':
3212       return GetClassRoot(kPrimitiveVoid);
3213     default:
3214       break;
3215   }
3216   std::string printable_type(PrintableChar(type));
3217   ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
3218   return nullptr;
3219 }
3220 
InsertClass(const char * descriptor,mirror::Class * klass,size_t hash)3221 mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3222                                         size_t hash) {
3223   if (VLOG_IS_ON(class_linker)) {
3224     mirror::DexCache* dex_cache = klass->GetDexCache();
3225     std::string source;
3226     if (dex_cache != nullptr) {
3227       source += " from ";
3228       source += dex_cache->GetLocation()->ToModifiedUtf8();
3229     }
3230     LOG(INFO) << "Loaded class " << descriptor << source;
3231   }
3232   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3233   mirror::Class* existing =
3234       LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3235   if (existing != nullptr) {
3236     return existing;
3237   }
3238   if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
3239       dex_cache_image_class_lookup_required_) {
3240     // Check a class loaded with the system class loader matches one in the image if the class
3241     // is in the image.
3242     existing = LookupClassFromImage(descriptor);
3243     if (existing != nullptr) {
3244       CHECK(klass == existing);
3245     }
3246   }
3247   VerifyObject(klass);
3248   class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
3249   if (log_new_class_table_roots_) {
3250     new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
3251   }
3252   return nullptr;
3253 }
3254 
UpdateClass(const char * descriptor,mirror::Class * klass,size_t hash)3255 mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3256                                         size_t hash) {
3257   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3258   mirror::Class* existing =
3259       LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3260 
3261   if (existing == nullptr) {
3262     CHECK(klass->IsProxyClass());
3263     return nullptr;
3264   }
3265 
3266   CHECK_NE(existing, klass) << descriptor;
3267   CHECK(!existing->IsResolved()) << descriptor;
3268   CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3269 
3270   for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3271        it != end && it->first == hash; ++it) {
3272     mirror::Class* klass = it->second.Read();
3273     if (klass == existing) {
3274       class_table_.erase(it);
3275       break;
3276     }
3277   }
3278 
3279   CHECK(!klass->IsTemp()) << descriptor;
3280   if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3281       dex_cache_image_class_lookup_required_) {
3282     // Check a class loaded with the system class loader matches one in the image if the class
3283     // is in the image.
3284     existing = LookupClassFromImage(descriptor);
3285     if (existing != nullptr) {
3286       CHECK(klass == existing) << descriptor;
3287     }
3288   }
3289   VerifyObject(klass);
3290 
3291   class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
3292   if (log_new_class_table_roots_) {
3293     new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
3294   }
3295 
3296   return existing;
3297 }
3298 
RemoveClass(const char * descriptor,const mirror::ClassLoader * class_loader)3299 bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
3300   size_t hash = Hash(descriptor);
3301   WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3302   for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3303        it != end && it->first == hash;
3304        ++it) {
3305     mirror::Class* klass = it->second.Read();
3306     if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
3307       class_table_.erase(it);
3308       return true;
3309     }
3310   }
3311   return false;
3312 }
3313 
LookupClass(const char * descriptor,const mirror::ClassLoader * class_loader)3314 mirror::Class* ClassLinker::LookupClass(const char* descriptor,
3315                                         const mirror::ClassLoader* class_loader) {
3316   size_t hash = Hash(descriptor);
3317   {
3318     ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3319     mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
3320     if (result != nullptr) {
3321       return result;
3322     }
3323   }
3324   if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3325     return nullptr;
3326   } else {
3327     // Lookup failed but need to search dex_caches_.
3328     mirror::Class* result = LookupClassFromImage(descriptor);
3329     if (result != nullptr) {
3330       InsertClass(descriptor, result, hash);
3331     } else {
3332       // Searching the image dex files/caches failed, we don't want to get into this situation
3333       // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3334       // classes into the class table.
3335       constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
3336       if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3337         MoveImageClassesToClassTable();
3338       }
3339     }
3340     return result;
3341   }
3342 }
3343 
LookupClassFromTableLocked(const char * descriptor,const mirror::ClassLoader * class_loader,size_t hash)3344 mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3345                                                        const mirror::ClassLoader* class_loader,
3346                                                        size_t hash) {
3347   auto end = class_table_.end();
3348   for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
3349     mirror::Class* klass = it->second.Read();
3350     if (klass->GetClassLoader() == class_loader && klass->DescriptorEquals(descriptor)) {
3351       if (kIsDebugBuild) {
3352         // Check for duplicates in the table.
3353         for (++it; it != end && it->first == hash; ++it) {
3354           mirror::Class* klass2 = it->second.Read();
3355           CHECK(!(klass2->GetClassLoader() == class_loader &&
3356               klass2->DescriptorEquals(descriptor)))
3357               << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
3358               << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
3359         }
3360       }
3361       return klass;
3362     }
3363   }
3364   return nullptr;
3365 }
3366 
GetImageDexCaches()3367 static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3368     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3369   gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
3370   CHECK(image != nullptr);
3371   mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3372   return root->AsObjectArray<mirror::DexCache>();
3373 }
3374 
MoveImageClassesToClassTable()3375 void ClassLinker::MoveImageClassesToClassTable() {
3376   Thread* self = Thread::Current();
3377   WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3378   if (!dex_cache_image_class_lookup_required_) {
3379     return;  // All dex cache classes are already in the class table.
3380   }
3381   const char* old_no_suspend_cause =
3382       self->StartAssertNoThreadSuspension("Moving image classes to class table");
3383   mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3384   std::string temp;
3385   for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3386     mirror::DexCache* dex_cache = dex_caches->Get(i);
3387     mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3388     for (int32_t j = 0; j < types->GetLength(); j++) {
3389       mirror::Class* klass = types->Get(j);
3390       if (klass != nullptr) {
3391         DCHECK(klass->GetClassLoader() == nullptr);
3392         const char* descriptor = klass->GetDescriptor(&temp);
3393         size_t hash = Hash(descriptor);
3394         mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3395         if (existing != nullptr) {
3396           CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
3397               << PrettyClassAndClassLoader(klass);
3398         } else {
3399           class_table_.insert(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
3400           if (log_new_class_table_roots_) {
3401             new_class_roots_.push_back(std::make_pair(hash, GcRoot<mirror::Class>(klass)));
3402           }
3403         }
3404       }
3405     }
3406   }
3407   dex_cache_image_class_lookup_required_ = false;
3408   self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3409 }
3410 
LookupClassFromImage(const char * descriptor)3411 mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
3412   Thread* self = Thread::Current();
3413   const char* old_no_suspend_cause =
3414       self->StartAssertNoThreadSuspension("Image class lookup");
3415   mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3416   for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3417     mirror::DexCache* dex_cache = dex_caches->Get(i);
3418     const DexFile* dex_file = dex_cache->GetDexFile();
3419     // Try binary searching the string/type index.
3420     const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
3421     if (string_id != nullptr) {
3422       const DexFile::TypeId* type_id =
3423           dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
3424       if (type_id != nullptr) {
3425         uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3426         mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3427         if (klass != nullptr) {
3428           self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3429           return klass;
3430         }
3431       }
3432     }
3433   }
3434   self->EndAssertNoThreadSuspension(old_no_suspend_cause);
3435   return nullptr;
3436 }
3437 
LookupClasses(const char * descriptor,std::vector<mirror::Class * > & result)3438 void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3439   result.clear();
3440   if (dex_cache_image_class_lookup_required_) {
3441     MoveImageClassesToClassTable();
3442   }
3443   size_t hash = Hash(descriptor);
3444   ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3445   for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
3446       it != end && it->first == hash; ++it) {
3447     mirror::Class* klass = it->second.Read();
3448     if (klass->DescriptorEquals(descriptor)) {
3449       result.push_back(klass);
3450     }
3451   }
3452 }
3453 
VerifyClass(Handle<mirror::Class> klass)3454 void ClassLinker::VerifyClass(Handle<mirror::Class> klass) {
3455   // TODO: assert that the monitor on the Class is held
3456   Thread* self = Thread::Current();
3457   ObjectLock<mirror::Class> lock(self, klass);
3458 
3459   // Don't attempt to re-verify if already sufficiently verified.
3460   if (klass->IsVerified()) {
3461     EnsurePreverifiedMethods(klass);
3462     return;
3463   }
3464   if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3465     return;
3466   }
3467 
3468   // The class might already be erroneous, for example at compile time if we attempted to verify
3469   // this class as a parent to another.
3470   if (klass->IsErroneous()) {
3471     ThrowEarlierClassFailure(klass.Get());
3472     return;
3473   }
3474 
3475   if (klass->GetStatus() == mirror::Class::kStatusResolved) {
3476     klass->SetStatus(mirror::Class::kStatusVerifying, self);
3477   } else {
3478     CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
3479         << PrettyClass(klass.Get());
3480     CHECK(!Runtime::Current()->IsCompiler());
3481     klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
3482   }
3483 
3484   // Skip verification if disabled.
3485   if (!Runtime::Current()->IsVerificationEnabled()) {
3486     klass->SetStatus(mirror::Class::kStatusVerified, self);
3487     EnsurePreverifiedMethods(klass);
3488     return;
3489   }
3490 
3491   // Verify super class.
3492   StackHandleScope<2> hs(self);
3493   Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
3494   if (super.Get() != nullptr) {
3495     // Acquire lock to prevent races on verifying the super class.
3496     ObjectLock<mirror::Class> lock(self, super);
3497 
3498     if (!super->IsVerified() && !super->IsErroneous()) {
3499       VerifyClass(super);
3500     }
3501     if (!super->IsCompileTimeVerified()) {
3502       std::string error_msg(
3503           StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3504                        PrettyDescriptor(klass.Get()).c_str(),
3505                        PrettyDescriptor(super.Get()).c_str()));
3506       LOG(ERROR) << error_msg  << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
3507       Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3508       if (cause.Get() != nullptr) {
3509         self->ClearException();
3510       }
3511       ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3512       if (cause.Get() != nullptr) {
3513         self->GetException(nullptr)->SetCause(cause.Get());
3514       }
3515       ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3516       if (Runtime::Current()->IsCompiler()) {
3517         Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3518       }
3519       klass->SetStatus(mirror::Class::kStatusError, self);
3520       return;
3521     }
3522   }
3523 
3524   // Try to use verification information from the oat file, otherwise do runtime verification.
3525   const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
3526   mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
3527   bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
3528   if (oat_file_class_status == mirror::Class::kStatusError) {
3529     VLOG(class_linker) << "Skipping runtime verification of erroneous class "
3530         << PrettyDescriptor(klass.Get()) << " in "
3531         << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
3532     ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3533                      PrettyDescriptor(klass.Get()).c_str());
3534     klass->SetStatus(mirror::Class::kStatusError, self);
3535     return;
3536   }
3537   verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
3538   std::string error_msg;
3539   if (!preverified) {
3540     verifier_failure = verifier::MethodVerifier::VerifyClass(klass.Get(),
3541                                                              Runtime::Current()->IsCompiler(),
3542                                                              &error_msg);
3543   }
3544   if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
3545     if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
3546       VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
3547           << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3548           << " because: " << error_msg;
3549     }
3550     self->AssertNoPendingException();
3551     // Make sure all classes referenced by catch blocks are resolved.
3552     ResolveClassExceptionHandlerTypes(dex_file, klass);
3553     if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
3554       // Even though there were no verifier failures we need to respect whether the super-class
3555       // was verified or requiring runtime reverification.
3556       if (super.Get() == nullptr || super->IsVerified()) {
3557         klass->SetStatus(mirror::Class::kStatusVerified, self);
3558       } else {
3559         CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
3560         klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
3561         // Pretend a soft failure occured so that we don't consider the class verified below.
3562         verifier_failure = verifier::MethodVerifier::kSoftFailure;
3563       }
3564     } else {
3565       CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3566       // Soft failures at compile time should be retried at runtime. Soft
3567       // failures at runtime will be handled by slow paths in the generated
3568       // code. Set status accordingly.
3569       if (Runtime::Current()->IsCompiler()) {
3570         klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
3571       } else {
3572         klass->SetStatus(mirror::Class::kStatusVerified, self);
3573         // As this is a fake verified status, make sure the methods are _not_ marked preverified
3574         // later.
3575         klass->SetAccessFlags(klass->GetAccessFlags() | kAccPreverified);
3576       }
3577     }
3578   } else {
3579     LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
3580         << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3581         << " because: " << error_msg;
3582     self->AssertNoPendingException();
3583     ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3584     klass->SetStatus(mirror::Class::kStatusError, self);
3585   }
3586   if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
3587     // Class is verified so we don't need to do any access check on its methods.
3588     // Let the interpreter know it by setting the kAccPreverified flag onto each
3589     // method.
3590     // Note: we're going here during compilation and at runtime. When we set the
3591     // kAccPreverified flag when compiling image classes, the flag is recorded
3592     // in the image and is set when loading the image.
3593     EnsurePreverifiedMethods(klass);
3594   }
3595 }
3596 
EnsurePreverifiedMethods(Handle<mirror::Class> klass)3597 void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
3598   if ((klass->GetAccessFlags() & kAccPreverified) == 0) {
3599     klass->SetPreverifiedFlagOnAllMethods();
3600     klass->SetAccessFlags(klass->GetAccessFlags() | kAccPreverified);
3601   }
3602 }
3603 
VerifyClassUsingOatFile(const DexFile & dex_file,mirror::Class * klass,mirror::Class::Status & oat_file_class_status)3604 bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3605                                           mirror::Class::Status& oat_file_class_status) {
3606   // If we're compiling, we can only verify the class using the oat file if
3607   // we are not compiling the image or if the class we're verifying is not part of
3608   // the app.  In other words, we will only check for preverification of bootclasspath
3609   // classes.
3610   if (Runtime::Current()->IsCompiler()) {
3611     // Are we compiling the bootclasspath?
3612     if (!Runtime::Current()->UseCompileTimeClassPath()) {
3613       return false;
3614     }
3615     // We are compiling an app (not the image).
3616 
3617     // Is this an app class? (I.e. not a bootclasspath class)
3618     if (klass->GetClassLoader() != nullptr) {
3619       return false;
3620     }
3621   }
3622 
3623   const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
3624   // In case we run without an image there won't be a backing oat file.
3625   if (oat_dex_file == nullptr) {
3626     return false;
3627   }
3628 
3629   uint16_t class_def_index = klass->GetDexClassDefIndex();
3630   oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
3631   if (oat_file_class_status == mirror::Class::kStatusVerified ||
3632       oat_file_class_status == mirror::Class::kStatusInitialized) {
3633       return true;
3634   }
3635   if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
3636     // Compile time verification failed with a soft error. Compile time verification can fail
3637     // because we have incomplete type information. Consider the following:
3638     // class ... {
3639     //   Foo x;
3640     //   .... () {
3641     //     if (...) {
3642     //       v1 gets assigned a type of resolved class Foo
3643     //     } else {
3644     //       v1 gets assigned a type of unresolved class Bar
3645     //     }
3646     //     iput x = v1
3647     // } }
3648     // when we merge v1 following the if-the-else it results in Conflict
3649     // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3650     // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3651     // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3652     // at compile time).
3653     return false;
3654   }
3655   if (oat_file_class_status == mirror::Class::kStatusError) {
3656     // Compile time verification failed with a hard error. This is caused by invalid instructions
3657     // in the class. These errors are unrecoverable.
3658     return false;
3659   }
3660   if (oat_file_class_status == mirror::Class::kStatusNotReady) {
3661     // Status is uninitialized if we couldn't determine the status at compile time, for example,
3662     // not loading the class.
3663     // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3664     // isn't a problem and this case shouldn't occur
3665     return false;
3666   }
3667   std::string temp;
3668   LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
3669              << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
3670              << klass->GetDescriptor(&temp);
3671 
3672   return false;
3673 }
3674 
ResolveClassExceptionHandlerTypes(const DexFile & dex_file,Handle<mirror::Class> klass)3675 void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
3676                                                     Handle<mirror::Class> klass) {
3677   for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3678     ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3679   }
3680   for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3681     ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3682   }
3683 }
3684 
ResolveMethodExceptionHandlerTypes(const DexFile & dex_file,mirror::ArtMethod * method)3685 void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
3686                                                      mirror::ArtMethod* method) {
3687   // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3688   const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
3689   if (code_item == nullptr) {
3690     return;  // native or abstract method
3691   }
3692   if (code_item->tries_size_ == 0) {
3693     return;  // nothing to process
3694   }
3695   const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3696   uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3697   ClassLinker* linker = Runtime::Current()->GetClassLinker();
3698   for (uint32_t idx = 0; idx < handlers_size; idx++) {
3699     CatchHandlerIterator iterator(handlers_ptr);
3700     for (; iterator.HasNext(); iterator.Next()) {
3701       // Ensure exception types are resolved so that they don't need resolution to be delivered,
3702       // unresolved exception types will be ignored by exception delivery
3703       if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
3704         mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
3705         if (exception_type == nullptr) {
3706           DCHECK(Thread::Current()->IsExceptionPending());
3707           Thread::Current()->ClearException();
3708         }
3709       }
3710     }
3711     handlers_ptr = iterator.EndDataPointer();
3712   }
3713 }
3714 
3715 static void CheckProxyConstructor(mirror::ArtMethod* constructor);
3716 static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3717                              Handle<mirror::ArtMethod> prototype);
3718 
CreateProxyClass(ScopedObjectAccessAlreadyRunnable & soa,jstring name,jobjectArray interfaces,jobject loader,jobjectArray methods,jobjectArray throws)3719 mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
3720                                              jobjectArray interfaces, jobject loader,
3721                                              jobjectArray methods, jobjectArray throws) {
3722   Thread* self = soa.Self();
3723   StackHandleScope<8> hs(self);
3724   Handle<mirror::Class> klass(hs.NewHandle(
3725       AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
3726   if (klass.Get() == nullptr) {
3727     CHECK(self->IsExceptionPending());  // OOME.
3728     return nullptr;
3729   }
3730   DCHECK(klass->GetClass() != nullptr);
3731   klass->SetObjectSize(sizeof(mirror::Proxy));
3732   // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3733   klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
3734   klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
3735   DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
3736   klass->SetName(soa.Decode<mirror::String*>(name));
3737   mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
3738   klass->SetDexCache(proxy_class->GetDexCache());
3739   klass->SetStatus(mirror::Class::kStatusIdx, self);
3740 
3741   // Instance fields are inherited, but we add a couple of static fields...
3742   {
3743     mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
3744     if (UNLIKELY(sfields == nullptr)) {
3745       CHECK(self->IsExceptionPending());  // OOME.
3746       return nullptr;
3747     }
3748     klass->SetSFields(sfields);
3749   }
3750   // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3751   // our proxy, so Class.getInterfaces doesn't return the flattened set.
3752   Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3753   if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
3754     CHECK(self->IsExceptionPending());  // OOME.
3755     return nullptr;
3756   }
3757   klass->SetStaticField(0, interfaces_sfield.Get());
3758   interfaces_sfield->SetDexFieldIndex(0);
3759   interfaces_sfield->SetDeclaringClass(klass.Get());
3760   interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3761   // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
3762   Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3763   if (UNLIKELY(throws_sfield.Get() == nullptr)) {
3764     CHECK(self->IsExceptionPending());  // OOME.
3765     return nullptr;
3766   }
3767   klass->SetStaticField(1, throws_sfield.Get());
3768   throws_sfield->SetDexFieldIndex(1);
3769   throws_sfield->SetDeclaringClass(klass.Get());
3770   throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3771 
3772   // Proxies have 1 direct method, the constructor
3773   {
3774     mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
3775     if (UNLIKELY(directs == nullptr)) {
3776       CHECK(self->IsExceptionPending());  // OOME.
3777       return nullptr;
3778     }
3779     klass->SetDirectMethods(directs);
3780     mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
3781     if (UNLIKELY(constructor == nullptr)) {
3782       CHECK(self->IsExceptionPending());  // OOME.
3783       return nullptr;
3784     }
3785     klass->SetDirectMethod(0, constructor);
3786   }
3787 
3788   // Create virtual method using specified prototypes.
3789   size_t num_virtual_methods =
3790       soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
3791   {
3792     mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3793                                                                            num_virtual_methods);
3794     if (UNLIKELY(virtuals == nullptr)) {
3795       CHECK(self->IsExceptionPending());  // OOME.
3796       return nullptr;
3797     }
3798     klass->SetVirtualMethods(virtuals);
3799   }
3800   for (size_t i = 0; i < num_virtual_methods; ++i) {
3801     StackHandleScope<1> hs(self);
3802     mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3803         soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
3804     Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
3805     mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
3806     if (UNLIKELY(clone == nullptr)) {
3807       CHECK(self->IsExceptionPending());  // OOME.
3808       return nullptr;
3809     }
3810     klass->SetVirtualMethod(i, clone);
3811   }
3812 
3813   klass->SetSuperClass(proxy_class);  // The super class is java.lang.reflect.Proxy
3814   klass->SetStatus(mirror::Class::kStatusLoaded, self);  // Now effectively in the loaded state.
3815   self->AssertNoPendingException();
3816 
3817   std::string descriptor(GetDescriptorForProxy(klass.Get()));
3818   mirror::Class* new_class = nullptr;
3819   {
3820     // Must hold lock on object when resolved.
3821     ObjectLock<mirror::Class> resolution_lock(self, klass);
3822     // Link the fields and virtual methods, creating vtable and iftables
3823     Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
3824         hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
3825     if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
3826       klass->SetStatus(mirror::Class::kStatusError, self);
3827       return nullptr;
3828     }
3829   }
3830 
3831   CHECK(klass->IsRetired());
3832   CHECK_NE(klass.Get(), new_class);
3833   klass.Assign(new_class);
3834 
3835   CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
3836   interfaces_sfield->SetObject<false>(klass.Get(),
3837                                       soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3838   CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
3839   throws_sfield->SetObject<false>(klass.Get(),
3840       soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
3841 
3842   {
3843     // Lock on klass is released. Lock new class object.
3844     ObjectLock<mirror::Class> initialization_lock(self, klass);
3845     klass->SetStatus(mirror::Class::kStatusInitialized, self);
3846   }
3847 
3848   // sanity checks
3849   if (kIsDebugBuild) {
3850     CHECK(klass->GetIFields() == nullptr);
3851     CheckProxyConstructor(klass->GetDirectMethod(0));
3852     for (size_t i = 0; i < num_virtual_methods; ++i) {
3853       StackHandleScope<2> hs(self);
3854       mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3855           soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
3856       Handle<mirror::ArtMethod> prototype(hs.NewHandle(decoded_methods->Get(i)));
3857       Handle<mirror::ArtMethod> virtual_method(hs.NewHandle(klass->GetVirtualMethod(i)));
3858       CheckProxyMethod(virtual_method, prototype);
3859     }
3860 
3861     mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
3862     std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
3863                                                    decoded_name->ToModifiedUtf8().c_str()));
3864     CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3865 
3866     std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
3867                                                decoded_name->ToModifiedUtf8().c_str()));
3868     CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
3869 
3870     CHECK_EQ(klass.Get()->GetInterfaces(),
3871              soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3872     CHECK_EQ(klass.Get()->GetThrows(),
3873              soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
3874   }
3875   mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(), Hash(descriptor.c_str()));
3876   CHECK(existing == nullptr);
3877   return klass.Get();
3878 }
3879 
GetDescriptorForProxy(mirror::Class * proxy_class)3880 std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
3881   DCHECK(proxy_class->IsProxyClass());
3882   mirror::String* name = proxy_class->GetName();
3883   DCHECK(name != nullptr);
3884   return DotToDescriptor(name->ToModifiedUtf8().c_str());
3885 }
3886 
FindMethodForProxy(mirror::Class * proxy_class,mirror::ArtMethod * proxy_method)3887 mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3888                                                    mirror::ArtMethod* proxy_method) {
3889   DCHECK(proxy_class->IsProxyClass());
3890   DCHECK(proxy_method->IsProxyMethod());
3891   // Locate the dex cache of the original interface/Object
3892   mirror::DexCache* dex_cache = nullptr;
3893   {
3894     ReaderMutexLock mu(Thread::Current(), dex_lock_);
3895     for (size_t i = 0; i != dex_caches_.size(); ++i) {
3896       mirror::DexCache* a_dex_cache = GetDexCache(i);
3897       if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
3898         dex_cache = a_dex_cache;
3899         break;
3900       }
3901     }
3902   }
3903   CHECK(dex_cache != nullptr);
3904   uint32_t method_idx = proxy_method->GetDexMethodIndex();
3905   mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
3906   CHECK(resolved_method != nullptr);
3907   return resolved_method;
3908 }
3909 
3910 
CreateProxyConstructor(Thread * self,Handle<mirror::Class> klass,mirror::Class * proxy_class)3911 mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
3912                                                        Handle<mirror::Class> klass,
3913                                                        mirror::Class* proxy_class) {
3914   // Create constructor for Proxy that must initialize h
3915   mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
3916       proxy_class->GetDirectMethods();
3917   CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3918   mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
3919   // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3920   // constructor method.
3921   proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3922                                                 proxy_constructor);
3923   // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
3924   // code_ too)
3925   mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
3926   if (constructor == nullptr) {
3927     CHECK(self->IsExceptionPending());  // OOME.
3928     return nullptr;
3929   }
3930   // Make this constructor public and fix the class to be our Proxy version
3931   constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
3932   constructor->SetDeclaringClass(klass.Get());
3933   return constructor;
3934 }
3935 
CheckProxyConstructor(mirror::ArtMethod * constructor)3936 static void CheckProxyConstructor(mirror::ArtMethod* constructor)
3937     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3938   CHECK(constructor->IsConstructor());
3939   CHECK_STREQ(constructor->GetName(), "<init>");
3940   CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
3941               "(Ljava/lang/reflect/InvocationHandler;)V");
3942   DCHECK(constructor->IsPublic());
3943 }
3944 
CreateProxyMethod(Thread * self,Handle<mirror::Class> klass,Handle<mirror::ArtMethod> prototype)3945 mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
3946                                                   Handle<mirror::Class> klass,
3947                                                   Handle<mirror::ArtMethod> prototype) {
3948   // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
3949   // prototype method
3950   prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
3951                                                                    prototype.Get());
3952   // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
3953   // as necessary
3954   mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
3955   if (UNLIKELY(method == nullptr)) {
3956     CHECK(self->IsExceptionPending());  // OOME.
3957     return nullptr;
3958   }
3959 
3960   // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
3961   // the intersection of throw exceptions as defined in Proxy
3962   method->SetDeclaringClass(klass.Get());
3963   method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
3964 
3965   // At runtime the method looks like a reference and argument saving method, clone the code
3966   // related parameters from this method.
3967   method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
3968 #if defined(ART_USE_PORTABLE_COMPILER)
3969   method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
3970 #endif
3971   method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
3972 
3973   return method;
3974 }
3975 
CheckProxyMethod(Handle<mirror::ArtMethod> method,Handle<mirror::ArtMethod> prototype)3976 static void CheckProxyMethod(Handle<mirror::ArtMethod> method, Handle<mirror::ArtMethod> prototype)
3977     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3978   // Basic sanity
3979   CHECK(!prototype->IsFinal());
3980   CHECK(method->IsFinal());
3981   CHECK(!method->IsAbstract());
3982 
3983   // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
3984   // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
3985   CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
3986   CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
3987   CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
3988   CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
3989 
3990   MethodHelper mh(method);
3991   MethodHelper mh2(prototype);
3992   CHECK_STREQ(method->GetName(), prototype->GetName());
3993   CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
3994   // More complex sanity - via dex cache
3995   CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
3996 }
3997 
CanWeInitializeClass(mirror::Class * klass,bool can_init_statics,bool can_init_parents)3998 static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
3999                                  bool can_init_parents)
4000     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4001   if (can_init_statics && can_init_parents) {
4002     return true;
4003   }
4004   if (!can_init_statics) {
4005     // Check if there's a class initializer.
4006     mirror::ArtMethod* clinit = klass->FindClassInitializer();
4007     if (clinit != nullptr) {
4008       return false;
4009     }
4010     // Check if there are encoded static values needing initialization.
4011     if (klass->NumStaticFields() != 0) {
4012       const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
4013       DCHECK(dex_class_def != nullptr);
4014       if (dex_class_def->static_values_off_ != 0) {
4015         return false;
4016       }
4017     }
4018   }
4019   if (!klass->IsInterface() && klass->HasSuperClass()) {
4020     mirror::Class* super_class = klass->GetSuperClass();
4021     if (!can_init_parents && !super_class->IsInitialized()) {
4022       return false;
4023     } else {
4024       if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
4025         return false;
4026       }
4027     }
4028   }
4029   return true;
4030 }
4031 
IsInitialized() const4032 bool ClassLinker::IsInitialized() const {
4033   return init_done_;
4034 }
4035 
InitializeClass(Handle<mirror::Class> klass,bool can_init_statics,bool can_init_parents)4036 bool ClassLinker::InitializeClass(Handle<mirror::Class> klass, bool can_init_statics,
4037                                   bool can_init_parents) {
4038   // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4039 
4040   // Are we already initialized and therefore done?
4041   // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4042   // an initialized class will never change its state.
4043   if (klass->IsInitialized()) {
4044     return true;
4045   }
4046 
4047   // Fast fail if initialization requires a full runtime. Not part of the JLS.
4048   if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
4049     return false;
4050   }
4051 
4052   Thread* self = Thread::Current();
4053   uint64_t t0;
4054   {
4055     ObjectLock<mirror::Class> lock(self, klass);
4056 
4057     // Re-check under the lock in case another thread initialized ahead of us.
4058     if (klass->IsInitialized()) {
4059       return true;
4060     }
4061 
4062     // Was the class already found to be erroneous? Done under the lock to match the JLS.
4063     if (klass->IsErroneous()) {
4064       ThrowEarlierClassFailure(klass.Get());
4065       return false;
4066     }
4067 
4068     CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
4069 
4070     if (!klass->IsVerified()) {
4071       VerifyClass(klass);
4072       if (!klass->IsVerified()) {
4073         // We failed to verify, expect either the klass to be erroneous or verification failed at
4074         // compile time.
4075         if (klass->IsErroneous()) {
4076           CHECK(self->IsExceptionPending());
4077         } else {
4078           CHECK(Runtime::Current()->IsCompiler());
4079           CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
4080         }
4081         return false;
4082       } else {
4083         self->AssertNoPendingException();
4084       }
4085     }
4086 
4087     // If the class is kStatusInitializing, either this thread is
4088     // initializing higher up the stack or another thread has beat us
4089     // to initializing and we need to wait. Either way, this
4090     // invocation of InitializeClass will not be responsible for
4091     // running <clinit> and will return.
4092     if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
4093       // Could have got an exception during verification.
4094       if (self->IsExceptionPending()) {
4095         return false;
4096       }
4097       // We caught somebody else in the act; was it us?
4098       if (klass->GetClinitThreadId() == self->GetTid()) {
4099         // Yes. That's fine. Return so we can continue initializing.
4100         return true;
4101       }
4102       // No. That's fine. Wait for another thread to finish initializing.
4103       return WaitForInitializeClass(klass, self, lock);
4104     }
4105 
4106     if (!ValidateSuperClassDescriptors(klass)) {
4107       klass->SetStatus(mirror::Class::kStatusError, self);
4108       return false;
4109     }
4110 
4111     CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
4112 
4113     // From here out other threads may observe that we're initializing and so changes of state
4114     // require the a notification.
4115     klass->SetClinitThreadId(self->GetTid());
4116     klass->SetStatus(mirror::Class::kStatusInitializing, self);
4117 
4118     t0 = NanoTime();
4119   }
4120 
4121   // Initialize super classes, must be done while initializing for the JLS.
4122   if (!klass->IsInterface() && klass->HasSuperClass()) {
4123     mirror::Class* super_class = klass->GetSuperClass();
4124     if (!super_class->IsInitialized()) {
4125       CHECK(!super_class->IsInterface());
4126       CHECK(can_init_parents);
4127       StackHandleScope<1> hs(self);
4128       Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
4129       bool super_initialized = InitializeClass(handle_scope_super, can_init_statics, true);
4130       if (!super_initialized) {
4131         // The super class was verified ahead of entering initializing, we should only be here if
4132         // the super class became erroneous due to initialization.
4133         CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
4134             << "Super class initialization failed for "
4135             << PrettyDescriptor(handle_scope_super.Get())
4136             << " that has unexpected status " << handle_scope_super->GetStatus()
4137             << "\nPending exception:\n"
4138             << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
4139         ObjectLock<mirror::Class> lock(self, klass);
4140         // Initialization failed because the super-class is erroneous.
4141         klass->SetStatus(mirror::Class::kStatusError, self);
4142         return false;
4143       }
4144     }
4145   }
4146 
4147   if (klass->NumStaticFields() > 0) {
4148     const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
4149     CHECK(dex_class_def != nullptr);
4150     const DexFile& dex_file = klass->GetDexFile();
4151     StackHandleScope<2> hs(self);
4152     Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
4153     Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4154     EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader,
4155                                        this, *dex_class_def);
4156     if (it.HasNext()) {
4157       CHECK(can_init_statics);
4158       // We reordered the fields, so we need to be able to map the
4159       // field indexes to the right fields.
4160       SafeMap<uint32_t, mirror::ArtField*> field_map;
4161       ConstructFieldMap(dex_file, *dex_class_def, klass.Get(), field_map);
4162       for (size_t i = 0; it.HasNext(); i++, it.Next()) {
4163         if (Runtime::Current()->IsActiveTransaction()) {
4164           it.ReadValueToField<true>(field_map.Get(i));
4165         } else {
4166           it.ReadValueToField<false>(field_map.Get(i));
4167         }
4168       }
4169     }
4170   }
4171 
4172   mirror::ArtMethod* clinit = klass->FindClassInitializer();
4173   if (clinit != nullptr) {
4174     CHECK(can_init_statics);
4175     JValue result;
4176     clinit->Invoke(self, nullptr, 0, &result, "V");
4177   }
4178 
4179   uint64_t t1 = NanoTime();
4180 
4181   bool success = true;
4182   {
4183     ObjectLock<mirror::Class> lock(self, klass);
4184 
4185     if (self->IsExceptionPending()) {
4186       WrapExceptionInInitializer();
4187       klass->SetStatus(mirror::Class::kStatusError, self);
4188       success = false;
4189     } else {
4190       RuntimeStats* global_stats = Runtime::Current()->GetStats();
4191       RuntimeStats* thread_stats = self->GetStats();
4192       ++global_stats->class_init_count;
4193       ++thread_stats->class_init_count;
4194       global_stats->class_init_time_ns += (t1 - t0);
4195       thread_stats->class_init_time_ns += (t1 - t0);
4196       // Set the class as initialized except if failed to initialize static fields.
4197       klass->SetStatus(mirror::Class::kStatusInitialized, self);
4198       if (VLOG_IS_ON(class_linker)) {
4199         std::string temp;
4200         LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
4201             klass->GetLocation();
4202       }
4203       // Opportunistically set static method trampolines to their destination.
4204       FixupStaticTrampolines(klass.Get());
4205     }
4206   }
4207   return success;
4208 }
4209 
WaitForInitializeClass(Handle<mirror::Class> klass,Thread * self,ObjectLock<mirror::Class> & lock)4210 bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
4211                                          ObjectLock<mirror::Class>& lock)
4212     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4213   while (true) {
4214     self->AssertNoPendingException();
4215     CHECK(!klass->IsInitialized());
4216     lock.WaitIgnoringInterrupts();
4217 
4218     // When we wake up, repeat the test for init-in-progress.  If
4219     // there's an exception pending (only possible if
4220     // "interruptShouldThrow" was set), bail out.
4221     if (self->IsExceptionPending()) {
4222       WrapExceptionInInitializer();
4223       klass->SetStatus(mirror::Class::kStatusError, self);
4224       return false;
4225     }
4226     // Spurious wakeup? Go back to waiting.
4227     if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
4228       continue;
4229     }
4230     if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
4231       // Compile time initialization failed.
4232       return false;
4233     }
4234     if (klass->IsErroneous()) {
4235       // The caller wants an exception, but it was thrown in a
4236       // different thread.  Synthesize one here.
4237       ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
4238                                 PrettyDescriptor(klass.Get()).c_str());
4239       return false;
4240     }
4241     if (klass->IsInitialized()) {
4242       return true;
4243     }
4244     LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
4245         << klass->GetStatus();
4246   }
4247   LOG(FATAL) << "Not Reached" << PrettyClass(klass.Get());
4248 }
4249 
ValidateSuperClassDescriptors(Handle<mirror::Class> klass)4250 bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
4251   if (klass->IsInterface()) {
4252     return true;
4253   }
4254   // Begin with the methods local to the superclass.
4255   StackHandleScope<2> hs(Thread::Current());
4256   MethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4257   MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4258   if (klass->HasSuperClass() &&
4259       klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
4260     for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4261       mh.ChangeMethod(klass->GetVTableEntry(i));
4262       super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
4263       if (mh.GetMethod() != super_mh.GetMethod() &&
4264           !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4265         ThrowLinkageError(klass.Get(),
4266                           "Class %s method %s resolves differently in superclass %s",
4267                           PrettyDescriptor(klass.Get()).c_str(),
4268                           PrettyMethod(mh.GetMethod()).c_str(),
4269                           PrettyDescriptor(klass->GetSuperClass()).c_str());
4270         return false;
4271       }
4272     }
4273   }
4274   for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
4275     if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4276       uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4277       for (uint32_t j = 0; j < num_methods; ++j) {
4278         mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4279         super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
4280         if (mh.GetMethod() != super_mh.GetMethod() &&
4281             !mh.HasSameSignatureWithDifferentClassLoaders(&super_mh)) {
4282           ThrowLinkageError(klass.Get(),
4283                             "Class %s method %s resolves differently in interface %s",
4284                             PrettyDescriptor(klass.Get()).c_str(),
4285                             PrettyMethod(mh.GetMethod()).c_str(),
4286                             PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
4287           return false;
4288         }
4289       }
4290     }
4291   }
4292   return true;
4293 }
4294 
EnsureInitialized(Handle<mirror::Class> c,bool can_init_fields,bool can_init_parents)4295 bool ClassLinker::EnsureInitialized(Handle<mirror::Class> c, bool can_init_fields,
4296                                     bool can_init_parents) {
4297   DCHECK(c.Get() != nullptr);
4298   if (c->IsInitialized()) {
4299     EnsurePreverifiedMethods(c);
4300     return true;
4301   }
4302   const bool success = InitializeClass(c, can_init_fields, can_init_parents);
4303   Thread* self = Thread::Current();
4304   if (!success) {
4305     if (can_init_fields && can_init_parents) {
4306       CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4307     }
4308   } else {
4309     self->AssertNoPendingException();
4310   }
4311   return success;
4312 }
4313 
ConstructFieldMap(const DexFile & dex_file,const DexFile::ClassDef & dex_class_def,mirror::Class * c,SafeMap<uint32_t,mirror::ArtField * > & field_map)4314 void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
4315                                     mirror::Class* c,
4316                                     SafeMap<uint32_t, mirror::ArtField*>& field_map) {
4317   const byte* class_data = dex_file.GetClassData(dex_class_def);
4318   ClassDataItemIterator it(dex_file, class_data);
4319   StackHandleScope<2> hs(Thread::Current());
4320   Handle<mirror::DexCache> dex_cache(hs.NewHandle(c->GetDexCache()));
4321   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(c->GetClassLoader()));
4322   CHECK(!kMovingFields);
4323   for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
4324     field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true));
4325   }
4326 }
4327 
FixupTemporaryDeclaringClass(mirror::Class * temp_class,mirror::Class * new_class)4328 void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4329   mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4330   if (fields != nullptr) {
4331     for (int index = 0; index < fields->GetLength(); index ++) {
4332       if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4333         fields->Get(index)->SetDeclaringClass(new_class);
4334       }
4335     }
4336   }
4337 
4338   fields = new_class->GetSFields();
4339   if (fields != nullptr) {
4340     for (int index = 0; index < fields->GetLength(); index ++) {
4341       if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4342         fields->Get(index)->SetDeclaringClass(new_class);
4343       }
4344     }
4345   }
4346 
4347   mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4348   if (methods != nullptr) {
4349     for (int index = 0; index < methods->GetLength(); index ++) {
4350       if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4351         methods->Get(index)->SetDeclaringClass(new_class);
4352       }
4353     }
4354   }
4355 
4356   methods = new_class->GetVirtualMethods();
4357   if (methods != nullptr) {
4358     for (int index = 0; index < methods->GetLength(); index ++) {
4359       if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4360         methods->Get(index)->SetDeclaringClass(new_class);
4361       }
4362     }
4363   }
4364 }
4365 
LinkClass(Thread * self,const char * descriptor,Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces,mirror::Class ** new_class)4366 bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4367                             Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4368                             mirror::Class** new_class) {
4369   CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
4370 
4371   if (!LinkSuperClass(klass)) {
4372     return false;
4373   }
4374   if (!LinkMethods(self, klass, interfaces)) {
4375     return false;
4376   }
4377   if (!LinkInstanceFields(klass)) {
4378     return false;
4379   }
4380   size_t class_size;
4381   if (!LinkStaticFields(klass, &class_size)) {
4382     return false;
4383   }
4384   CreateReferenceInstanceOffsets(klass);
4385   CreateReferenceStaticOffsets(klass);
4386   CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
4387 
4388   if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4389     // We don't need to retire this class as it has no embedded tables or it was created the
4390     // correct size during class linker initialization.
4391     CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4392 
4393     if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4394       klass->PopulateEmbeddedImtAndVTable();
4395     }
4396 
4397     // This will notify waiters on klass that saw the not yet resolved
4398     // class in the class_table_ during EnsureResolved.
4399     klass->SetStatus(mirror::Class::kStatusResolved, self);
4400     *new_class = klass.Get();
4401   } else {
4402     CHECK(!klass->IsResolved());
4403     // Retire the temporary class and create the correctly sized resolved class.
4404     *new_class = klass->CopyOf(self, class_size);
4405     if (UNLIKELY(*new_class == nullptr)) {
4406       CHECK(self->IsExceptionPending());  // Expect an OOME.
4407       klass->SetStatus(mirror::Class::kStatusError, self);
4408       return false;
4409     }
4410 
4411     CHECK_EQ((*new_class)->GetClassSize(), class_size);
4412     StackHandleScope<1> hs(self);
4413     auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4414     ObjectLock<mirror::Class> lock(self, new_class_h);
4415 
4416     FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4417 
4418     mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(), Hash(descriptor));
4419     CHECK(existing == nullptr || existing == klass.Get());
4420 
4421     // This will notify waiters on temp class that saw the not yet resolved class in the
4422     // class_table_ during EnsureResolved.
4423     klass->SetStatus(mirror::Class::kStatusRetired, self);
4424 
4425     CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4426     // This will notify waiters on new_class that saw the not yet resolved
4427     // class in the class_table_ during EnsureResolved.
4428     new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
4429   }
4430   return true;
4431 }
4432 
LoadSuperAndInterfaces(Handle<mirror::Class> klass,const DexFile & dex_file)4433 bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
4434   CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
4435   const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4436   uint16_t super_class_idx = class_def.superclass_idx_;
4437   if (super_class_idx != DexFile::kDexNoIndex16) {
4438     mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
4439     if (super_class == nullptr) {
4440       DCHECK(Thread::Current()->IsExceptionPending());
4441       return false;
4442     }
4443     // Verify
4444     if (!klass->CanAccess(super_class)) {
4445       ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
4446                               PrettyDescriptor(super_class).c_str(),
4447                               PrettyDescriptor(klass.Get()).c_str());
4448       return false;
4449     }
4450     CHECK(super_class->IsResolved());
4451     klass->SetSuperClass(super_class);
4452   }
4453   const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
4454   if (interfaces != nullptr) {
4455     for (size_t i = 0; i < interfaces->Size(); i++) {
4456       uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
4457       mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
4458       if (interface == nullptr) {
4459         DCHECK(Thread::Current()->IsExceptionPending());
4460         return false;
4461       }
4462       // Verify
4463       if (!klass->CanAccess(interface)) {
4464         // TODO: the RI seemed to ignore this in my testing.
4465         ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
4466                                 PrettyDescriptor(interface).c_str(),
4467                                 PrettyDescriptor(klass.Get()).c_str());
4468         return false;
4469       }
4470     }
4471   }
4472   // Mark the class as loaded.
4473   klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
4474   return true;
4475 }
4476 
LinkSuperClass(Handle<mirror::Class> klass)4477 bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
4478   CHECK(!klass->IsPrimitive());
4479   mirror::Class* super = klass->GetSuperClass();
4480   if (klass.Get() == GetClassRoot(kJavaLangObject)) {
4481     if (super != nullptr) {
4482       ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
4483       return false;
4484     }
4485     return true;
4486   }
4487   if (super == nullptr) {
4488     ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4489                       PrettyDescriptor(klass.Get()).c_str());
4490     return false;
4491   }
4492   // Verify
4493   if (super->IsFinal() || super->IsInterface()) {
4494     ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
4495                                       PrettyDescriptor(super).c_str(),
4496                                       PrettyDescriptor(klass.Get()).c_str(),
4497                                       super->IsFinal() ? "declared final" : "an interface");
4498     return false;
4499   }
4500   if (!klass->CanAccess(super)) {
4501     ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
4502                             PrettyDescriptor(super).c_str(),
4503                             PrettyDescriptor(klass.Get()).c_str());
4504     return false;
4505   }
4506 
4507   // Inherit kAccClassIsFinalizable from the superclass in case this
4508   // class doesn't override finalize.
4509   if (super->IsFinalizable()) {
4510     klass->SetFinalizable();
4511   }
4512 
4513   // Inherit reference flags (if any) from the superclass.
4514   int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4515   if (reference_flags != 0) {
4516     klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4517   }
4518   // Disallow custom direct subclasses of java.lang.ref.Reference.
4519   if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
4520     ThrowLinkageError(klass.Get(),
4521                       "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
4522                       PrettyDescriptor(klass.Get()).c_str());
4523     return false;
4524   }
4525 
4526   if (kIsDebugBuild) {
4527     // Ensure super classes are fully resolved prior to resolving fields..
4528     while (super != nullptr) {
4529       CHECK(super->IsResolved());
4530       super = super->GetSuperClass();
4531     }
4532   }
4533   return true;
4534 }
4535 
4536 // Populate the class vtable and itable. Compute return type indices.
LinkMethods(Thread * self,Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces)4537 bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
4538                               Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
4539   if (klass->IsInterface()) {
4540     // No vtable.
4541     size_t count = klass->NumVirtualMethods();
4542     if (!IsUint(16, count)) {
4543       ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
4544       return false;
4545     }
4546     for (size_t i = 0; i < count; ++i) {
4547       klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
4548     }
4549     // Link interface method tables
4550     return LinkInterfaceMethods(klass, interfaces);
4551   } else {
4552     // Link virtual and interface method tables
4553     return LinkVirtualMethods(self, klass) && LinkInterfaceMethods(klass, interfaces);
4554   }
4555   return true;
4556 }
4557 
LinkVirtualMethods(Thread * self,Handle<mirror::Class> klass)4558 bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
4559   if (klass->HasSuperClass()) {
4560     uint32_t max_count = klass->NumVirtualMethods() +
4561         klass->GetSuperClass()->GetVTableLength();
4562     size_t actual_count = klass->GetSuperClass()->GetVTableLength();
4563     CHECK_LE(actual_count, max_count);
4564     StackHandleScope<4> hs(self);
4565     Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
4566     Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
4567     if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4568       vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4569       if (UNLIKELY(vtable.Get() == nullptr)) {
4570         CHECK(self->IsExceptionPending());  // OOME.
4571         return false;
4572       }
4573       int len = super_class->GetVTableLength();
4574       for (int i = 0; i < len; i++) {
4575         vtable->Set<false>(i, super_class->GetVTableEntry(i));
4576       }
4577     } else {
4578       CHECK(super_class->GetVTable() != nullptr) << PrettyClass(super_class.Get());
4579       vtable = hs.NewHandle(super_class->GetVTable()->CopyOf(self, max_count));
4580       if (UNLIKELY(vtable.Get() == nullptr)) {
4581         CHECK(self->IsExceptionPending());  // OOME.
4582         return false;
4583       }
4584     }
4585 
4586     // See if any of our virtual methods override the superclass.
4587     MethodHelper local_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4588     MethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4589     for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
4590       mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4591       local_mh.ChangeMethod(local_method);
4592       size_t j = 0;
4593       for (; j < actual_count; ++j) {
4594         mirror::ArtMethod* super_method = vtable->Get(j);
4595         super_mh.ChangeMethod(super_method);
4596         if (local_mh.HasSameNameAndSignature(&super_mh)) {
4597           if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4598                                      super_method->GetAccessFlags())) {
4599             if (super_method->IsFinal()) {
4600               ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4601                                 PrettyMethod(local_method).c_str(),
4602                                 super_method->GetDeclaringClassDescriptor());
4603               return false;
4604             }
4605             vtable->Set<false>(j, local_method);
4606             local_method->SetMethodIndex(j);
4607             break;
4608           } else {
4609             LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
4610                          << " would have incorrectly overridden the package-private method in "
4611                          << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
4612           }
4613         }
4614       }
4615       if (j == actual_count) {
4616         // Not overriding, append.
4617         vtable->Set<false>(actual_count, local_method);
4618         local_method->SetMethodIndex(actual_count);
4619         actual_count += 1;
4620       }
4621     }
4622     if (!IsUint(16, actual_count)) {
4623       ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
4624       return false;
4625     }
4626     // Shrink vtable if possible
4627     CHECK_LE(actual_count, max_count);
4628     if (actual_count < max_count) {
4629       vtable.Assign(vtable->CopyOf(self, actual_count));
4630       if (UNLIKELY(vtable.Get() == nullptr)) {
4631         CHECK(self->IsExceptionPending());  // OOME.
4632         return false;
4633       }
4634     }
4635     klass->SetVTable(vtable.Get());
4636   } else {
4637     CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
4638     uint32_t num_virtual_methods = klass->NumVirtualMethods();
4639     if (!IsUint(16, num_virtual_methods)) {
4640       ThrowClassFormatError(klass.Get(), "Too many methods: %d", num_virtual_methods);
4641       return false;
4642     }
4643     StackHandleScope<1> hs(self);
4644     Handle<mirror::ObjectArray<mirror::ArtMethod>>
4645         vtable(hs.NewHandle(AllocArtMethodArray(self, num_virtual_methods)));
4646     if (UNLIKELY(vtable.Get() == nullptr)) {
4647       CHECK(self->IsExceptionPending());  // OOME.
4648       return false;
4649     }
4650     for (size_t i = 0; i < num_virtual_methods; ++i) {
4651       mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
4652       vtable->Set<false>(i, virtual_method);
4653       virtual_method->SetMethodIndex(i & 0xFFFF);
4654     }
4655     klass->SetVTable(vtable.Get());
4656   }
4657   return true;
4658 }
4659 
LinkInterfaceMethods(Handle<mirror::Class> klass,Handle<mirror::ObjectArray<mirror::Class>> interfaces)4660 bool ClassLinker::LinkInterfaceMethods(Handle<mirror::Class> klass,
4661                                        Handle<mirror::ObjectArray<mirror::Class>> interfaces) {
4662   Thread* const self = Thread::Current();
4663   Runtime* const runtime = Runtime::Current();
4664   // Set the imt table to be all conflicts by default.
4665   klass->SetImTable(runtime->GetDefaultImt());
4666   size_t super_ifcount;
4667   if (klass->HasSuperClass()) {
4668     super_ifcount = klass->GetSuperClass()->GetIfTableCount();
4669   } else {
4670     super_ifcount = 0;
4671   }
4672   uint32_t num_interfaces =
4673       interfaces.Get() == nullptr ? klass->NumDirectInterfaces() : interfaces->GetLength();
4674   size_t ifcount = super_ifcount + num_interfaces;
4675   for (size_t i = 0; i < num_interfaces; i++) {
4676     mirror::Class* interface =
4677         interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4678             interfaces->Get(i);
4679     ifcount += interface->GetIfTableCount();
4680   }
4681   if (ifcount == 0) {
4682     // Class implements no interfaces.
4683     DCHECK_EQ(klass->GetIfTableCount(), 0);
4684     DCHECK(klass->GetIfTable() == nullptr);
4685     return true;
4686   }
4687   if (ifcount == super_ifcount) {
4688     // Class implements same interfaces as parent, are any of these not marker interfaces?
4689     bool has_non_marker_interface = false;
4690     mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
4691     for (size_t i = 0; i < ifcount; ++i) {
4692       if (super_iftable->GetMethodArrayCount(i) > 0) {
4693         has_non_marker_interface = true;
4694         break;
4695       }
4696     }
4697     if (!has_non_marker_interface) {
4698       // Class just inherits marker interfaces from parent so recycle parent's iftable.
4699       klass->SetIfTable(super_iftable);
4700       return true;
4701     }
4702   }
4703   StackHandleScope<4> hs(self);
4704   Handle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
4705   if (UNLIKELY(iftable.Get() == nullptr)) {
4706     CHECK(self->IsExceptionPending());  // OOME.
4707     return false;
4708   }
4709   if (super_ifcount != 0) {
4710     mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
4711     for (size_t i = 0; i < super_ifcount; i++) {
4712       mirror::Class* super_interface = super_iftable->GetInterface(i);
4713       iftable->SetInterface(i, super_interface);
4714     }
4715   }
4716   // Flatten the interface inheritance hierarchy.
4717   size_t idx = super_ifcount;
4718   for (size_t i = 0; i < num_interfaces; i++) {
4719     mirror::Class* interface =
4720         interfaces.Get() == nullptr ? mirror::Class::GetDirectInterface(self, klass, i) :
4721             interfaces->Get(i);
4722     DCHECK(interface != nullptr);
4723     if (!interface->IsInterface()) {
4724       std::string temp;
4725       ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4726                                         PrettyDescriptor(klass.Get()).c_str(),
4727                                         PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4728       return false;
4729     }
4730     // Check if interface is already in iftable
4731     bool duplicate = false;
4732     for (size_t j = 0; j < idx; j++) {
4733       mirror::Class* existing_interface = iftable->GetInterface(j);
4734       if (existing_interface == interface) {
4735         duplicate = true;
4736         break;
4737       }
4738     }
4739     if (!duplicate) {
4740       // Add this non-duplicate interface.
4741       iftable->SetInterface(idx++, interface);
4742       // Add this interface's non-duplicate super-interfaces.
4743       for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
4744         mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
4745         bool super_duplicate = false;
4746         for (size_t k = 0; k < idx; k++) {
4747           mirror::Class* existing_interface = iftable->GetInterface(k);
4748           if (existing_interface == super_interface) {
4749             super_duplicate = true;
4750             break;
4751           }
4752         }
4753         if (!super_duplicate) {
4754           iftable->SetInterface(idx++, super_interface);
4755         }
4756       }
4757     }
4758   }
4759   // Shrink iftable in case duplicates were found
4760   if (idx < ifcount) {
4761     iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
4762     if (UNLIKELY(iftable.Get() == nullptr)) {
4763       CHECK(self->IsExceptionPending());  // OOME.
4764       return false;
4765     }
4766     ifcount = idx;
4767   } else {
4768     CHECK_EQ(idx, ifcount);
4769   }
4770   klass->SetIfTable(iftable.Get());
4771 
4772   // If we're an interface, we don't need the vtable pointers, so we're done.
4773   if (klass->IsInterface()) {
4774     return true;
4775   }
4776   // Allocate imtable
4777   bool imtable_changed = false;
4778   Handle<mirror::ObjectArray<mirror::ArtMethod>> imtable(
4779       hs.NewHandle(AllocArtMethodArray(self, mirror::Class::kImtSize)));
4780   if (UNLIKELY(imtable.Get() == nullptr)) {
4781     CHECK(self->IsExceptionPending());  // OOME.
4782     return false;
4783   }
4784   MethodHelper interface_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4785   MethodHelper vtable_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4786   std::vector<mirror::ArtMethod*> miranda_list;
4787   for (size_t i = 0; i < ifcount; ++i) {
4788     size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
4789     if (num_methods > 0) {
4790       StackHandleScope<2> hs(self);
4791       Handle<mirror::ObjectArray<mirror::ArtMethod>>
4792           method_array(hs.NewHandle(AllocArtMethodArray(self, num_methods)));
4793       if (UNLIKELY(method_array.Get() == nullptr)) {
4794         CHECK(self->IsExceptionPending());  // OOME.
4795         return false;
4796       }
4797       iftable->SetMethodArray(i, method_array.Get());
4798       Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4799           hs.NewHandle(klass->GetVTableDuringLinking()));
4800       for (size_t j = 0; j < num_methods; ++j) {
4801         mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
4802         interface_mh.ChangeMethod(interface_method);
4803         int32_t k;
4804         // For each method listed in the interface's method list, find the
4805         // matching method in our class's method list.  We want to favor the
4806         // subclass over the superclass, which just requires walking
4807         // back from the end of the vtable.  (This only matters if the
4808         // superclass defines a private method and this class redefines
4809         // it -- otherwise it would use the same vtable slot.  In .dex files
4810         // those don't end up in the virtual method table, so it shouldn't
4811         // matter which direction we go.  We walk it backward anyway.)
4812         for (k = vtable->GetLength() - 1; k >= 0; --k) {
4813           mirror::ArtMethod* vtable_method = vtable->Get(k);
4814           vtable_mh.ChangeMethod(vtable_method);
4815           if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
4816             if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
4817               ThrowIllegalAccessError(
4818                   klass.Get(),
4819                   "Method '%s' implementing interface method '%s' is not public",
4820                   PrettyMethod(vtable_method).c_str(),
4821                   PrettyMethod(interface_method).c_str());
4822               return false;
4823             }
4824             method_array->Set<false>(j, vtable_method);
4825             // Place method in imt if entry is empty, place conflict otherwise.
4826             uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
4827             if (imtable->Get(imt_index) == nullptr) {
4828               imtable->Set<false>(imt_index, vtable_method);
4829               imtable_changed = true;
4830             } else {
4831               imtable->Set<false>(imt_index, runtime->GetImtConflictMethod());
4832             }
4833             break;
4834           }
4835         }
4836         if (k < 0) {
4837           StackHandleScope<1> hs(self);
4838           auto miranda_method = hs.NewHandle<mirror::ArtMethod>(nullptr);
4839           for (mirror::ArtMethod* mir_method : miranda_list) {
4840             vtable_mh.ChangeMethod(mir_method);
4841             if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
4842               miranda_method.Assign(mir_method);
4843               break;
4844             }
4845           }
4846           if (miranda_method.Get() == nullptr) {
4847             // Point the interface table at a phantom slot.
4848             miranda_method.Assign(down_cast<mirror::ArtMethod*>(interface_method->Clone(self)));
4849             if (UNLIKELY(miranda_method.Get() == nullptr)) {
4850               CHECK(self->IsExceptionPending());  // OOME.
4851               return false;
4852             }
4853             // TODO: If a methods move then the miranda_list may hold stale references.
4854             miranda_list.push_back(miranda_method.Get());
4855           }
4856           method_array->Set<false>(j, miranda_method.Get());
4857         }
4858       }
4859     }
4860   }
4861   if (imtable_changed) {
4862     // Fill in empty entries in interface method table with conflict.
4863     mirror::ArtMethod* imt_conflict_method = runtime->GetImtConflictMethod();
4864     for (size_t i = 0; i < mirror::Class::kImtSize; i++) {
4865       if (imtable->Get(i) == nullptr) {
4866         imtable->Set<false>(i, imt_conflict_method);
4867       }
4868     }
4869     klass->SetImTable(imtable.Get());
4870   }
4871   if (!miranda_list.empty()) {
4872     int old_method_count = klass->NumVirtualMethods();
4873     int new_method_count = old_method_count + miranda_list.size();
4874     mirror::ObjectArray<mirror::ArtMethod>* virtuals;
4875     if (old_method_count == 0) {
4876       virtuals = AllocArtMethodArray(self, new_method_count);
4877     } else {
4878       virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
4879     }
4880     if (UNLIKELY(virtuals == nullptr)) {
4881       CHECK(self->IsExceptionPending());  // OOME.
4882       return false;
4883     }
4884     klass->SetVirtualMethods(virtuals);
4885 
4886     StackHandleScope<1> hs(self);
4887     Handle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
4888         hs.NewHandle(klass->GetVTableDuringLinking()));
4889     CHECK(vtable.Get() != nullptr);
4890     int old_vtable_count = vtable->GetLength();
4891     int new_vtable_count = old_vtable_count + miranda_list.size();
4892     vtable.Assign(vtable->CopyOf(self, new_vtable_count));
4893     if (UNLIKELY(vtable.Get() == nullptr)) {
4894       CHECK(self->IsExceptionPending());  // OOME.
4895       return false;
4896     }
4897     for (size_t i = 0; i < miranda_list.size(); ++i) {
4898       mirror::ArtMethod* method = miranda_list[i];
4899       // Leave the declaring class alone as type indices are relative to it
4900       method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
4901       method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
4902       klass->SetVirtualMethod(old_method_count + i, method);
4903       vtable->Set<false>(old_vtable_count + i, method);
4904     }
4905     // TODO: do not assign to the vtable field until it is fully constructed.
4906     klass->SetVTable(vtable.Get());
4907   }
4908 
4909   mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
4910   for (int i = 0; i < vtable->GetLength(); ++i) {
4911     CHECK(vtable->Get(i) != nullptr);
4912   }
4913 
4914 //  klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
4915 
4916   return true;
4917 }
4918 
LinkInstanceFields(Handle<mirror::Class> klass)4919 bool ClassLinker::LinkInstanceFields(Handle<mirror::Class> klass) {
4920   CHECK(klass.Get() != nullptr);
4921   return LinkFields(klass, false, nullptr);
4922 }
4923 
LinkStaticFields(Handle<mirror::Class> klass,size_t * class_size)4924 bool ClassLinker::LinkStaticFields(Handle<mirror::Class> klass, size_t* class_size) {
4925   CHECK(klass.Get() != nullptr);
4926   return LinkFields(klass, true, class_size);
4927 }
4928 
4929 struct LinkFieldsComparator {
SHARED_LOCKS_REQUIREDart::LinkFieldsComparator4930   explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4931   }
4932   // No thread safety analysis as will be called from STL. Checked lock held in constructor.
operator ()art::LinkFieldsComparator4933   bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
4934       NO_THREAD_SAFETY_ANALYSIS {
4935     // First come reference fields, then 64-bit, and finally 32-bit
4936     Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
4937     Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
4938     if (type1 != type2) {
4939       bool is_primitive1 = type1 != Primitive::kPrimNot;
4940       bool is_primitive2 = type2 != Primitive::kPrimNot;
4941       bool is64bit1 = is_primitive1 && (type1 == Primitive::kPrimLong ||
4942                                         type1 == Primitive::kPrimDouble);
4943       bool is64bit2 = is_primitive2 && (type2 == Primitive::kPrimLong ||
4944                                         type2 == Primitive::kPrimDouble);
4945       int order1 = !is_primitive1 ? 0 : (is64bit1 ? 1 : 2);
4946       int order2 = !is_primitive2 ? 0 : (is64bit2 ? 1 : 2);
4947       if (order1 != order2) {
4948         return order1 < order2;
4949       }
4950     }
4951     // same basic group? then sort by string.
4952     return strcmp(field1->GetName(), field2->GetName()) < 0;
4953   }
4954 };
4955 
LinkFields(Handle<mirror::Class> klass,bool is_static,size_t * class_size)4956 bool ClassLinker::LinkFields(Handle<mirror::Class> klass, bool is_static, size_t* class_size) {
4957   size_t num_fields =
4958       is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
4959 
4960   mirror::ObjectArray<mirror::ArtField>* fields =
4961       is_static ? klass->GetSFields() : klass->GetIFields();
4962 
4963   // Initialize field_offset
4964   MemberOffset field_offset(0);
4965   if (is_static) {
4966     uint32_t base = sizeof(mirror::Class);  // Static fields come after the class.
4967     if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4968       // Static fields come after the embedded tables.
4969       base = mirror::Class::ComputeClassSize(true, klass->GetVTableDuringLinking()->GetLength(),
4970                                              0, 0, 0);
4971     }
4972     field_offset = MemberOffset(base);
4973   } else {
4974     mirror::Class* super_class = klass->GetSuperClass();
4975     if (super_class != nullptr) {
4976       CHECK(super_class->IsResolved())
4977           << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
4978       field_offset = MemberOffset(super_class->GetObjectSize());
4979     }
4980   }
4981 
4982   CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
4983 
4984   // we want a relatively stable order so that adding new fields
4985   // minimizes disruption of C++ version such as Class and Method.
4986   std::deque<mirror::ArtField*> grouped_and_sorted_fields;
4987   for (size_t i = 0; i < num_fields; i++) {
4988     mirror::ArtField* f = fields->Get(i);
4989     CHECK(f != nullptr) << PrettyClass(klass.Get());
4990     grouped_and_sorted_fields.push_back(f);
4991   }
4992   std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
4993             LinkFieldsComparator());
4994 
4995   // References should be at the front.
4996   size_t current_field = 0;
4997   size_t num_reference_fields = 0;
4998   for (; current_field < num_fields; current_field++) {
4999     mirror::ArtField* field = grouped_and_sorted_fields.front();
5000     Primitive::Type type = field->GetTypeAsPrimitiveType();
5001     bool isPrimitive = type != Primitive::kPrimNot;
5002     if (isPrimitive) {
5003       break;  // past last reference, move on to the next phase
5004     }
5005     grouped_and_sorted_fields.pop_front();
5006     num_reference_fields++;
5007     fields->Set<false>(current_field, field);
5008     field->SetOffset(field_offset);
5009     field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
5010   }
5011 
5012   // Now we want to pack all of the double-wide fields together.  If
5013   // we're not aligned, though, we want to shuffle one 32-bit field
5014   // into place.  If we can't find one, we'll have to pad it.
5015   if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
5016     for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
5017       mirror::ArtField* field = grouped_and_sorted_fields[i];
5018       Primitive::Type type = field->GetTypeAsPrimitiveType();
5019       CHECK(type != Primitive::kPrimNot) << PrettyField(field);  // should be primitive types
5020       if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
5021         continue;
5022       }
5023       fields->Set<false>(current_field++, field);
5024       field->SetOffset(field_offset);
5025       // drop the consumed field
5026       grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
5027       break;
5028     }
5029     // whether we found a 32-bit field for padding or not, we advance
5030     field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
5031   }
5032 
5033   // Alignment is good, shuffle any double-wide fields forward, and
5034   // finish assigning field offsets to all fields.
5035   DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()))
5036       << PrettyClass(klass.Get());
5037   while (!grouped_and_sorted_fields.empty()) {
5038     mirror::ArtField* field = grouped_and_sorted_fields.front();
5039     grouped_and_sorted_fields.pop_front();
5040     Primitive::Type type = field->GetTypeAsPrimitiveType();
5041     CHECK(type != Primitive::kPrimNot) << PrettyField(field);  // should be primitive types
5042     fields->Set<false>(current_field, field);
5043     field->SetOffset(field_offset);
5044     field_offset = MemberOffset(field_offset.Uint32Value() +
5045                                 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
5046                                  ? sizeof(uint64_t)
5047                                  : sizeof(uint32_t)));
5048     current_field++;
5049   }
5050 
5051   // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
5052   if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
5053     // We know there are no non-reference fields in the Reference classes, and we know
5054     // that 'referent' is alphabetically last, so this is easy...
5055     CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
5056     CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
5057     --num_reference_fields;
5058   }
5059 
5060   if (kIsDebugBuild) {
5061     // Make sure that all reference fields appear before
5062     // non-reference fields, and all double-wide fields are aligned.
5063     bool seen_non_ref = false;
5064     for (size_t i = 0; i < num_fields; i++) {
5065       mirror::ArtField* field = fields->Get(i);
5066       if (false) {  // enable to debug field layout
5067         LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5068                     << " class=" << PrettyClass(klass.Get())
5069                     << " field=" << PrettyField(field)
5070                     << " offset="
5071                     << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()));
5072       }
5073       Primitive::Type type = field->GetTypeAsPrimitiveType();
5074       bool is_primitive = type != Primitive::kPrimNot;
5075       if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5076           strcmp("referent", field->GetName()) == 0) {
5077         is_primitive = true;  // We lied above, so we have to expect a lie here.
5078       }
5079       if (is_primitive) {
5080         if (!seen_non_ref) {
5081           seen_non_ref = true;
5082           DCHECK_EQ(num_reference_fields, i) << PrettyField(field);
5083         }
5084       } else {
5085         DCHECK(!seen_non_ref) << PrettyField(field);
5086       }
5087     }
5088     if (!seen_non_ref) {
5089       DCHECK_EQ(num_fields, num_reference_fields) << PrettyClass(klass.Get());
5090     }
5091   }
5092 
5093   size_t size = field_offset.Uint32Value();
5094   // Update klass
5095   if (is_static) {
5096     klass->SetNumReferenceStaticFields(num_reference_fields);
5097     *class_size = size;
5098   } else {
5099     klass->SetNumReferenceInstanceFields(num_reference_fields);
5100     if (!klass->IsVariableSize()) {
5101       std::string temp;
5102       DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5103       size_t previous_size = klass->GetObjectSize();
5104       if (previous_size != 0) {
5105         // Make sure that we didn't originally have an incorrect size.
5106         CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5107       }
5108       klass->SetObjectSize(size);
5109     }
5110   }
5111   return true;
5112 }
5113 
5114 //  Set the bitmap of reference offsets, refOffsets, from the ifields
5115 //  list.
CreateReferenceInstanceOffsets(Handle<mirror::Class> klass)5116 void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
5117   uint32_t reference_offsets = 0;
5118   mirror::Class* super_class = klass->GetSuperClass();
5119   if (super_class != nullptr) {
5120     reference_offsets = super_class->GetReferenceInstanceOffsets();
5121     // If our superclass overflowed, we don't stand a chance.
5122     if (reference_offsets == CLASS_WALK_SUPER) {
5123       klass->SetReferenceInstanceOffsets(reference_offsets);
5124       return;
5125     }
5126   }
5127   CreateReferenceOffsets(klass, false, reference_offsets);
5128 }
5129 
CreateReferenceStaticOffsets(Handle<mirror::Class> klass)5130 void ClassLinker::CreateReferenceStaticOffsets(Handle<mirror::Class> klass) {
5131   CreateReferenceOffsets(klass, true, 0);
5132 }
5133 
CreateReferenceOffsets(Handle<mirror::Class> klass,bool is_static,uint32_t reference_offsets)5134 void ClassLinker::CreateReferenceOffsets(Handle<mirror::Class> klass, bool is_static,
5135                                          uint32_t reference_offsets) {
5136   size_t num_reference_fields =
5137       is_static ? klass->NumReferenceStaticFieldsDuringLinking()
5138                 : klass->NumReferenceInstanceFieldsDuringLinking();
5139   mirror::ObjectArray<mirror::ArtField>* fields =
5140       is_static ? klass->GetSFields() : klass->GetIFields();
5141   // All of the fields that contain object references are guaranteed
5142   // to be at the beginning of the fields list.
5143   for (size_t i = 0; i < num_reference_fields; ++i) {
5144     // Note that byte_offset is the offset from the beginning of
5145     // object, not the offset into instance data
5146     mirror::ArtField* field = fields->Get(i);
5147     MemberOffset byte_offset = field->GetOffsetDuringLinking();
5148     CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
5149     if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
5150       uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
5151       CHECK_NE(new_bit, 0U);
5152       reference_offsets |= new_bit;
5153     } else {
5154       reference_offsets = CLASS_WALK_SUPER;
5155       break;
5156     }
5157   }
5158   // Update fields in klass
5159   if (is_static) {
5160     klass->SetReferenceStaticOffsets(reference_offsets);
5161   } else {
5162     klass->SetReferenceInstanceOffsets(reference_offsets);
5163   }
5164 }
5165 
ResolveString(const DexFile & dex_file,uint32_t string_idx,Handle<mirror::DexCache> dex_cache)5166 mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
5167                                            Handle<mirror::DexCache> dex_cache) {
5168   DCHECK(dex_cache.Get() != nullptr);
5169   mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
5170   if (resolved != nullptr) {
5171     return resolved;
5172   }
5173   uint32_t utf16_length;
5174   const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
5175   mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
5176   dex_cache->SetResolvedString(string_idx, string);
5177   return string;
5178 }
5179 
ResolveType(const DexFile & dex_file,uint16_t type_idx,mirror::Class * referrer)5180 mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
5181                                         mirror::Class* referrer) {
5182   StackHandleScope<2> hs(Thread::Current());
5183   Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5184   Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
5185   return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5186 }
5187 
ResolveType(const DexFile & dex_file,uint16_t type_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)5188 mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
5189                                         Handle<mirror::DexCache> dex_cache,
5190                                         Handle<mirror::ClassLoader> class_loader) {
5191   DCHECK(dex_cache.Get() != nullptr);
5192   mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
5193   if (resolved == nullptr) {
5194     Thread* self = Thread::Current();
5195     const char* descriptor = dex_file.StringByTypeIdx(type_idx);
5196     resolved = FindClass(self, descriptor, class_loader);
5197     if (resolved != nullptr) {
5198       // TODO: we used to throw here if resolved's class loader was not the
5199       //       boot class loader. This was to permit different classes with the
5200       //       same name to be loaded simultaneously by different loaders
5201       dex_cache->SetResolvedType(type_idx, resolved);
5202     } else {
5203       CHECK(self->IsExceptionPending())
5204           << "Expected pending exception for failed resolution of: " << descriptor;
5205       // Convert a ClassNotFoundException to a NoClassDefFoundError.
5206       StackHandleScope<1> hs(self);
5207       Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
5208       if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
5209         DCHECK(resolved == nullptr);  // No Handle needed to preserve resolved.
5210         self->ClearException();
5211         ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
5212         self->GetException(nullptr)->SetCause(cause.Get());
5213       }
5214     }
5215   }
5216   DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
5217           << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
5218   return resolved;
5219 }
5220 
ResolveMethod(const DexFile & dex_file,uint32_t method_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,Handle<mirror::ArtMethod> referrer,InvokeType type)5221 mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
5222                                               Handle<mirror::DexCache> dex_cache,
5223                                               Handle<mirror::ClassLoader> class_loader,
5224                                               Handle<mirror::ArtMethod> referrer,
5225                                               InvokeType type) {
5226   DCHECK(dex_cache.Get() != nullptr);
5227   // Check for hit in the dex cache.
5228   mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
5229   if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
5230     return resolved;
5231   }
5232   // Fail, get the declaring class.
5233   const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
5234   mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
5235   if (klass == nullptr) {
5236     DCHECK(Thread::Current()->IsExceptionPending());
5237     return nullptr;
5238   }
5239   // Scan using method_idx, this saves string compares but will only hit for matching dex
5240   // caches/files.
5241   switch (type) {
5242     case kDirect:  // Fall-through.
5243     case kStatic:
5244       resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
5245       break;
5246     case kInterface:
5247       resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
5248       DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
5249       break;
5250     case kSuper:  // Fall-through.
5251     case kVirtual:
5252       resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
5253       break;
5254     default:
5255       LOG(FATAL) << "Unreachable - invocation type: " << type;
5256   }
5257   if (resolved == nullptr) {
5258     // Search by name, which works across dex files.
5259     const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5260     const Signature signature = dex_file.GetMethodSignature(method_id);
5261     switch (type) {
5262       case kDirect:  // Fall-through.
5263       case kStatic:
5264         resolved = klass->FindDirectMethod(name, signature);
5265         break;
5266       case kInterface:
5267         resolved = klass->FindInterfaceMethod(name, signature);
5268         DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
5269         break;
5270       case kSuper:  // Fall-through.
5271       case kVirtual:
5272         resolved = klass->FindVirtualMethod(name, signature);
5273         break;
5274     }
5275   }
5276   // If we found a method, check for incompatible class changes.
5277   if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
5278     // Be a good citizen and update the dex cache to speed subsequent calls.
5279     dex_cache->SetResolvedMethod(method_idx, resolved);
5280     return resolved;
5281   } else {
5282     // If we had a method, it's an incompatible-class-change error.
5283     if (resolved != nullptr) {
5284       ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5285     } else {
5286       // We failed to find the method which means either an access error, an incompatible class
5287       // change, or no such method. First try to find the method among direct and virtual methods.
5288       const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5289       const Signature signature = dex_file.GetMethodSignature(method_id);
5290       switch (type) {
5291         case kDirect:
5292         case kStatic:
5293           resolved = klass->FindVirtualMethod(name, signature);
5294           // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5295           //       have had a resolved method before, which triggers the "true" branch above.
5296           break;
5297         case kInterface:
5298         case kVirtual:
5299         case kSuper:
5300           resolved = klass->FindDirectMethod(name, signature);
5301           break;
5302       }
5303 
5304       // If we found something, check that it can be accessed by the referrer.
5305       if (resolved != nullptr && referrer.Get() != nullptr) {
5306         mirror::Class* methods_class = resolved->GetDeclaringClass();
5307         mirror::Class* referring_class = referrer->GetDeclaringClass();
5308         if (!referring_class->CanAccess(methods_class)) {
5309           ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5310                                                         resolved, type);
5311           return nullptr;
5312         } else if (!referring_class->CanAccessMember(methods_class,
5313                                                      resolved->GetAccessFlags())) {
5314           ThrowIllegalAccessErrorMethod(referring_class, resolved);
5315           return nullptr;
5316         }
5317       }
5318 
5319       // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5320       // methods and throw if we find the method there. If we find nothing, throw a
5321       // NoSuchMethodError.
5322       switch (type) {
5323         case kDirect:
5324         case kStatic:
5325           if (resolved != nullptr) {
5326             ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5327           } else {
5328             resolved = klass->FindInterfaceMethod(name, signature);
5329             if (resolved != nullptr) {
5330               ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5331             } else {
5332               ThrowNoSuchMethodError(type, klass, name, signature);
5333             }
5334           }
5335           break;
5336         case kInterface:
5337           if (resolved != nullptr) {
5338             ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5339           } else {
5340             resolved = klass->FindVirtualMethod(name, signature);
5341             if (resolved != nullptr) {
5342               ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5343             } else {
5344               ThrowNoSuchMethodError(type, klass, name, signature);
5345             }
5346           }
5347           break;
5348         case kSuper:
5349           if (resolved != nullptr) {
5350             ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5351           } else {
5352             ThrowNoSuchMethodError(type, klass, name, signature);
5353           }
5354           break;
5355         case kVirtual:
5356           if (resolved != nullptr) {
5357             ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5358           } else {
5359             resolved = klass->FindInterfaceMethod(name, signature);
5360             if (resolved != nullptr) {
5361               ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5362             } else {
5363               ThrowNoSuchMethodError(type, klass, name, signature);
5364             }
5365           }
5366           break;
5367       }
5368     }
5369     DCHECK(Thread::Current()->IsExceptionPending());
5370     return nullptr;
5371   }
5372 }
5373 
ResolveField(const DexFile & dex_file,uint32_t field_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader,bool is_static)5374 mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
5375                                             Handle<mirror::DexCache> dex_cache,
5376                                             Handle<mirror::ClassLoader> class_loader,
5377                                             bool is_static) {
5378   DCHECK(dex_cache.Get() != nullptr);
5379   mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
5380   if (resolved != nullptr) {
5381     return resolved;
5382   }
5383   const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
5384   Thread* const self = Thread::Current();
5385   StackHandleScope<1> hs(self);
5386   Handle<mirror::Class> klass(
5387       hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
5388   if (klass.Get() == nullptr) {
5389     DCHECK(Thread::Current()->IsExceptionPending());
5390     return nullptr;
5391   }
5392 
5393   if (is_static) {
5394     resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
5395   } else {
5396     resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
5397   }
5398 
5399   if (resolved == nullptr) {
5400     const char* name = dex_file.GetFieldName(field_id);
5401     const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5402     if (is_static) {
5403       resolved = mirror::Class::FindStaticField(self, klass, name, type);
5404     } else {
5405       resolved = klass->FindInstanceField(name, type);
5406     }
5407     if (resolved == nullptr) {
5408       ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
5409       return nullptr;
5410     }
5411   }
5412   dex_cache->SetResolvedField(field_idx, resolved);
5413   return resolved;
5414 }
5415 
ResolveFieldJLS(const DexFile & dex_file,uint32_t field_idx,Handle<mirror::DexCache> dex_cache,Handle<mirror::ClassLoader> class_loader)5416 mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
5417                                                uint32_t field_idx,
5418                                                Handle<mirror::DexCache> dex_cache,
5419                                                Handle<mirror::ClassLoader> class_loader) {
5420   DCHECK(dex_cache.Get() != nullptr);
5421   mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
5422   if (resolved != nullptr) {
5423     return resolved;
5424   }
5425   const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
5426   Thread* self = Thread::Current();
5427   StackHandleScope<1> hs(self);
5428   Handle<mirror::Class> klass(
5429       hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
5430   if (klass.Get() == nullptr) {
5431     DCHECK(Thread::Current()->IsExceptionPending());
5432     return nullptr;
5433   }
5434 
5435   StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5436   StringPiece type(dex_file.StringDataByIdx(
5437       dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
5438   resolved = mirror::Class::FindField(self, klass, name, type);
5439   if (resolved != nullptr) {
5440     dex_cache->SetResolvedField(field_idx, resolved);
5441   } else {
5442     ThrowNoSuchFieldError("", klass.Get(), type, name);
5443   }
5444   return resolved;
5445 }
5446 
MethodShorty(uint32_t method_idx,mirror::ArtMethod * referrer,uint32_t * length)5447 const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
5448                                       uint32_t* length) {
5449   mirror::Class* declaring_class = referrer->GetDeclaringClass();
5450   mirror::DexCache* dex_cache = declaring_class->GetDexCache();
5451   const DexFile& dex_file = *dex_cache->GetDexFile();
5452   const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
5453   return dex_file.GetMethodShorty(method_id, length);
5454 }
5455 
DumpAllClasses(int flags)5456 void ClassLinker::DumpAllClasses(int flags) {
5457   if (dex_cache_image_class_lookup_required_) {
5458     MoveImageClassesToClassTable();
5459   }
5460   // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5461   // lock held, because it might need to resolve a field's type, which would try to take the lock.
5462   std::vector<mirror::Class*> all_classes;
5463   {
5464     ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
5465     for (std::pair<const size_t, GcRoot<mirror::Class> >& it : class_table_) {
5466       mirror::Class* klass = it.second.Read();
5467       all_classes.push_back(klass);
5468     }
5469   }
5470 
5471   for (size_t i = 0; i < all_classes.size(); ++i) {
5472     all_classes[i]->DumpClass(std::cerr, flags);
5473   }
5474 }
5475 
DumpForSigQuit(std::ostream & os)5476 void ClassLinker::DumpForSigQuit(std::ostream& os) {
5477   if (dex_cache_image_class_lookup_required_) {
5478     MoveImageClassesToClassTable();
5479   }
5480   ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
5481   os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
5482 }
5483 
NumLoadedClasses()5484 size_t ClassLinker::NumLoadedClasses() {
5485   if (dex_cache_image_class_lookup_required_) {
5486     MoveImageClassesToClassTable();
5487   }
5488   ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
5489   return class_table_.size();
5490 }
5491 
GetClassesLockOwner()5492 pid_t ClassLinker::GetClassesLockOwner() {
5493   return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
5494 }
5495 
GetDexLockOwner()5496 pid_t ClassLinker::GetDexLockOwner() {
5497   return dex_lock_.GetExclusiveOwnerTid();
5498 }
5499 
SetClassRoot(ClassRoot class_root,mirror::Class * klass)5500 void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
5501   DCHECK(!init_done_);
5502 
5503   DCHECK(klass != nullptr);
5504   DCHECK(klass->GetClassLoader() == nullptr);
5505 
5506   mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
5507   DCHECK(class_roots != nullptr);
5508   DCHECK(class_roots->Get(class_root) == nullptr);
5509   class_roots->Set<false>(class_root, klass);
5510 }
5511 
5512 }  // namespace art
5513