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