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