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