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