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