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