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