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