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