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