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