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