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