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