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