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