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