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