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