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