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