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