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