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