class_linker.cc revision 2d7210188805292e463be4bcf7a133b654d7e0ea
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  if (class_loader->GetClass() !=
2064      soa.Decode<mirror::Class*>(WellKnownClasses::dalvik_system_PathClassLoader) ||
2065      class_loader->GetParent()->GetClass() !=
2066          soa.Decode<mirror::Class*>(WellKnownClasses::java_lang_BootClassLoader)) {
2067    return nullptr;
2068  }
2069  ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2070  // Check if this would be found in the parent boot class loader.
2071  if (pair.second != nullptr) {
2072    mirror::Class* klass = LookupClass(self, descriptor, hash, nullptr);
2073    if (klass != nullptr) {
2074      return EnsureResolved(self, descriptor, klass);
2075    }
2076    klass = DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2077                        *pair.second);
2078    if (klass != nullptr) {
2079      return klass;
2080    }
2081    CHECK(self->IsExceptionPending()) << descriptor;
2082    self->ClearException();
2083  } else {
2084    // RegisterDexFile may allocate dex caches (and cause thread suspension).
2085    StackHandleScope<3> hs(self);
2086    // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
2087    // We need to get the DexPathList and loop through it.
2088    Handle<mirror::ArtField> cookie_field =
2089        hs.NewHandle(soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie));
2090    Handle<mirror::ArtField> dex_file_field =
2091        hs.NewHandle(
2092            soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile));
2093    mirror::Object* dex_path_list =
2094        soa.DecodeField(WellKnownClasses::dalvik_system_PathClassLoader_pathList)->
2095        GetObject(class_loader.Get());
2096    if (dex_path_list != nullptr && dex_file_field.Get() != nullptr &&
2097        cookie_field.Get() != nullptr) {
2098      // DexPathList has an array dexElements of Elements[] which each contain a dex file.
2099      mirror::Object* dex_elements_obj =
2100          soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
2101          GetObject(dex_path_list);
2102      // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
2103      // at the mCookie which is a DexFile vector.
2104      if (dex_elements_obj != nullptr) {
2105        Handle<mirror::ObjectArray<mirror::Object>> dex_elements =
2106            hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>());
2107        for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
2108          mirror::Object* element = dex_elements->GetWithoutChecks(i);
2109          if (element == nullptr) {
2110            // Should never happen, fall back to java code to throw a NPE.
2111            break;
2112          }
2113          mirror::Object* dex_file = dex_file_field->GetObject(element);
2114          if (dex_file != nullptr) {
2115            const uint64_t cookie = cookie_field->GetLong(dex_file);
2116            auto* dex_files =
2117                reinterpret_cast<std::vector<const DexFile*>*>(static_cast<uintptr_t>(cookie));
2118            if (dex_files == nullptr) {
2119              // This should never happen so log a warning.
2120              LOG(WARNING) << "Null DexFile::mCookie for " << descriptor;
2121              break;
2122            }
2123            for (const DexFile* cp_dex_file : *dex_files) {
2124              const DexFile::ClassDef* dex_class_def = cp_dex_file->FindClassDef(descriptor, hash);
2125              if (dex_class_def != nullptr) {
2126                RegisterDexFile(*cp_dex_file);
2127                mirror::Class* klass = DefineClass(self, descriptor, hash, class_loader,
2128                                                   *cp_dex_file, *dex_class_def);
2129                if (klass == nullptr) {
2130                  CHECK(self->IsExceptionPending()) << descriptor;
2131                  self->ClearException();
2132                  return nullptr;
2133                }
2134                return klass;
2135              }
2136            }
2137          }
2138        }
2139      }
2140    }
2141  }
2142  return nullptr;
2143}
2144
2145mirror::Class* ClassLinker::FindClass(Thread* self, const char* descriptor,
2146                                      Handle<mirror::ClassLoader> class_loader) {
2147  DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
2148  DCHECK(self != nullptr);
2149  self->AssertNoPendingException();
2150  if (descriptor[1] == '\0') {
2151    // only the descriptors of primitive types should be 1 character long, also avoid class lookup
2152    // for primitive classes that aren't backed by dex files.
2153    return FindPrimitiveClass(descriptor[0]);
2154  }
2155  const size_t hash = ComputeModifiedUtf8Hash(descriptor);
2156  // Find the class in the loaded classes table.
2157  mirror::Class* klass = LookupClass(self, descriptor, hash, class_loader.Get());
2158  if (klass != nullptr) {
2159    return EnsureResolved(self, descriptor, klass);
2160  }
2161  // Class is not yet loaded.
2162  if (descriptor[0] == '[') {
2163    return CreateArrayClass(self, descriptor, hash, class_loader);
2164  } else if (class_loader.Get() == nullptr) {
2165    // The boot class loader, search the boot class path.
2166    ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2167    if (pair.second != nullptr) {
2168      return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2169                         *pair.second);
2170    } else {
2171      // The boot class loader is searched ahead of the application class loader, failures are
2172      // expected and will be wrapped in a ClassNotFoundException. Use the pre-allocated error to
2173      // trigger the chaining with a proper stack trace.
2174      mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2175      self->SetException(ThrowLocation(), pre_allocated);
2176      return nullptr;
2177    }
2178  } else if (Runtime::Current()->UseCompileTimeClassPath()) {
2179    // First try with the bootstrap class loader.
2180    if (class_loader.Get() != nullptr) {
2181      klass = LookupClass(self, descriptor, hash, nullptr);
2182      if (klass != nullptr) {
2183        return EnsureResolved(self, descriptor, klass);
2184      }
2185    }
2186    // If the lookup failed search the boot class path. We don't perform a recursive call to avoid
2187    // a NoClassDefFoundError being allocated.
2188    ClassPathEntry pair = FindInClassPath(descriptor, hash, boot_class_path_);
2189    if (pair.second != nullptr) {
2190      return DefineClass(self, descriptor, hash, NullHandle<mirror::ClassLoader>(), *pair.first,
2191                         *pair.second);
2192    }
2193    // Next try the compile time class path.
2194    const std::vector<const DexFile*>* class_path;
2195    {
2196      ScopedObjectAccessUnchecked soa(self);
2197      ScopedLocalRef<jobject> jclass_loader(soa.Env(),
2198                                            soa.AddLocalReference<jobject>(class_loader.Get()));
2199      class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
2200    }
2201    pair = FindInClassPath(descriptor, hash, *class_path);
2202    if (pair.second != nullptr) {
2203      return DefineClass(self, descriptor, hash, class_loader, *pair.first, *pair.second);
2204    } else {
2205      // Use the pre-allocated NCDFE at compile time to avoid wasting time constructing exceptions.
2206      mirror::Throwable* pre_allocated = Runtime::Current()->GetPreAllocatedNoClassDefFoundError();
2207      self->SetException(ThrowLocation(), pre_allocated);
2208      return nullptr;
2209    }
2210  } else {
2211    ScopedObjectAccessUnchecked soa(self);
2212    mirror::Class* cp_klass = FindClassInPathClassLoader(soa, self, descriptor, hash,
2213                                                         class_loader);
2214    if (cp_klass != nullptr) {
2215      return cp_klass;
2216    }
2217    ScopedLocalRef<jobject> class_loader_object(soa.Env(),
2218                                                soa.AddLocalReference<jobject>(class_loader.Get()));
2219    std::string class_name_string(DescriptorToDot(descriptor));
2220    ScopedLocalRef<jobject> result(soa.Env(), nullptr);
2221    {
2222      ScopedThreadStateChange tsc(self, kNative);
2223      ScopedLocalRef<jobject> class_name_object(soa.Env(),
2224                                                soa.Env()->NewStringUTF(class_name_string.c_str()));
2225      if (class_name_object.get() == nullptr) {
2226        DCHECK(self->IsExceptionPending());  // OOME.
2227        return nullptr;
2228      }
2229      CHECK(class_loader_object.get() != nullptr);
2230      result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
2231                                               WellKnownClasses::java_lang_ClassLoader_loadClass,
2232                                               class_name_object.get()));
2233    }
2234    if (self->IsExceptionPending()) {
2235      // If the ClassLoader threw, pass that exception up.
2236      return nullptr;
2237    } else if (result.get() == nullptr) {
2238      // broken loader - throw NPE to be compatible with Dalvik
2239      ThrowNullPointerException(nullptr, StringPrintf("ClassLoader.loadClass returned null for %s",
2240                                                      class_name_string.c_str()).c_str());
2241      return nullptr;
2242    } else {
2243      // success, return mirror::Class*
2244      return soa.Decode<mirror::Class*>(result.get());
2245    }
2246  }
2247  UNREACHABLE();
2248}
2249
2250mirror::Class* ClassLinker::DefineClass(Thread* self, const char* descriptor, size_t hash,
2251                                        Handle<mirror::ClassLoader> class_loader,
2252                                        const DexFile& dex_file,
2253                                        const DexFile::ClassDef& dex_class_def) {
2254  StackHandleScope<3> hs(self);
2255  auto klass = hs.NewHandle<mirror::Class>(nullptr);
2256
2257  // Load the class from the dex file.
2258  if (UNLIKELY(!init_done_)) {
2259    // finish up init of hand crafted class_roots_
2260    if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
2261      klass.Assign(GetClassRoot(kJavaLangObject));
2262    } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
2263      klass.Assign(GetClassRoot(kJavaLangClass));
2264    } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
2265      klass.Assign(GetClassRoot(kJavaLangString));
2266    } else if (strcmp(descriptor, "Ljava/lang/ref/Reference;") == 0) {
2267      klass.Assign(GetClassRoot(kJavaLangRefReference));
2268    } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
2269      klass.Assign(GetClassRoot(kJavaLangDexCache));
2270    } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
2271      klass.Assign(GetClassRoot(kJavaLangReflectArtField));
2272    } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
2273      klass.Assign(GetClassRoot(kJavaLangReflectArtMethod));
2274    }
2275  }
2276
2277  if (klass.Get() == nullptr) {
2278    // Allocate a class with the status of not ready.
2279    // Interface object should get the right size here. Regular class will
2280    // figure out the right size later and be replaced with one of the right
2281    // size when the class becomes resolved.
2282    klass.Assign(AllocClass(self, SizeOfClassWithoutEmbeddedTables(dex_file, dex_class_def)));
2283  }
2284  if (UNLIKELY(klass.Get() == nullptr)) {
2285    CHECK(self->IsExceptionPending());  // Expect an OOME.
2286    return nullptr;
2287  }
2288  klass->SetDexCache(FindDexCache(dex_file));
2289  LoadClass(self, dex_file, dex_class_def, klass, class_loader.Get());
2290  ObjectLock<mirror::Class> lock(self, klass);
2291  if (self->IsExceptionPending()) {
2292    // An exception occured during load, set status to erroneous while holding klass' lock in case
2293    // notification is necessary.
2294    if (!klass->IsErroneous()) {
2295      klass->SetStatus(mirror::Class::kStatusError, self);
2296    }
2297    return nullptr;
2298  }
2299  klass->SetClinitThreadId(self->GetTid());
2300
2301  // Add the newly loaded class to the loaded classes table.
2302  mirror::Class* existing = InsertClass(descriptor, klass.Get(), hash);
2303  if (existing != nullptr) {
2304    // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
2305    // this thread to block.
2306    return EnsureResolved(self, descriptor, existing);
2307  }
2308
2309  // Finish loading (if necessary) by finding parents
2310  CHECK(!klass->IsLoaded());
2311  if (!LoadSuperAndInterfaces(klass, dex_file)) {
2312    // Loading failed.
2313    if (!klass->IsErroneous()) {
2314      klass->SetStatus(mirror::Class::kStatusError, self);
2315    }
2316    return nullptr;
2317  }
2318  CHECK(klass->IsLoaded());
2319  // Link the class (if necessary)
2320  CHECK(!klass->IsResolved());
2321  // TODO: Use fast jobjects?
2322  auto interfaces = hs.NewHandle<mirror::ObjectArray<mirror::Class>>(nullptr);
2323
2324  mirror::Class* new_class = nullptr;
2325  if (!LinkClass(self, descriptor, klass, interfaces, &new_class)) {
2326    // Linking failed.
2327    if (!klass->IsErroneous()) {
2328      klass->SetStatus(mirror::Class::kStatusError, self);
2329    }
2330    return nullptr;
2331  }
2332  self->AssertNoPendingException();
2333  CHECK(new_class != nullptr) << descriptor;
2334  CHECK(new_class->IsResolved()) << descriptor;
2335
2336  Handle<mirror::Class> new_class_h(hs.NewHandle(new_class));
2337
2338  /*
2339   * We send CLASS_PREPARE events to the debugger from here.  The
2340   * definition of "preparation" is creating the static fields for a
2341   * class and initializing them to the standard default values, but not
2342   * executing any code (that comes later, during "initialization").
2343   *
2344   * We did the static preparation in LinkClass.
2345   *
2346   * The class has been prepared and resolved but possibly not yet verified
2347   * at this point.
2348   */
2349  Dbg::PostClassPrepare(new_class_h.Get());
2350
2351  return new_class_h.Get();
2352}
2353
2354uint32_t ClassLinker::SizeOfClassWithoutEmbeddedTables(const DexFile& dex_file,
2355                                                       const DexFile::ClassDef& dex_class_def) {
2356  const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
2357  size_t num_ref = 0;
2358  size_t num_8 = 0;
2359  size_t num_16 = 0;
2360  size_t num_32 = 0;
2361  size_t num_64 = 0;
2362  if (class_data != nullptr) {
2363    for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
2364      const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
2365      const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
2366      char c = descriptor[0];
2367      switch (c) {
2368        case 'L':
2369        case '[':
2370          num_ref++;
2371          break;
2372        case 'J':
2373        case 'D':
2374          num_64++;
2375          break;
2376        case 'I':
2377        case 'F':
2378          num_32++;
2379          break;
2380        case 'S':
2381        case 'C':
2382          num_16++;
2383          break;
2384        case 'B':
2385        case 'Z':
2386          num_8++;
2387          break;
2388        default:
2389          LOG(FATAL) << "Unknown descriptor: " << c;
2390      }
2391    }
2392  }
2393  return mirror::Class::ComputeClassSize(false, 0, num_8, num_16, num_32, num_64, num_ref);
2394}
2395
2396OatFile::OatClass ClassLinker::FindOatClass(const DexFile& dex_file, uint16_t class_def_idx,
2397                                            bool* found) {
2398  DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
2399  const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
2400  if (oat_dex_file == nullptr) {
2401    *found = false;
2402    return OatFile::OatClass::Invalid();
2403  }
2404  *found = true;
2405  return oat_dex_file->GetOatClass(class_def_idx);
2406}
2407
2408static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
2409                                                 uint32_t method_idx) {
2410  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
2411  const uint8_t* class_data = dex_file.GetClassData(class_def);
2412  CHECK(class_data != nullptr);
2413  ClassDataItemIterator it(dex_file, class_data);
2414  // Skip fields
2415  while (it.HasNextStaticField()) {
2416    it.Next();
2417  }
2418  while (it.HasNextInstanceField()) {
2419    it.Next();
2420  }
2421  // Process methods
2422  size_t class_def_method_index = 0;
2423  while (it.HasNextDirectMethod()) {
2424    if (it.GetMemberIndex() == method_idx) {
2425      return class_def_method_index;
2426    }
2427    class_def_method_index++;
2428    it.Next();
2429  }
2430  while (it.HasNextVirtualMethod()) {
2431    if (it.GetMemberIndex() == method_idx) {
2432      return class_def_method_index;
2433    }
2434    class_def_method_index++;
2435    it.Next();
2436  }
2437  DCHECK(!it.HasNext());
2438  LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
2439  return 0;
2440}
2441
2442const OatFile::OatMethod ClassLinker::FindOatMethodFor(mirror::ArtMethod* method, bool* found) {
2443  // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
2444  // method for direct methods (or virtual methods made direct).
2445  mirror::Class* declaring_class = method->GetDeclaringClass();
2446  size_t oat_method_index;
2447  if (method->IsStatic() || method->IsDirect()) {
2448    // Simple case where the oat method index was stashed at load time.
2449    oat_method_index = method->GetMethodIndex();
2450  } else {
2451    // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
2452    // by search for its position in the declared virtual methods.
2453    oat_method_index = declaring_class->NumDirectMethods();
2454    size_t end = declaring_class->NumVirtualMethods();
2455    bool found_virtual = false;
2456    for (size_t i = 0; i < end; i++) {
2457      // Check method index instead of identity in case of duplicate method definitions.
2458      if (method->GetDexMethodIndex() ==
2459          declaring_class->GetVirtualMethod(i)->GetDexMethodIndex()) {
2460        found_virtual = true;
2461        break;
2462      }
2463      oat_method_index++;
2464    }
2465    CHECK(found_virtual) << "Didn't find oat method index for virtual method: "
2466                         << PrettyMethod(method);
2467  }
2468  DCHECK_EQ(oat_method_index,
2469            GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
2470                                             method->GetDeclaringClass()->GetDexClassDefIndex(),
2471                                             method->GetDexMethodIndex()));
2472  OatFile::OatClass oat_class = FindOatClass(*declaring_class->GetDexCache()->GetDexFile(),
2473                                             declaring_class->GetDexClassDefIndex(),
2474                                             found);
2475  if (!(*found)) {
2476    return OatFile::OatMethod::Invalid();
2477  }
2478  return oat_class.GetOatMethod(oat_method_index);
2479}
2480
2481// Special case to get oat code without overwriting a trampoline.
2482const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
2483  CHECK(!method->IsAbstract()) << PrettyMethod(method);
2484  if (method->IsProxyMethod()) {
2485    return GetQuickProxyInvokeHandler();
2486  }
2487  bool found;
2488  OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2489  const void* result = nullptr;
2490  if (found) {
2491    result = oat_method.GetQuickCode();
2492  }
2493
2494  if (result == nullptr) {
2495    if (method->IsNative()) {
2496      // No code and native? Use generic trampoline.
2497      result = GetQuickGenericJniStub();
2498    } else if (method->IsPortableCompiled()) {
2499      // No code? Do we expect portable code?
2500      result = GetQuickToPortableBridge();
2501    } else {
2502      // No code? You must mean to go into the interpreter.
2503      result = GetQuickToInterpreterBridge();
2504    }
2505  }
2506  return result;
2507}
2508
2509const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
2510                                               bool* have_portable_code) {
2511  CHECK(!method->IsAbstract()) << PrettyMethod(method);
2512  *have_portable_code = false;
2513  if (method->IsProxyMethod()) {
2514    return GetPortableProxyInvokeHandler();
2515  }
2516  bool found;
2517  OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2518  const void* result = nullptr;
2519  const void* quick_code = nullptr;
2520  if (found) {
2521    result = oat_method.GetPortableCode();
2522    quick_code = oat_method.GetQuickCode();
2523  }
2524
2525  if (result == nullptr) {
2526    if (quick_code == nullptr) {
2527      // No code? You must mean to go into the interpreter.
2528      result = GetPortableToInterpreterBridge();
2529    } else {
2530      // No code? But there's quick code, so use a bridge.
2531      result = GetPortableToQuickBridge();
2532    }
2533  } else {
2534    *have_portable_code = true;
2535  }
2536  return result;
2537}
2538
2539const void* ClassLinker::GetOatMethodQuickCodeFor(mirror::ArtMethod* method) {
2540  if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2541    return nullptr;
2542  }
2543  bool found;
2544  OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2545  return found ? oat_method.GetQuickCode() : nullptr;
2546}
2547
2548const void* ClassLinker::GetOatMethodPortableCodeFor(mirror::ArtMethod* method) {
2549  if (method->IsNative() || method->IsAbstract() || method->IsProxyMethod()) {
2550    return nullptr;
2551  }
2552  bool found;
2553  OatFile::OatMethod oat_method = FindOatMethodFor(method, &found);
2554  return found ? oat_method.GetPortableCode() : nullptr;
2555}
2556
2557const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2558                                            uint32_t method_idx) {
2559  bool found;
2560  OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2561  if (!found) {
2562    return nullptr;
2563  }
2564  uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
2565  return oat_class.GetOatMethod(oat_method_idx).GetQuickCode();
2566}
2567
2568const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
2569                                               uint32_t method_idx) {
2570  bool found;
2571  OatFile::OatClass oat_class = FindOatClass(dex_file, class_def_idx, &found);
2572  if (!found) {
2573    return nullptr;
2574  }
2575  uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
2576  return oat_class.GetOatMethod(oat_method_idx).GetPortableCode();
2577}
2578
2579// Returns true if the method must run with interpreter, false otherwise.
2580static bool NeedsInterpreter(
2581    mirror::ArtMethod* method, const void* quick_code, const void* portable_code)
2582    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2583  if ((quick_code == nullptr) && (portable_code == nullptr)) {
2584    // No code: need interpreter.
2585    // May return true for native code, in the case of generic JNI
2586    // DCHECK(!method->IsNative());
2587    return true;
2588  }
2589#ifdef ART_SEA_IR_MODE
2590  ScopedObjectAccess soa(Thread::Current());
2591  if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
2592    LOG(INFO) << "Found " << PrettyMethod(method);
2593    return false;
2594  }
2595#endif
2596  // If interpreter mode is enabled, every method (except native and proxy) must
2597  // be run with interpreter.
2598  return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
2599         !method->IsNative() && !method->IsProxyMethod();
2600}
2601
2602void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
2603  DCHECK(klass->IsInitialized()) << PrettyDescriptor(klass);
2604  if (klass->NumDirectMethods() == 0) {
2605    return;  // No direct methods => no static methods.
2606  }
2607  Runtime* runtime = Runtime::Current();
2608  if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
2609    if (runtime->IsCompiler() || runtime->GetHeap()->HasImageSpace()) {
2610      return;  // OAT file unavailable.
2611    }
2612  }
2613
2614  const DexFile& dex_file = klass->GetDexFile();
2615  const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
2616  CHECK(dex_class_def != nullptr);
2617  const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
2618  // There should always be class data if there were direct methods.
2619  CHECK(class_data != nullptr) << PrettyDescriptor(klass);
2620  ClassDataItemIterator it(dex_file, class_data);
2621  // Skip fields
2622  while (it.HasNextStaticField()) {
2623    it.Next();
2624  }
2625  while (it.HasNextInstanceField()) {
2626    it.Next();
2627  }
2628  bool has_oat_class;
2629  OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2630                                             &has_oat_class);
2631  // Link the code of methods skipped by LinkCode.
2632  for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
2633    mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
2634    if (!method->IsStatic()) {
2635      // Only update static methods.
2636      continue;
2637    }
2638    const void* portable_code = nullptr;
2639    const void* quick_code = nullptr;
2640    if (has_oat_class) {
2641      OatFile::OatMethod oat_method = oat_class.GetOatMethod(method_index);
2642      portable_code = oat_method.GetPortableCode();
2643      quick_code = oat_method.GetQuickCode();
2644    }
2645    const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
2646    bool have_portable_code = false;
2647    if (enter_interpreter) {
2648      // Use interpreter entry point.
2649      // Check whether the method is native, in which case it's generic JNI.
2650      if (quick_code == nullptr && portable_code == nullptr && method->IsNative()) {
2651        quick_code = GetQuickGenericJniStub();
2652        portable_code = GetPortableToQuickBridge();
2653      } else {
2654        portable_code = GetPortableToInterpreterBridge();
2655        quick_code = GetQuickToInterpreterBridge();
2656      }
2657    } else {
2658      if (portable_code == nullptr) {
2659        portable_code = GetPortableToQuickBridge();
2660      } else {
2661        have_portable_code = true;
2662      }
2663      if (quick_code == nullptr) {
2664        quick_code = GetQuickToPortableBridge();
2665      }
2666    }
2667    runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
2668                                                     have_portable_code);
2669  }
2670  // Ignore virtual methods on the iterator.
2671}
2672
2673void ClassLinker::LinkCode(Handle<mirror::ArtMethod> method,
2674                           const OatFile::OatClass* oat_class,
2675                           uint32_t class_def_method_index) {
2676  Runtime* runtime = Runtime::Current();
2677  if (runtime->IsCompiler()) {
2678    // The following code only applies to a non-compiler runtime.
2679    return;
2680  }
2681  // Method shouldn't have already been linked.
2682  DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2683  DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
2684  if (oat_class != nullptr) {
2685    // Every kind of method should at least get an invoke stub from the oat_method.
2686    // non-abstract methods also get their code pointers.
2687    const OatFile::OatMethod oat_method = oat_class->GetOatMethod(class_def_method_index);
2688    oat_method.LinkMethod(method.Get());
2689  }
2690
2691  // Install entry point from interpreter.
2692  bool enter_interpreter = NeedsInterpreter(method.Get(),
2693                                            method->GetEntryPointFromQuickCompiledCode(),
2694                                            method->GetEntryPointFromPortableCompiledCode());
2695  if (enter_interpreter && !method->IsNative()) {
2696    method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
2697  } else {
2698    method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
2699  }
2700
2701  if (method->IsAbstract()) {
2702    method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2703    method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2704    return;
2705  }
2706
2707  bool have_portable_code = false;
2708  if (method->IsStatic() && !method->IsConstructor()) {
2709    // For static methods excluding the class initializer, install the trampoline.
2710    // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
2711    // after initializing class (see ClassLinker::InitializeClass method).
2712    method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionStub());
2713    method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionStub());
2714  } else if (enter_interpreter) {
2715    if (!method->IsNative()) {
2716      // Set entry point from compiled code if there's no code or in interpreter only mode.
2717      method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
2718      method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
2719    } else {
2720      method->SetEntryPointFromQuickCompiledCode(GetQuickGenericJniStub());
2721      method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2722    }
2723  } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
2724    DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
2725    have_portable_code = true;
2726    method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
2727  } else {
2728    DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
2729    method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
2730  }
2731
2732  if (method->IsNative()) {
2733    // Unregistering restores the dlsym lookup stub.
2734    method->UnregisterNative();
2735
2736    if (enter_interpreter) {
2737      // We have a native method here without code. Then it should have either the generic JNI
2738      // trampoline as entrypoint (non-static), or the resolution trampoline (static).
2739      // TODO: this doesn't handle all the cases where trampolines may be installed.
2740      const void* entry_point = method->GetEntryPointFromQuickCompiledCode();
2741      DCHECK(IsQuickGenericJniStub(entry_point) || IsQuickResolutionStub(entry_point));
2742    }
2743  }
2744
2745  // Allow instrumentation its chance to hijack code.
2746  runtime->GetInstrumentation()->UpdateMethodsCode(method.Get(),
2747                                                   method->GetEntryPointFromQuickCompiledCode(),
2748                                                   method->GetEntryPointFromPortableCompiledCode(),
2749                                                   have_portable_code);
2750}
2751
2752
2753
2754void ClassLinker::LoadClass(Thread* self, const DexFile& dex_file,
2755                            const DexFile::ClassDef& dex_class_def,
2756                            Handle<mirror::Class> klass,
2757                            mirror::ClassLoader* class_loader) {
2758  CHECK(klass.Get() != nullptr);
2759  CHECK(klass->GetDexCache() != nullptr);
2760  CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
2761  const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
2762  CHECK(descriptor != nullptr);
2763
2764  klass->SetClass(GetClassRoot(kJavaLangClass));
2765  if (kUseBakerOrBrooksReadBarrier) {
2766    klass->AssertReadBarrierPointer();
2767  }
2768  uint32_t access_flags = dex_class_def.GetJavaAccessFlags();
2769  CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
2770  klass->SetAccessFlags(access_flags);
2771  klass->SetClassLoader(class_loader);
2772  DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
2773  klass->SetStatus(mirror::Class::kStatusIdx, nullptr);
2774
2775  klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
2776  klass->SetDexTypeIndex(dex_class_def.class_idx_);
2777
2778  const uint8_t* class_data = dex_file.GetClassData(dex_class_def);
2779  if (class_data == nullptr) {
2780    return;  // no fields or methods - for example a marker interface
2781  }
2782
2783
2784  bool has_oat_class = false;
2785  if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
2786    OatFile::OatClass oat_class = FindOatClass(dex_file, klass->GetDexClassDefIndex(),
2787                                               &has_oat_class);
2788    if (has_oat_class) {
2789      LoadClassMembers(self, dex_file, class_data, klass, &oat_class);
2790    }
2791  }
2792  if (!has_oat_class) {
2793    LoadClassMembers(self, dex_file, class_data, klass, nullptr);
2794  }
2795}
2796
2797void ClassLinker::LoadClassMembers(Thread* self, const DexFile& dex_file,
2798                                   const uint8_t* class_data,
2799                                   Handle<mirror::Class> klass,
2800                                   const OatFile::OatClass* oat_class) {
2801  // Load fields.
2802  ClassDataItemIterator it(dex_file, class_data);
2803  if (it.NumStaticFields() != 0) {
2804    mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
2805    if (UNLIKELY(statics == nullptr)) {
2806      CHECK(self->IsExceptionPending());  // OOME.
2807      return;
2808    }
2809    klass->SetSFields(statics);
2810  }
2811  if (it.NumInstanceFields() != 0) {
2812    mirror::ObjectArray<mirror::ArtField>* fields =
2813        AllocArtFieldArray(self, it.NumInstanceFields());
2814    if (UNLIKELY(fields == nullptr)) {
2815      CHECK(self->IsExceptionPending());  // OOME.
2816      return;
2817    }
2818    klass->SetIFields(fields);
2819  }
2820  for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2821    self->AllowThreadSuspension();
2822    StackHandleScope<1> hs(self);
2823    Handle<mirror::ArtField> sfield(hs.NewHandle(AllocArtField(self)));
2824    if (UNLIKELY(sfield.Get() == nullptr)) {
2825      CHECK(self->IsExceptionPending());  // OOME.
2826      return;
2827    }
2828    klass->SetStaticField(i, sfield.Get());
2829    LoadField(dex_file, it, klass, sfield);
2830  }
2831  for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
2832    self->AllowThreadSuspension();
2833    StackHandleScope<1> hs(self);
2834    Handle<mirror::ArtField> ifield(hs.NewHandle(AllocArtField(self)));
2835    if (UNLIKELY(ifield.Get() == nullptr)) {
2836      CHECK(self->IsExceptionPending());  // OOME.
2837      return;
2838    }
2839    klass->SetInstanceField(i, ifield.Get());
2840    LoadField(dex_file, it, klass, ifield);
2841  }
2842
2843  // Load methods.
2844  if (it.NumDirectMethods() != 0) {
2845    // TODO: append direct methods to class object
2846    mirror::ObjectArray<mirror::ArtMethod>* directs =
2847         AllocArtMethodArray(self, it.NumDirectMethods());
2848    if (UNLIKELY(directs == nullptr)) {
2849      CHECK(self->IsExceptionPending());  // OOME.
2850      return;
2851    }
2852    klass->SetDirectMethods(directs);
2853  }
2854  if (it.NumVirtualMethods() != 0) {
2855    // TODO: append direct methods to class object
2856    mirror::ObjectArray<mirror::ArtMethod>* virtuals =
2857        AllocArtMethodArray(self, it.NumVirtualMethods());
2858    if (UNLIKELY(virtuals == nullptr)) {
2859      CHECK(self->IsExceptionPending());  // OOME.
2860      return;
2861    }
2862    klass->SetVirtualMethods(virtuals);
2863  }
2864  size_t class_def_method_index = 0;
2865  uint32_t last_dex_method_index = DexFile::kDexNoIndex;
2866  size_t last_class_def_method_index = 0;
2867  for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
2868    self->AllowThreadSuspension();
2869    StackHandleScope<1> hs(self);
2870    Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2871    if (UNLIKELY(method.Get() == nullptr)) {
2872      CHECK(self->IsExceptionPending());  // OOME.
2873      return;
2874    }
2875    klass->SetDirectMethod(i, method.Get());
2876    LinkCode(method, oat_class, class_def_method_index);
2877    uint32_t it_method_index = it.GetMemberIndex();
2878    if (last_dex_method_index == it_method_index) {
2879      // duplicate case
2880      method->SetMethodIndex(last_class_def_method_index);
2881    } else {
2882      method->SetMethodIndex(class_def_method_index);
2883      last_dex_method_index = it_method_index;
2884      last_class_def_method_index = class_def_method_index;
2885    }
2886    class_def_method_index++;
2887  }
2888  for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
2889    self->AllowThreadSuspension();
2890    StackHandleScope<1> hs(self);
2891    Handle<mirror::ArtMethod> method(hs.NewHandle(LoadMethod(self, dex_file, it, klass)));
2892    if (UNLIKELY(method.Get() == nullptr)) {
2893      CHECK(self->IsExceptionPending());  // OOME.
2894      return;
2895    }
2896    klass->SetVirtualMethod(i, method.Get());
2897    DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
2898    LinkCode(method, oat_class, class_def_method_index);
2899    class_def_method_index++;
2900  }
2901  DCHECK(!it.HasNext());
2902}
2903
2904void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
2905                            Handle<mirror::Class> klass,
2906                            Handle<mirror::ArtField> dst) {
2907  uint32_t field_idx = it.GetMemberIndex();
2908  dst->SetDexFieldIndex(field_idx);
2909  dst->SetDeclaringClass(klass.Get());
2910  dst->SetAccessFlags(it.GetFieldAccessFlags());
2911}
2912
2913mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
2914                                           const ClassDataItemIterator& it,
2915                                           Handle<mirror::Class> klass) {
2916  uint32_t dex_method_idx = it.GetMemberIndex();
2917  const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
2918  const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
2919
2920  mirror::ArtMethod* dst = AllocArtMethod(self);
2921  if (UNLIKELY(dst == nullptr)) {
2922    CHECK(self->IsExceptionPending());  // OOME.
2923    return nullptr;
2924  }
2925  DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
2926
2927  ScopedAssertNoThreadSuspension ants(self, "LoadMethod");
2928  dst->SetDexMethodIndex(dex_method_idx);
2929  dst->SetDeclaringClass(klass.Get());
2930  dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
2931
2932  dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
2933  dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
2934  dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
2935
2936  uint32_t access_flags = it.GetMethodAccessFlags();
2937
2938  if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
2939    // Set finalizable flag on declaring class.
2940    if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
2941      // Void return type.
2942      if (klass->GetClassLoader() != nullptr) {  // All non-boot finalizer methods are flagged.
2943        klass->SetFinalizable();
2944      } else {
2945        std::string temp;
2946        const char* klass_descriptor = klass->GetDescriptor(&temp);
2947        // The Enum class declares a "final" finalize() method to prevent subclasses from
2948        // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
2949        // subclasses, so we exclude it here.
2950        // We also want to avoid setting the flag on Object, where we know that finalize() is
2951        // empty.
2952        if (strcmp(klass_descriptor, "Ljava/lang/Object;") != 0 &&
2953            strcmp(klass_descriptor, "Ljava/lang/Enum;") != 0) {
2954          klass->SetFinalizable();
2955        }
2956      }
2957    }
2958  } else if (method_name[0] == '<') {
2959    // Fix broken access flags for initializers. Bug 11157540.
2960    bool is_init = (strcmp("<init>", method_name) == 0);
2961    bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
2962    if (UNLIKELY(!is_init && !is_clinit)) {
2963      LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
2964    } else {
2965      if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
2966        LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
2967            << PrettyDescriptor(klass.Get()) << " in dex file " << dex_file.GetLocation();
2968        access_flags |= kAccConstructor;
2969      }
2970    }
2971  }
2972  dst->SetAccessFlags(access_flags);
2973
2974  return dst;
2975}
2976
2977void ClassLinker::AppendToBootClassPath(Thread* self, const DexFile& dex_file) {
2978  StackHandleScope<1> hs(self);
2979  Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
2980  CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
2981                                    << dex_file.GetLocation();
2982  AppendToBootClassPath(dex_file, dex_cache);
2983}
2984
2985void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
2986                                        Handle<mirror::DexCache> dex_cache) {
2987  CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
2988  boot_class_path_.push_back(&dex_file);
2989  RegisterDexFile(dex_file, dex_cache);
2990}
2991
2992bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) {
2993  dex_lock_.AssertSharedHeld(Thread::Current());
2994  for (size_t i = 0; i != dex_caches_.size(); ++i) {
2995    mirror::DexCache* dex_cache = GetDexCache(i);
2996    if (dex_cache->GetDexFile() == &dex_file) {
2997      return true;
2998    }
2999  }
3000  return false;
3001}
3002
3003bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) {
3004  ReaderMutexLock mu(Thread::Current(), dex_lock_);
3005  return IsDexFileRegisteredLocked(dex_file);
3006}
3007
3008void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
3009                                        Handle<mirror::DexCache> dex_cache) {
3010  dex_lock_.AssertExclusiveHeld(Thread::Current());
3011  CHECK(dex_cache.Get() != nullptr) << dex_file.GetLocation();
3012  CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
3013      << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
3014  dex_caches_.push_back(GcRoot<mirror::DexCache>(dex_cache.Get()));
3015  dex_cache->SetDexFile(&dex_file);
3016  if (log_new_dex_caches_roots_) {
3017    // TODO: This is not safe if we can remove dex caches.
3018    new_dex_cache_roots_.push_back(dex_caches_.size() - 1);
3019  }
3020}
3021
3022void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
3023  Thread* self = Thread::Current();
3024  {
3025    ReaderMutexLock mu(self, dex_lock_);
3026    if (IsDexFileRegisteredLocked(dex_file)) {
3027      return;
3028    }
3029  }
3030  // Don't alloc while holding the lock, since allocation may need to
3031  // suspend all threads and another thread may need the dex_lock_ to
3032  // get to a suspend point.
3033  StackHandleScope<1> hs(self);
3034  Handle<mirror::DexCache> dex_cache(hs.NewHandle(AllocDexCache(self, dex_file)));
3035  CHECK(dex_cache.Get() != nullptr) << "Failed to allocate dex cache for "
3036                                    << dex_file.GetLocation();
3037  {
3038    WriterMutexLock mu(self, dex_lock_);
3039    if (IsDexFileRegisteredLocked(dex_file)) {
3040      return;
3041    }
3042    RegisterDexFileLocked(dex_file, dex_cache);
3043  }
3044}
3045
3046void ClassLinker::RegisterDexFile(const DexFile& dex_file,
3047                                  Handle<mirror::DexCache> dex_cache) {
3048  WriterMutexLock mu(Thread::Current(), dex_lock_);
3049  RegisterDexFileLocked(dex_file, dex_cache);
3050}
3051
3052mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) {
3053  ReaderMutexLock mu(Thread::Current(), dex_lock_);
3054  // Search assuming unique-ness of dex file.
3055  for (size_t i = 0; i != dex_caches_.size(); ++i) {
3056    mirror::DexCache* dex_cache = GetDexCache(i);
3057    if (dex_cache->GetDexFile() == &dex_file) {
3058      return dex_cache;
3059    }
3060  }
3061  // Search matching by location name.
3062  std::string location(dex_file.GetLocation());
3063  for (size_t i = 0; i != dex_caches_.size(); ++i) {
3064    mirror::DexCache* dex_cache = GetDexCache(i);
3065    if (dex_cache->GetDexFile()->GetLocation() == location) {
3066      return dex_cache;
3067    }
3068  }
3069  // Failure, dump diagnostic and abort.
3070  for (size_t i = 0; i != dex_caches_.size(); ++i) {
3071    mirror::DexCache* dex_cache = GetDexCache(i);
3072    LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
3073  }
3074  LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
3075  return nullptr;
3076}
3077
3078void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) {
3079  ReaderMutexLock mu(Thread::Current(), dex_lock_);
3080  for (size_t i = 0; i != dex_caches_.size(); ++i) {
3081    mirror::DexCache* dex_cache = GetDexCache(i);
3082    dex_cache->Fixup(resolution_method);
3083  }
3084}
3085
3086mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
3087  mirror::Class* klass = AllocClass(self, mirror::Class::PrimitiveClassSize());
3088  if (UNLIKELY(klass == nullptr)) {
3089    return nullptr;
3090  }
3091  return InitializePrimitiveClass(klass, type);
3092}
3093
3094mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
3095                                                     Primitive::Type type) {
3096  CHECK(primitive_class != nullptr);
3097  // Must hold lock on object when initializing.
3098  Thread* self = Thread::Current();
3099  StackHandleScope<1> hs(self);
3100  Handle<mirror::Class> h_class(hs.NewHandle(primitive_class));
3101  ObjectLock<mirror::Class> lock(self, h_class);
3102  primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
3103  primitive_class->SetPrimitiveType(type);
3104  primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
3105  const char* descriptor = Primitive::Descriptor(type);
3106  mirror::Class* existing = InsertClass(descriptor, primitive_class,
3107                                        ComputeModifiedUtf8Hash(descriptor));
3108  CHECK(existing == nullptr) << "InitPrimitiveClass(" << type << ") failed";
3109  return primitive_class;
3110}
3111
3112// Create an array class (i.e. the class object for the array, not the
3113// array itself).  "descriptor" looks like "[C" or "[[[[B" or
3114// "[Ljava/lang/String;".
3115//
3116// If "descriptor" refers to an array of primitives, look up the
3117// primitive type's internally-generated class object.
3118//
3119// "class_loader" is the class loader of the class that's referring to
3120// us.  It's used to ensure that we're looking for the element type in
3121// the right context.  It does NOT become the class loader for the
3122// array class; that always comes from the base element class.
3123//
3124// Returns nullptr with an exception raised on failure.
3125mirror::Class* ClassLinker::CreateArrayClass(Thread* self, const char* descriptor, size_t hash,
3126                                             Handle<mirror::ClassLoader> class_loader) {
3127  // Identify the underlying component type
3128  CHECK_EQ('[', descriptor[0]);
3129  StackHandleScope<2> hs(self);
3130  MutableHandle<mirror::Class> component_type(hs.NewHandle(FindClass(self, descriptor + 1,
3131                                                                     class_loader)));
3132  if (component_type.Get() == nullptr) {
3133    DCHECK(self->IsExceptionPending());
3134    // We need to accept erroneous classes as component types.
3135    const size_t component_hash = ComputeModifiedUtf8Hash(descriptor + 1);
3136    component_type.Assign(LookupClass(self, descriptor + 1, component_hash, class_loader.Get()));
3137    if (component_type.Get() == nullptr) {
3138      DCHECK(self->IsExceptionPending());
3139      return nullptr;
3140    } else {
3141      self->ClearException();
3142    }
3143  }
3144  if (UNLIKELY(component_type->IsPrimitiveVoid())) {
3145    ThrowNoClassDefFoundError("Attempt to create array of void primitive type");
3146    return nullptr;
3147  }
3148  // See if the component type is already loaded.  Array classes are
3149  // always associated with the class loader of their underlying
3150  // element type -- an array of Strings goes with the loader for
3151  // java/lang/String -- so we need to look for it there.  (The
3152  // caller should have checked for the existence of the class
3153  // before calling here, but they did so with *their* class loader,
3154  // not the component type's loader.)
3155  //
3156  // If we find it, the caller adds "loader" to the class' initiating
3157  // loader list, which should prevent us from going through this again.
3158  //
3159  // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
3160  // are the same, because our caller (FindClass) just did the
3161  // lookup.  (Even if we get this wrong we still have correct behavior,
3162  // because we effectively do this lookup again when we add the new
3163  // class to the hash table --- necessary because of possible races with
3164  // other threads.)
3165  if (class_loader.Get() != component_type->GetClassLoader()) {
3166    mirror::Class* new_class = LookupClass(self, descriptor, hash, component_type->GetClassLoader());
3167    if (new_class != nullptr) {
3168      return new_class;
3169    }
3170  }
3171
3172  // Fill out the fields in the Class.
3173  //
3174  // It is possible to execute some methods against arrays, because
3175  // all arrays are subclasses of java_lang_Object_, so we need to set
3176  // up a vtable.  We can just point at the one in java_lang_Object_.
3177  //
3178  // Array classes are simple enough that we don't need to do a full
3179  // link step.
3180  auto new_class = hs.NewHandle<mirror::Class>(nullptr);
3181  if (UNLIKELY(!init_done_)) {
3182    // Classes that were hand created, ie not by FindSystemClass
3183    if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
3184      new_class.Assign(GetClassRoot(kClassArrayClass));
3185    } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
3186      new_class.Assign(GetClassRoot(kObjectArrayClass));
3187    } else if (strcmp(descriptor, GetClassRootDescriptor(kJavaLangStringArrayClass)) == 0) {
3188      new_class.Assign(GetClassRoot(kJavaLangStringArrayClass));
3189    } else if (strcmp(descriptor,
3190                      GetClassRootDescriptor(kJavaLangReflectArtMethodArrayClass)) == 0) {
3191      new_class.Assign(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
3192    } else if (strcmp(descriptor,
3193                      GetClassRootDescriptor(kJavaLangReflectArtFieldArrayClass)) == 0) {
3194      new_class.Assign(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
3195    } else if (strcmp(descriptor, "[C") == 0) {
3196      new_class.Assign(GetClassRoot(kCharArrayClass));
3197    } else if (strcmp(descriptor, "[I") == 0) {
3198      new_class.Assign(GetClassRoot(kIntArrayClass));
3199    }
3200  }
3201  if (new_class.Get() == nullptr) {
3202    new_class.Assign(AllocClass(self, mirror::Array::ClassSize()));
3203    if (new_class.Get() == nullptr) {
3204      return nullptr;
3205    }
3206    new_class->SetComponentType(component_type.Get());
3207  }
3208  ObjectLock<mirror::Class> lock(self, new_class);  // Must hold lock on object when initializing.
3209  DCHECK(new_class->GetComponentType() != nullptr);
3210  mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
3211  new_class->SetSuperClass(java_lang_Object);
3212  new_class->SetVTable(java_lang_Object->GetVTable());
3213  new_class->SetPrimitiveType(Primitive::kPrimNot);
3214  new_class->SetClassLoader(component_type->GetClassLoader());
3215  new_class->SetStatus(mirror::Class::kStatusLoaded, self);
3216  {
3217    StackHandleScope<mirror::Class::kImtSize> hs2(self,
3218                                                  Runtime::Current()->GetImtUnimplementedMethod());
3219    new_class->PopulateEmbeddedImtAndVTable(&hs2);
3220  }
3221  new_class->SetStatus(mirror::Class::kStatusInitialized, self);
3222  // don't need to set new_class->SetObjectSize(..)
3223  // because Object::SizeOf delegates to Array::SizeOf
3224
3225
3226  // All arrays have java/lang/Cloneable and java/io/Serializable as
3227  // interfaces.  We need to set that up here, so that stuff like
3228  // "instanceof" works right.
3229  //
3230  // Note: The GC could run during the call to FindSystemClass,
3231  // so we need to make sure the class object is GC-valid while we're in
3232  // there.  Do this by clearing the interface list so the GC will just
3233  // think that the entries are null.
3234
3235
3236  // Use the single, global copies of "interfaces" and "iftable"
3237  // (remember not to free them for arrays).
3238  {
3239    mirror::IfTable* array_iftable = array_iftable_.Read();
3240    CHECK(array_iftable != nullptr);
3241    new_class->SetIfTable(array_iftable);
3242  }
3243
3244  // Inherit access flags from the component type.
3245  int access_flags = new_class->GetComponentType()->GetAccessFlags();
3246  // Lose any implementation detail flags; in particular, arrays aren't finalizable.
3247  access_flags &= kAccJavaFlagsMask;
3248  // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
3249  // and remove "interface".
3250  access_flags |= kAccAbstract | kAccFinal;
3251  access_flags &= ~kAccInterface;
3252
3253  new_class->SetAccessFlags(access_flags);
3254
3255  mirror::Class* existing = InsertClass(descriptor, new_class.Get(), hash);
3256  if (existing == nullptr) {
3257    return new_class.Get();
3258  }
3259  // Another thread must have loaded the class after we
3260  // started but before we finished.  Abandon what we've
3261  // done.
3262  //
3263  // (Yes, this happens.)
3264
3265  return existing;
3266}
3267
3268mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
3269  switch (type) {
3270    case 'B':
3271      return GetClassRoot(kPrimitiveByte);
3272    case 'C':
3273      return GetClassRoot(kPrimitiveChar);
3274    case 'D':
3275      return GetClassRoot(kPrimitiveDouble);
3276    case 'F':
3277      return GetClassRoot(kPrimitiveFloat);
3278    case 'I':
3279      return GetClassRoot(kPrimitiveInt);
3280    case 'J':
3281      return GetClassRoot(kPrimitiveLong);
3282    case 'S':
3283      return GetClassRoot(kPrimitiveShort);
3284    case 'Z':
3285      return GetClassRoot(kPrimitiveBoolean);
3286    case 'V':
3287      return GetClassRoot(kPrimitiveVoid);
3288    default:
3289      break;
3290  }
3291  std::string printable_type(PrintableChar(type));
3292  ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
3293  return nullptr;
3294}
3295
3296mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
3297                                        size_t hash) {
3298  if (VLOG_IS_ON(class_linker)) {
3299    mirror::DexCache* dex_cache = klass->GetDexCache();
3300    std::string source;
3301    if (dex_cache != nullptr) {
3302      source += " from ";
3303      source += dex_cache->GetLocation()->ToModifiedUtf8();
3304    }
3305    LOG(INFO) << "Loaded class " << descriptor << source;
3306  }
3307  WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3308  mirror::Class* existing = LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
3309  if (existing != nullptr) {
3310    return existing;
3311  }
3312  if (kIsDebugBuild && !klass->IsTemp() && klass->GetClassLoader() == nullptr &&
3313      dex_cache_image_class_lookup_required_) {
3314    // Check a class loaded with the system class loader matches one in the image if the class
3315    // is in the image.
3316    existing = LookupClassFromImage(descriptor);
3317    if (existing != nullptr) {
3318      CHECK_EQ(klass, existing);
3319    }
3320  }
3321  VerifyObject(klass);
3322  class_table_.InsertWithHash(GcRoot<mirror::Class>(klass), hash);
3323  if (log_new_class_table_roots_) {
3324    new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
3325  }
3326  return nullptr;
3327}
3328
3329mirror::Class* ClassLinker::UpdateClass(const char* descriptor, mirror::Class* klass,
3330                                        size_t hash) {
3331  WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3332  auto existing_it = class_table_.FindWithHash(std::make_pair(descriptor, klass->GetClassLoader()),
3333                                               hash);
3334  if (existing_it == class_table_.end()) {
3335    CHECK(klass->IsProxyClass());
3336    return nullptr;
3337  }
3338
3339  mirror::Class* existing = existing_it->Read();
3340  CHECK_NE(existing, klass) << descriptor;
3341  CHECK(!existing->IsResolved()) << descriptor;
3342  CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusResolving) << descriptor;
3343
3344  CHECK(!klass->IsTemp()) << descriptor;
3345  if (kIsDebugBuild && klass->GetClassLoader() == nullptr &&
3346      dex_cache_image_class_lookup_required_) {
3347    // Check a class loaded with the system class loader matches one in the image if the class
3348    // is in the image.
3349    existing = LookupClassFromImage(descriptor);
3350    if (existing != nullptr) {
3351      CHECK_EQ(klass, existing) << descriptor;
3352    }
3353  }
3354  VerifyObject(klass);
3355
3356  // Update the element in the hash set.
3357  *existing_it = GcRoot<mirror::Class>(klass);
3358  if (log_new_class_table_roots_) {
3359    new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
3360  }
3361
3362  return existing;
3363}
3364
3365bool ClassLinker::RemoveClass(const char* descriptor, mirror::ClassLoader* class_loader) {
3366  WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3367  auto pair = std::make_pair(descriptor, class_loader);
3368  auto it = class_table_.Find(pair);
3369  if (it != class_table_.end()) {
3370    class_table_.Erase(it);
3371    return true;
3372  }
3373  it = pre_zygote_class_table_.Find(pair);
3374  if (it != pre_zygote_class_table_.end()) {
3375    pre_zygote_class_table_.Erase(it);
3376    return true;
3377  }
3378  return false;
3379}
3380
3381mirror::Class* ClassLinker::LookupClass(Thread* self, const char* descriptor, size_t hash,
3382                                        mirror::ClassLoader* class_loader) {
3383  {
3384    ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
3385    mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
3386    if (result != nullptr) {
3387      return result;
3388    }
3389  }
3390  if (class_loader != nullptr || !dex_cache_image_class_lookup_required_) {
3391    return nullptr;
3392  } else {
3393    // Lookup failed but need to search dex_caches_.
3394    mirror::Class* result = LookupClassFromImage(descriptor);
3395    if (result != nullptr) {
3396      InsertClass(descriptor, result, hash);
3397    } else {
3398      // Searching the image dex files/caches failed, we don't want to get into this situation
3399      // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
3400      // classes into the class table.
3401      constexpr uint32_t kMaxFailedDexCacheLookups = 1000;
3402      if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
3403        MoveImageClassesToClassTable();
3404      }
3405    }
3406    return result;
3407  }
3408}
3409
3410mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
3411                                                       mirror::ClassLoader* class_loader,
3412                                                       size_t hash) {
3413  auto descriptor_pair = std::make_pair(descriptor, class_loader);
3414  auto it = pre_zygote_class_table_.FindWithHash(descriptor_pair, hash);
3415  if (it == pre_zygote_class_table_.end()) {
3416    it = class_table_.FindWithHash(descriptor_pair, hash);
3417    if (it == class_table_.end()) {
3418      return nullptr;
3419    }
3420  }
3421  return it->Read();
3422}
3423
3424static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
3425    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3426  gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
3427  CHECK(image != nullptr);
3428  mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
3429  return root->AsObjectArray<mirror::DexCache>();
3430}
3431
3432void ClassLinker::MoveImageClassesToClassTable() {
3433  Thread* self = Thread::Current();
3434  WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
3435  if (!dex_cache_image_class_lookup_required_) {
3436    return;  // All dex cache classes are already in the class table.
3437  }
3438  ScopedAssertNoThreadSuspension ants(self, "Moving image classes to class table");
3439  mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3440  std::string temp;
3441  for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
3442    mirror::DexCache* dex_cache = dex_caches->Get(i);
3443    mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
3444    for (int32_t j = 0; j < types->GetLength(); j++) {
3445      mirror::Class* klass = types->Get(j);
3446      if (klass != nullptr) {
3447        DCHECK(klass->GetClassLoader() == nullptr);
3448        const char* descriptor = klass->GetDescriptor(&temp);
3449        size_t hash = ComputeModifiedUtf8Hash(descriptor);
3450        mirror::Class* existing = LookupClassFromTableLocked(descriptor, nullptr, hash);
3451        if (existing != nullptr) {
3452          CHECK_EQ(existing, klass) << PrettyClassAndClassLoader(existing) << " != "
3453              << PrettyClassAndClassLoader(klass);
3454        } else {
3455          class_table_.Insert(GcRoot<mirror::Class>(klass));
3456          if (log_new_class_table_roots_) {
3457            new_class_roots_.push_back(GcRoot<mirror::Class>(klass));
3458          }
3459        }
3460      }
3461    }
3462  }
3463  dex_cache_image_class_lookup_required_ = false;
3464}
3465
3466void ClassLinker::MoveClassTableToPreZygote() {
3467  WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3468  DCHECK(pre_zygote_class_table_.Empty());
3469  pre_zygote_class_table_ = std::move(class_table_);
3470  class_table_.Clear();
3471}
3472
3473mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
3474  ScopedAssertNoThreadSuspension ants(Thread::Current(), "Image class lookup");
3475  mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
3476  for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
3477    mirror::DexCache* dex_cache = dex_caches->Get(i);
3478    const DexFile* dex_file = dex_cache->GetDexFile();
3479    // Try binary searching the string/type index.
3480    const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
3481    if (string_id != nullptr) {
3482      const DexFile::TypeId* type_id =
3483          dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
3484      if (type_id != nullptr) {
3485        uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
3486        mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
3487        if (klass != nullptr) {
3488          return klass;
3489        }
3490      }
3491    }
3492  }
3493  return nullptr;
3494}
3495
3496void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
3497  result.clear();
3498  if (dex_cache_image_class_lookup_required_) {
3499    MoveImageClassesToClassTable();
3500  }
3501  WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
3502  while (true) {
3503    auto it = class_table_.Find(descriptor);
3504    if (it == class_table_.end()) {
3505      break;
3506    }
3507    result.push_back(it->Read());
3508    class_table_.Erase(it);
3509  }
3510  for (mirror::Class* k : result) {
3511    class_table_.Insert(GcRoot<mirror::Class>(k));
3512  }
3513  size_t pre_zygote_start = result.size();
3514  // Now handle the pre zygote table.
3515  // Note: This dirties the pre-zygote table but shouldn't be an issue since LookupClasses is only
3516  // called from the debugger.
3517  while (true) {
3518    auto it = pre_zygote_class_table_.Find(descriptor);
3519    if (it == pre_zygote_class_table_.end()) {
3520      break;
3521    }
3522    result.push_back(it->Read());
3523    pre_zygote_class_table_.Erase(it);
3524  }
3525  for (size_t i = pre_zygote_start; i < result.size(); ++i) {
3526    pre_zygote_class_table_.Insert(GcRoot<mirror::Class>(result[i]));
3527  }
3528}
3529
3530void ClassLinker::VerifyClass(Thread* self, Handle<mirror::Class> klass) {
3531  // TODO: assert that the monitor on the Class is held
3532  ObjectLock<mirror::Class> lock(self, klass);
3533
3534  // Don't attempt to re-verify if already sufficiently verified.
3535  if (klass->IsVerified()) {
3536    EnsurePreverifiedMethods(klass);
3537    return;
3538  }
3539  if (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler()) {
3540    return;
3541  }
3542
3543  // The class might already be erroneous, for example at compile time if we attempted to verify
3544  // this class as a parent to another.
3545  if (klass->IsErroneous()) {
3546    ThrowEarlierClassFailure(klass.Get());
3547    return;
3548  }
3549
3550  if (klass->GetStatus() == mirror::Class::kStatusResolved) {
3551    klass->SetStatus(mirror::Class::kStatusVerifying, self);
3552  } else {
3553    CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
3554        << PrettyClass(klass.Get());
3555    CHECK(!Runtime::Current()->IsCompiler());
3556    klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
3557  }
3558
3559  // Skip verification if disabled.
3560  if (!Runtime::Current()->IsVerificationEnabled()) {
3561    klass->SetStatus(mirror::Class::kStatusVerified, self);
3562    EnsurePreverifiedMethods(klass);
3563    return;
3564  }
3565
3566  // Verify super class.
3567  StackHandleScope<2> hs(self);
3568  Handle<mirror::Class> super(hs.NewHandle(klass->GetSuperClass()));
3569  if (super.Get() != nullptr) {
3570    // Acquire lock to prevent races on verifying the super class.
3571    ObjectLock<mirror::Class> super_lock(self, super);
3572
3573    if (!super->IsVerified() && !super->IsErroneous()) {
3574      VerifyClass(self, super);
3575    }
3576    if (!super->IsCompileTimeVerified()) {
3577      std::string error_msg(
3578          StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
3579                       PrettyDescriptor(klass.Get()).c_str(),
3580                       PrettyDescriptor(super.Get()).c_str()));
3581      LOG(ERROR) << error_msg  << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
3582      Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
3583      if (cause.Get() != nullptr) {
3584        self->ClearException();
3585      }
3586      ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3587      if (cause.Get() != nullptr) {
3588        self->GetException(nullptr)->SetCause(cause.Get());
3589      }
3590      ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
3591      if (Runtime::Current()->IsCompiler()) {
3592        Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
3593      }
3594      klass->SetStatus(mirror::Class::kStatusError, self);
3595      return;
3596    }
3597  }
3598
3599  // Try to use verification information from the oat file, otherwise do runtime verification.
3600  const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
3601  mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
3602  bool preverified = VerifyClassUsingOatFile(dex_file, klass.Get(), oat_file_class_status);
3603  if (oat_file_class_status == mirror::Class::kStatusError) {
3604    VLOG(class_linker) << "Skipping runtime verification of erroneous class "
3605        << PrettyDescriptor(klass.Get()) << " in "
3606        << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
3607    ThrowVerifyError(klass.Get(), "Rejecting class %s because it failed compile-time verification",
3608                     PrettyDescriptor(klass.Get()).c_str());
3609    klass->SetStatus(mirror::Class::kStatusError, self);
3610    return;
3611  }
3612  verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
3613  std::string error_msg;
3614  if (!preverified) {
3615    verifier_failure = verifier::MethodVerifier::VerifyClass(self, klass.Get(),
3616                                                             Runtime::Current()->IsCompiler(),
3617                                                             &error_msg);
3618  }
3619  if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
3620    if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
3621      VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.Get())
3622          << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3623          << " because: " << error_msg;
3624    }
3625    self->AssertNoPendingException();
3626    // Make sure all classes referenced by catch blocks are resolved.
3627    ResolveClassExceptionHandlerTypes(dex_file, klass);
3628    if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
3629      // Even though there were no verifier failures we need to respect whether the super-class
3630      // was verified or requiring runtime reverification.
3631      if (super.Get() == nullptr || super->IsVerified()) {
3632        klass->SetStatus(mirror::Class::kStatusVerified, self);
3633      } else {
3634        CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
3635        klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
3636        // Pretend a soft failure occured so that we don't consider the class verified below.
3637        verifier_failure = verifier::MethodVerifier::kSoftFailure;
3638      }
3639    } else {
3640      CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
3641      // Soft failures at compile time should be retried at runtime. Soft
3642      // failures at runtime will be handled by slow paths in the generated
3643      // code. Set status accordingly.
3644      if (Runtime::Current()->IsCompiler()) {
3645        klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
3646      } else {
3647        klass->SetStatus(mirror::Class::kStatusVerified, self);
3648        // As this is a fake verified status, make sure the methods are _not_ marked preverified
3649        // later.
3650        klass->SetPreverified();
3651      }
3652    }
3653  } else {
3654    LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.Get())
3655        << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
3656        << " because: " << error_msg;
3657    self->AssertNoPendingException();
3658    ThrowVerifyError(klass.Get(), "%s", error_msg.c_str());
3659    klass->SetStatus(mirror::Class::kStatusError, self);
3660  }
3661  if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
3662    // Class is verified so we don't need to do any access check on its methods.
3663    // Let the interpreter know it by setting the kAccPreverified flag onto each
3664    // method.
3665    // Note: we're going here during compilation and at runtime. When we set the
3666    // kAccPreverified flag when compiling image classes, the flag is recorded
3667    // in the image and is set when loading the image.
3668    EnsurePreverifiedMethods(klass);
3669  }
3670}
3671
3672void ClassLinker::EnsurePreverifiedMethods(Handle<mirror::Class> klass) {
3673  if (!klass->IsPreverified()) {
3674    klass->SetPreverifiedFlagOnAllMethods();
3675    klass->SetPreverified();
3676  }
3677}
3678
3679bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
3680                                          mirror::Class::Status& oat_file_class_status) {
3681  // If we're compiling, we can only verify the class using the oat file if
3682  // we are not compiling the image or if the class we're verifying is not part of
3683  // the app.  In other words, we will only check for preverification of bootclasspath
3684  // classes.
3685  if (Runtime::Current()->IsCompiler()) {
3686    // Are we compiling the bootclasspath?
3687    if (!Runtime::Current()->UseCompileTimeClassPath()) {
3688      return false;
3689    }
3690    // We are compiling an app (not the image).
3691
3692    // Is this an app class? (I.e. not a bootclasspath class)
3693    if (klass->GetClassLoader() != nullptr) {
3694      return false;
3695    }
3696  }
3697
3698  const OatFile::OatDexFile* oat_dex_file = FindOpenedOatDexFileForDexFile(dex_file);
3699  // In case we run without an image there won't be a backing oat file.
3700  if (oat_dex_file == nullptr) {
3701    return false;
3702  }
3703
3704  uint16_t class_def_index = klass->GetDexClassDefIndex();
3705  oat_file_class_status = oat_dex_file->GetOatClass(class_def_index).GetStatus();
3706  if (oat_file_class_status == mirror::Class::kStatusVerified ||
3707      oat_file_class_status == mirror::Class::kStatusInitialized) {
3708      return true;
3709  }
3710  if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
3711    // Compile time verification failed with a soft error. Compile time verification can fail
3712    // because we have incomplete type information. Consider the following:
3713    // class ... {
3714    //   Foo x;
3715    //   .... () {
3716    //     if (...) {
3717    //       v1 gets assigned a type of resolved class Foo
3718    //     } else {
3719    //       v1 gets assigned a type of unresolved class Bar
3720    //     }
3721    //     iput x = v1
3722    // } }
3723    // when we merge v1 following the if-the-else it results in Conflict
3724    // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
3725    // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
3726    // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
3727    // at compile time).
3728    return false;
3729  }
3730  if (oat_file_class_status == mirror::Class::kStatusError) {
3731    // Compile time verification failed with a hard error. This is caused by invalid instructions
3732    // in the class. These errors are unrecoverable.
3733    return false;
3734  }
3735  if (oat_file_class_status == mirror::Class::kStatusNotReady) {
3736    // Status is uninitialized if we couldn't determine the status at compile time, for example,
3737    // not loading the class.
3738    // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
3739    // isn't a problem and this case shouldn't occur
3740    return false;
3741  }
3742  std::string temp;
3743  LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
3744             << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
3745             << klass->GetDescriptor(&temp);
3746
3747  return false;
3748}
3749
3750void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
3751                                                    Handle<mirror::Class> klass) {
3752  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
3753    ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
3754  }
3755  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
3756    ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
3757  }
3758}
3759
3760void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
3761                                                     mirror::ArtMethod* method) {
3762  // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
3763  const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
3764  if (code_item == nullptr) {
3765    return;  // native or abstract method
3766  }
3767  if (code_item->tries_size_ == 0) {
3768    return;  // nothing to process
3769  }
3770  const uint8_t* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
3771  uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
3772  ClassLinker* linker = Runtime::Current()->GetClassLinker();
3773  for (uint32_t idx = 0; idx < handlers_size; idx++) {
3774    CatchHandlerIterator iterator(handlers_ptr);
3775    for (; iterator.HasNext(); iterator.Next()) {
3776      // Ensure exception types are resolved so that they don't need resolution to be delivered,
3777      // unresolved exception types will be ignored by exception delivery
3778      if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
3779        mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
3780        if (exception_type == nullptr) {
3781          DCHECK(Thread::Current()->IsExceptionPending());
3782          Thread::Current()->ClearException();
3783        }
3784      }
3785    }
3786    handlers_ptr = iterator.EndDataPointer();
3787  }
3788}
3789
3790static void CheckProxyConstructor(mirror::ArtMethod* constructor);
3791static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
3792                             Handle<mirror::ArtMethod> prototype);
3793
3794mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccessAlreadyRunnable& soa, jstring name,
3795                                             jobjectArray interfaces, jobject loader,
3796                                             jobjectArray methods, jobjectArray throws) {
3797  Thread* self = soa.Self();
3798  StackHandleScope<8> hs(self);
3799  MutableHandle<mirror::Class> klass(hs.NewHandle(
3800      AllocClass(self, GetClassRoot(kJavaLangClass), sizeof(mirror::Class))));
3801  if (klass.Get() == nullptr) {
3802    CHECK(self->IsExceptionPending());  // OOME.
3803    return nullptr;
3804  }
3805  DCHECK(klass->GetClass() != nullptr);
3806  klass->SetObjectSize(sizeof(mirror::Proxy));
3807  // Set the class access flags incl. preverified, so we do not try to set the flag on the methods.
3808  klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal | kAccPreverified);
3809  klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
3810  DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
3811  klass->SetName(soa.Decode<mirror::String*>(name));
3812  mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
3813  klass->SetDexCache(proxy_class->GetDexCache());
3814  klass->SetStatus(mirror::Class::kStatusIdx, self);
3815
3816  // Instance fields are inherited, but we add a couple of static fields...
3817  {
3818    mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
3819    if (UNLIKELY(sfields == nullptr)) {
3820      CHECK(self->IsExceptionPending());  // OOME.
3821      return nullptr;
3822    }
3823    klass->SetSFields(sfields);
3824  }
3825  // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
3826  // our proxy, so Class.getInterfaces doesn't return the flattened set.
3827  Handle<mirror::ArtField> interfaces_sfield(hs.NewHandle(AllocArtField(self)));
3828  if (UNLIKELY(interfaces_sfield.Get() == nullptr)) {
3829    CHECK(self->IsExceptionPending());  // OOME.
3830    return nullptr;
3831  }
3832  klass->SetStaticField(0, interfaces_sfield.Get());
3833  interfaces_sfield->SetDexFieldIndex(0);
3834  interfaces_sfield->SetDeclaringClass(klass.Get());
3835  interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3836  // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
3837  Handle<mirror::ArtField> throws_sfield(hs.NewHandle(AllocArtField(self)));
3838  if (UNLIKELY(throws_sfield.Get() == nullptr)) {
3839    CHECK(self->IsExceptionPending());  // OOME.
3840    return nullptr;
3841  }
3842  klass->SetStaticField(1, throws_sfield.Get());
3843  throws_sfield->SetDexFieldIndex(1);
3844  throws_sfield->SetDeclaringClass(klass.Get());
3845  throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
3846
3847  // Proxies have 1 direct method, the constructor
3848  {
3849    mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
3850    if (UNLIKELY(directs == nullptr)) {
3851      CHECK(self->IsExceptionPending());  // OOME.
3852      return nullptr;
3853    }
3854    klass->SetDirectMethods(directs);
3855    mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
3856    if (UNLIKELY(constructor == nullptr)) {
3857      CHECK(self->IsExceptionPending());  // OOME.
3858      return nullptr;
3859    }
3860    klass->SetDirectMethod(0, constructor);
3861  }
3862
3863  // Create virtual method using specified prototypes.
3864  size_t num_virtual_methods =
3865      soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
3866  {
3867    mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self,
3868                                                                           num_virtual_methods);
3869    if (UNLIKELY(virtuals == nullptr)) {
3870      CHECK(self->IsExceptionPending());  // OOME.
3871      return nullptr;
3872    }
3873    klass->SetVirtualMethods(virtuals);
3874  }
3875  for (size_t i = 0; i < num_virtual_methods; ++i) {
3876    StackHandleScope<1> hs2(self);
3877    mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3878        soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
3879    Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3880    mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
3881    if (UNLIKELY(clone == nullptr)) {
3882      CHECK(self->IsExceptionPending());  // OOME.
3883      return nullptr;
3884    }
3885    klass->SetVirtualMethod(i, clone);
3886  }
3887
3888  klass->SetSuperClass(proxy_class);  // The super class is java.lang.reflect.Proxy
3889  klass->SetStatus(mirror::Class::kStatusLoaded, self);  // Now effectively in the loaded state.
3890  self->AssertNoPendingException();
3891
3892  std::string descriptor(GetDescriptorForProxy(klass.Get()));
3893  mirror::Class* new_class = nullptr;
3894  {
3895    // Must hold lock on object when resolved.
3896    ObjectLock<mirror::Class> resolution_lock(self, klass);
3897    // Link the fields and virtual methods, creating vtable and iftables
3898    Handle<mirror::ObjectArray<mirror::Class> > h_interfaces(
3899        hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces)));
3900    if (!LinkClass(self, descriptor.c_str(), klass, h_interfaces, &new_class)) {
3901      klass->SetStatus(mirror::Class::kStatusError, self);
3902      return nullptr;
3903    }
3904  }
3905
3906  CHECK(klass->IsRetired());
3907  CHECK_NE(klass.Get(), new_class);
3908  klass.Assign(new_class);
3909
3910  CHECK_EQ(interfaces_sfield->GetDeclaringClass(), new_class);
3911  interfaces_sfield->SetObject<false>(klass.Get(),
3912                                      soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3913  CHECK_EQ(throws_sfield->GetDeclaringClass(), new_class);
3914  throws_sfield->SetObject<false>(klass.Get(),
3915      soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
3916
3917  {
3918    // Lock on klass is released. Lock new class object.
3919    ObjectLock<mirror::Class> initialization_lock(self, klass);
3920    klass->SetStatus(mirror::Class::kStatusInitialized, self);
3921  }
3922
3923  // sanity checks
3924  if (kIsDebugBuild) {
3925    CHECK(klass->GetIFields() == nullptr);
3926    CheckProxyConstructor(klass->GetDirectMethod(0));
3927    for (size_t i = 0; i < num_virtual_methods; ++i) {
3928      StackHandleScope<2> hs2(self);
3929      mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
3930          soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
3931      Handle<mirror::ArtMethod> prototype(hs2.NewHandle(decoded_methods->Get(i)));
3932      Handle<mirror::ArtMethod> virtual_method(hs2.NewHandle(klass->GetVirtualMethod(i)));
3933      CheckProxyMethod(virtual_method, prototype);
3934    }
3935
3936    mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
3937    std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
3938                                                   decoded_name->ToModifiedUtf8().c_str()));
3939    CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
3940
3941    std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
3942                                               decoded_name->ToModifiedUtf8().c_str()));
3943    CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
3944
3945    CHECK_EQ(klass.Get()->GetInterfaces(),
3946             soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
3947    CHECK_EQ(klass.Get()->GetThrows(),
3948             soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class>>*>(throws));
3949  }
3950  mirror::Class* existing = InsertClass(descriptor.c_str(), klass.Get(),
3951                                        ComputeModifiedUtf8Hash(descriptor.c_str()));
3952  CHECK(existing == nullptr);
3953  return klass.Get();
3954}
3955
3956std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
3957  DCHECK(proxy_class->IsProxyClass());
3958  mirror::String* name = proxy_class->GetName();
3959  DCHECK(name != nullptr);
3960  return DotToDescriptor(name->ToModifiedUtf8().c_str());
3961}
3962
3963mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
3964                                                   mirror::ArtMethod* proxy_method) {
3965  DCHECK(proxy_class->IsProxyClass());
3966  DCHECK(proxy_method->IsProxyMethod());
3967  // Locate the dex cache of the original interface/Object
3968  mirror::DexCache* dex_cache = nullptr;
3969  {
3970    ReaderMutexLock mu(Thread::Current(), dex_lock_);
3971    for (size_t i = 0; i != dex_caches_.size(); ++i) {
3972      mirror::DexCache* a_dex_cache = GetDexCache(i);
3973      if (proxy_method->HasSameDexCacheResolvedTypes(a_dex_cache->GetResolvedTypes())) {
3974        dex_cache = a_dex_cache;
3975        break;
3976      }
3977    }
3978  }
3979  CHECK(dex_cache != nullptr);
3980  uint32_t method_idx = proxy_method->GetDexMethodIndex();
3981  mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
3982  CHECK(resolved_method != nullptr);
3983  return resolved_method;
3984}
3985
3986
3987mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
3988                                                       Handle<mirror::Class> klass,
3989                                                       mirror::Class* proxy_class) {
3990  // Create constructor for Proxy that must initialize h
3991  mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
3992      proxy_class->GetDirectMethods();
3993  CHECK_EQ(proxy_direct_methods->GetLength(), 16);
3994  mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
3995  // Ensure constructor is in dex cache so that we can use the dex cache to look up the overridden
3996  // constructor method.
3997  proxy_class->GetDexCache()->SetResolvedMethod(proxy_constructor->GetDexMethodIndex(),
3998                                                proxy_constructor);
3999  // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
4000  // code_ too)
4001  mirror::ArtMethod* constructor = down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
4002  if (constructor == nullptr) {
4003    CHECK(self->IsExceptionPending());  // OOME.
4004    return nullptr;
4005  }
4006  // Make this constructor public and fix the class to be our Proxy version
4007  constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
4008  constructor->SetDeclaringClass(klass.Get());
4009  return constructor;
4010}
4011
4012static void CheckProxyConstructor(mirror::ArtMethod* constructor)
4013    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4014  CHECK(constructor->IsConstructor());
4015  CHECK_STREQ(constructor->GetName(), "<init>");
4016  CHECK_STREQ(constructor->GetSignature().ToString().c_str(),
4017              "(Ljava/lang/reflect/InvocationHandler;)V");
4018  DCHECK(constructor->IsPublic());
4019}
4020
4021mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
4022                                                  Handle<mirror::Class> klass,
4023                                                  Handle<mirror::ArtMethod> prototype) {
4024  // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
4025  // prototype method
4026  prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
4027                                                                   prototype.Get());
4028  // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
4029  // as necessary
4030  mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
4031  if (UNLIKELY(method == nullptr)) {
4032    CHECK(self->IsExceptionPending());  // OOME.
4033    return nullptr;
4034  }
4035
4036  // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
4037  // the intersection of throw exceptions as defined in Proxy
4038  method->SetDeclaringClass(klass.Get());
4039  method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
4040
4041  // At runtime the method looks like a reference and argument saving method, clone the code
4042  // related parameters from this method.
4043  method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
4044  method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
4045  method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
4046
4047  return method;
4048}
4049
4050static void CheckProxyMethod(Handle<mirror::ArtMethod> method,
4051                             Handle<mirror::ArtMethod> prototype)
4052    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4053  // Basic sanity
4054  CHECK(!prototype->IsFinal());
4055  CHECK(method->IsFinal());
4056  CHECK(!method->IsAbstract());
4057
4058  // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
4059  // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
4060  CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
4061  CHECK(prototype->HasSameDexCacheResolvedMethods(method.Get()));
4062  CHECK(prototype->HasSameDexCacheResolvedTypes(method.Get()));
4063  CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
4064
4065  CHECK_STREQ(method->GetName(), prototype->GetName());
4066  CHECK_STREQ(method->GetShorty(), prototype->GetShorty());
4067  // More complex sanity - via dex cache
4068  CHECK_EQ(method->GetInterfaceMethodIfProxy()->GetReturnType(), prototype->GetReturnType());
4069}
4070
4071static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
4072                                 bool can_init_parents)
4073    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4074  if (can_init_statics && can_init_parents) {
4075    return true;
4076  }
4077  if (!can_init_statics) {
4078    // Check if there's a class initializer.
4079    mirror::ArtMethod* clinit = klass->FindClassInitializer();
4080    if (clinit != nullptr) {
4081      return false;
4082    }
4083    // Check if there are encoded static values needing initialization.
4084    if (klass->NumStaticFields() != 0) {
4085      const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
4086      DCHECK(dex_class_def != nullptr);
4087      if (dex_class_def->static_values_off_ != 0) {
4088        return false;
4089      }
4090    }
4091  }
4092  if (!klass->IsInterface() && klass->HasSuperClass()) {
4093    mirror::Class* super_class = klass->GetSuperClass();
4094    if (!can_init_parents && !super_class->IsInitialized()) {
4095      return false;
4096    } else {
4097      if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
4098        return false;
4099      }
4100    }
4101  }
4102  return true;
4103}
4104
4105bool ClassLinker::InitializeClass(Thread* self, Handle<mirror::Class> klass,
4106                                  bool can_init_statics, bool can_init_parents) {
4107  // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
4108
4109  // Are we already initialized and therefore done?
4110  // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
4111  // an initialized class will never change its state.
4112  if (klass->IsInitialized()) {
4113    return true;
4114  }
4115
4116  // Fast fail if initialization requires a full runtime. Not part of the JLS.
4117  if (!CanWeInitializeClass(klass.Get(), can_init_statics, can_init_parents)) {
4118    return false;
4119  }
4120
4121  self->AllowThreadSuspension();
4122  uint64_t t0;
4123  {
4124    ObjectLock<mirror::Class> lock(self, klass);
4125
4126    // Re-check under the lock in case another thread initialized ahead of us.
4127    if (klass->IsInitialized()) {
4128      return true;
4129    }
4130
4131    // Was the class already found to be erroneous? Done under the lock to match the JLS.
4132    if (klass->IsErroneous()) {
4133      ThrowEarlierClassFailure(klass.Get());
4134      VlogClassInitializationFailure(klass);
4135      return false;
4136    }
4137
4138    CHECK(klass->IsResolved()) << PrettyClass(klass.Get()) << ": state=" << klass->GetStatus();
4139
4140    if (!klass->IsVerified()) {
4141      VerifyClass(self, klass);
4142      if (!klass->IsVerified()) {
4143        // We failed to verify, expect either the klass to be erroneous or verification failed at
4144        // compile time.
4145        if (klass->IsErroneous()) {
4146          CHECK(self->IsExceptionPending());
4147          VlogClassInitializationFailure(klass);
4148        } else {
4149          CHECK(Runtime::Current()->IsCompiler());
4150          CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
4151        }
4152        return false;
4153      } else {
4154        self->AssertNoPendingException();
4155      }
4156    }
4157
4158    // If the class is kStatusInitializing, either this thread is
4159    // initializing higher up the stack or another thread has beat us
4160    // to initializing and we need to wait. Either way, this
4161    // invocation of InitializeClass will not be responsible for
4162    // running <clinit> and will return.
4163    if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
4164      // Could have got an exception during verification.
4165      if (self->IsExceptionPending()) {
4166        VlogClassInitializationFailure(klass);
4167        return false;
4168      }
4169      // We caught somebody else in the act; was it us?
4170      if (klass->GetClinitThreadId() == self->GetTid()) {
4171        // Yes. That's fine. Return so we can continue initializing.
4172        return true;
4173      }
4174      // No. That's fine. Wait for another thread to finish initializing.
4175      return WaitForInitializeClass(klass, self, lock);
4176    }
4177
4178    if (!ValidateSuperClassDescriptors(klass)) {
4179      klass->SetStatus(mirror::Class::kStatusError, self);
4180      return false;
4181    }
4182    self->AllowThreadSuspension();
4183
4184    CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.Get());
4185
4186    // From here out other threads may observe that we're initializing and so changes of state
4187    // require the a notification.
4188    klass->SetClinitThreadId(self->GetTid());
4189    klass->SetStatus(mirror::Class::kStatusInitializing, self);
4190
4191    t0 = NanoTime();
4192  }
4193
4194  // Initialize super classes, must be done while initializing for the JLS.
4195  if (!klass->IsInterface() && klass->HasSuperClass()) {
4196    mirror::Class* super_class = klass->GetSuperClass();
4197    if (!super_class->IsInitialized()) {
4198      CHECK(!super_class->IsInterface());
4199      CHECK(can_init_parents);
4200      StackHandleScope<1> hs(self);
4201      Handle<mirror::Class> handle_scope_super(hs.NewHandle(super_class));
4202      bool super_initialized = InitializeClass(self, handle_scope_super, can_init_statics, true);
4203      if (!super_initialized) {
4204        // The super class was verified ahead of entering initializing, we should only be here if
4205        // the super class became erroneous due to initialization.
4206        CHECK(handle_scope_super->IsErroneous() && self->IsExceptionPending())
4207            << "Super class initialization failed for "
4208            << PrettyDescriptor(handle_scope_super.Get())
4209            << " that has unexpected status " << handle_scope_super->GetStatus()
4210            << "\nPending exception:\n"
4211            << (self->GetException(nullptr) != nullptr ? self->GetException(nullptr)->Dump() : "");
4212        ObjectLock<mirror::Class> lock(self, klass);
4213        // Initialization failed because the super-class is erroneous.
4214        klass->SetStatus(mirror::Class::kStatusError, self);
4215        return false;
4216      }
4217    }
4218  }
4219
4220  const size_t num_static_fields = klass->NumStaticFields();
4221  if (num_static_fields > 0) {
4222    const DexFile::ClassDef* dex_class_def = klass->GetClassDef();
4223    CHECK(dex_class_def != nullptr);
4224    const DexFile& dex_file = klass->GetDexFile();
4225    StackHandleScope<3> hs(self);
4226    Handle<mirror::ClassLoader> class_loader(hs.NewHandle(klass->GetClassLoader()));
4227    Handle<mirror::DexCache> dex_cache(hs.NewHandle(klass->GetDexCache()));
4228
4229    // Eagerly fill in static fields so that the we don't have to do as many expensive
4230    // Class::FindStaticField in ResolveField.
4231    for (size_t i = 0; i < num_static_fields; ++i) {
4232      mirror::ArtField* field = klass->GetStaticField(i);
4233      const uint32_t field_idx = field->GetDexFieldIndex();
4234      mirror::ArtField* resolved_field = dex_cache->GetResolvedField(field_idx);
4235      if (resolved_field == nullptr) {
4236        dex_cache->SetResolvedField(field_idx, field);
4237      } else {
4238        DCHECK_EQ(field, resolved_field);
4239      }
4240    }
4241
4242    EncodedStaticFieldValueIterator value_it(dex_file, &dex_cache, &class_loader,
4243                                             this, *dex_class_def);
4244    const uint8_t* class_data = dex_file.GetClassData(*dex_class_def);
4245    ClassDataItemIterator field_it(dex_file, class_data);
4246    if (value_it.HasNext()) {
4247      DCHECK(field_it.HasNextStaticField());
4248      CHECK(can_init_statics);
4249      for ( ; value_it.HasNext(); value_it.Next(), field_it.Next()) {
4250        StackHandleScope<1> hs2(self);
4251        Handle<mirror::ArtField> field(hs2.NewHandle(
4252            ResolveField(dex_file, field_it.GetMemberIndex(), dex_cache, class_loader, true)));
4253        if (Runtime::Current()->IsActiveTransaction()) {
4254          value_it.ReadValueToField<true>(field);
4255        } else {
4256          value_it.ReadValueToField<false>(field);
4257        }
4258        DCHECK(!value_it.HasNext() || field_it.HasNextStaticField());
4259      }
4260    }
4261  }
4262
4263  mirror::ArtMethod* clinit = klass->FindClassInitializer();
4264  if (clinit != nullptr) {
4265    CHECK(can_init_statics);
4266    JValue result;
4267    clinit->Invoke(self, nullptr, 0, &result, "V");
4268  }
4269
4270  self->AllowThreadSuspension();
4271  uint64_t t1 = NanoTime();
4272
4273  bool success = true;
4274  {
4275    ObjectLock<mirror::Class> lock(self, klass);
4276
4277    if (self->IsExceptionPending()) {
4278      WrapExceptionInInitializer(klass);
4279      klass->SetStatus(mirror::Class::kStatusError, self);
4280      success = false;
4281    } else {
4282      RuntimeStats* global_stats = Runtime::Current()->GetStats();
4283      RuntimeStats* thread_stats = self->GetStats();
4284      ++global_stats->class_init_count;
4285      ++thread_stats->class_init_count;
4286      global_stats->class_init_time_ns += (t1 - t0);
4287      thread_stats->class_init_time_ns += (t1 - t0);
4288      // Set the class as initialized except if failed to initialize static fields.
4289      klass->SetStatus(mirror::Class::kStatusInitialized, self);
4290      if (VLOG_IS_ON(class_linker)) {
4291        std::string temp;
4292        LOG(INFO) << "Initialized class " << klass->GetDescriptor(&temp) << " from " <<
4293            klass->GetLocation();
4294      }
4295      // Opportunistically set static method trampolines to their destination.
4296      FixupStaticTrampolines(klass.Get());
4297    }
4298  }
4299  return success;
4300}
4301
4302bool ClassLinker::WaitForInitializeClass(Handle<mirror::Class> klass, Thread* self,
4303                                         ObjectLock<mirror::Class>& lock)
4304    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4305  while (true) {
4306    self->AssertNoPendingException();
4307    CHECK(!klass->IsInitialized());
4308    lock.WaitIgnoringInterrupts();
4309
4310    // When we wake up, repeat the test for init-in-progress.  If
4311    // there's an exception pending (only possible if
4312    // we were not using WaitIgnoringInterrupts), bail out.
4313    if (self->IsExceptionPending()) {
4314      WrapExceptionInInitializer(klass);
4315      klass->SetStatus(mirror::Class::kStatusError, self);
4316      return false;
4317    }
4318    // Spurious wakeup? Go back to waiting.
4319    if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
4320      continue;
4321    }
4322    if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
4323      // Compile time initialization failed.
4324      return false;
4325    }
4326    if (klass->IsErroneous()) {
4327      // The caller wants an exception, but it was thrown in a
4328      // different thread.  Synthesize one here.
4329      ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
4330                                PrettyDescriptor(klass.Get()).c_str());
4331      VlogClassInitializationFailure(klass);
4332      return false;
4333    }
4334    if (klass->IsInitialized()) {
4335      return true;
4336    }
4337    LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.Get()) << " is "
4338        << klass->GetStatus();
4339  }
4340  UNREACHABLE();
4341}
4342
4343bool ClassLinker::ValidateSuperClassDescriptors(Handle<mirror::Class> klass) {
4344  if (klass->IsInterface()) {
4345    return true;
4346  }
4347  // Begin with the methods local to the superclass.
4348  Thread* self = Thread::Current();
4349  StackHandleScope<2> hs(self);
4350  MutableMethodHelper mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4351  MutableMethodHelper super_mh(hs.NewHandle<mirror::ArtMethod>(nullptr));
4352  if (klass->HasSuperClass() &&
4353      klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
4354    for (int i = klass->GetSuperClass()->GetVTableLength() - 1; i >= 0; --i) {
4355      mh.ChangeMethod(klass->GetVTableEntry(i));
4356      super_mh.ChangeMethod(klass->GetSuperClass()->GetVTableEntry(i));
4357      if (mh.GetMethod() != super_mh.GetMethod() &&
4358          !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
4359        ThrowLinkageError(klass.Get(),
4360                          "Class %s method %s resolves differently in superclass %s",
4361                          PrettyDescriptor(klass.Get()).c_str(),
4362                          PrettyMethod(mh.GetMethod()).c_str(),
4363                          PrettyDescriptor(klass->GetSuperClass()).c_str());
4364        return false;
4365      }
4366    }
4367  }
4368  for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
4369    if (klass->GetClassLoader() != klass->GetIfTable()->GetInterface(i)->GetClassLoader()) {
4370      uint32_t num_methods = klass->GetIfTable()->GetInterface(i)->NumVirtualMethods();
4371      for (uint32_t j = 0; j < num_methods; ++j) {
4372        mh.ChangeMethod(klass->GetIfTable()->GetMethodArray(i)->GetWithoutChecks(j));
4373        super_mh.ChangeMethod(klass->GetIfTable()->GetInterface(i)->GetVirtualMethod(j));
4374        if (mh.GetMethod() != super_mh.GetMethod() &&
4375            !mh.HasSameSignatureWithDifferentClassLoaders(self, &super_mh)) {
4376          ThrowLinkageError(klass.Get(),
4377                            "Class %s method %s resolves differently in interface %s",
4378                            PrettyDescriptor(klass.Get()).c_str(),
4379                            PrettyMethod(mh.GetMethod()).c_str(),
4380                            PrettyDescriptor(klass->GetIfTable()->GetInterface(i)).c_str());
4381          return false;
4382        }
4383      }
4384    }
4385  }
4386  return true;
4387}
4388
4389bool ClassLinker::EnsureInitialized(Thread* self, Handle<mirror::Class> c, bool can_init_fields,
4390                                    bool can_init_parents) {
4391  DCHECK(c.Get() != nullptr);
4392  if (c->IsInitialized()) {
4393    EnsurePreverifiedMethods(c);
4394    return true;
4395  }
4396  const bool success = InitializeClass(self, c, can_init_fields, can_init_parents);
4397  if (!success) {
4398    if (can_init_fields && can_init_parents) {
4399      CHECK(self->IsExceptionPending()) << PrettyClass(c.Get());
4400    }
4401  } else {
4402    self->AssertNoPendingException();
4403  }
4404  return success;
4405}
4406
4407void ClassLinker::FixupTemporaryDeclaringClass(mirror::Class* temp_class, mirror::Class* new_class) {
4408  mirror::ObjectArray<mirror::ArtField>* fields = new_class->GetIFields();
4409  if (fields != nullptr) {
4410    for (int index = 0; index < fields->GetLength(); index ++) {
4411      if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4412        fields->Get(index)->SetDeclaringClass(new_class);
4413      }
4414    }
4415  }
4416
4417  fields = new_class->GetSFields();
4418  if (fields != nullptr) {
4419    for (int index = 0; index < fields->GetLength(); index ++) {
4420      if (fields->Get(index)->GetDeclaringClass() == temp_class) {
4421        fields->Get(index)->SetDeclaringClass(new_class);
4422      }
4423    }
4424  }
4425
4426  mirror::ObjectArray<mirror::ArtMethod>* methods = new_class->GetDirectMethods();
4427  if (methods != nullptr) {
4428    for (int index = 0; index < methods->GetLength(); index ++) {
4429      if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4430        methods->Get(index)->SetDeclaringClass(new_class);
4431      }
4432    }
4433  }
4434
4435  methods = new_class->GetVirtualMethods();
4436  if (methods != nullptr) {
4437    for (int index = 0; index < methods->GetLength(); index ++) {
4438      if (methods->Get(index)->GetDeclaringClass() == temp_class) {
4439        methods->Get(index)->SetDeclaringClass(new_class);
4440      }
4441    }
4442  }
4443}
4444
4445bool ClassLinker::LinkClass(Thread* self, const char* descriptor, Handle<mirror::Class> klass,
4446                            Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4447                            mirror::Class** new_class) {
4448  CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
4449
4450  if (!LinkSuperClass(klass)) {
4451    return false;
4452  }
4453  StackHandleScope<mirror::Class::kImtSize> imt_handle_scope(
4454      self, Runtime::Current()->GetImtUnimplementedMethod());
4455  if (!LinkMethods(self, klass, interfaces, &imt_handle_scope)) {
4456    return false;
4457  }
4458  if (!LinkInstanceFields(self, klass)) {
4459    return false;
4460  }
4461  size_t class_size;
4462  if (!LinkStaticFields(self, klass, &class_size)) {
4463    return false;
4464  }
4465  CreateReferenceInstanceOffsets(klass);
4466  CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
4467
4468  if (!klass->IsTemp() || (!init_done_ && klass->GetClassSize() == class_size)) {
4469    // We don't need to retire this class as it has no embedded tables or it was created the
4470    // correct size during class linker initialization.
4471    CHECK_EQ(klass->GetClassSize(), class_size) << PrettyDescriptor(klass.Get());
4472
4473    if (klass->ShouldHaveEmbeddedImtAndVTable()) {
4474      klass->PopulateEmbeddedImtAndVTable(&imt_handle_scope);
4475    }
4476
4477    // This will notify waiters on klass that saw the not yet resolved
4478    // class in the class_table_ during EnsureResolved.
4479    klass->SetStatus(mirror::Class::kStatusResolved, self);
4480    *new_class = klass.Get();
4481  } else {
4482    CHECK(!klass->IsResolved());
4483    // Retire the temporary class and create the correctly sized resolved class.
4484    *new_class = klass->CopyOf(self, class_size, &imt_handle_scope);
4485    if (UNLIKELY(*new_class == nullptr)) {
4486      CHECK(self->IsExceptionPending());  // Expect an OOME.
4487      klass->SetStatus(mirror::Class::kStatusError, self);
4488      return false;
4489    }
4490
4491    CHECK_EQ((*new_class)->GetClassSize(), class_size);
4492    StackHandleScope<1> hs(self);
4493    auto new_class_h = hs.NewHandleWrapper<mirror::Class>(new_class);
4494    ObjectLock<mirror::Class> lock(self, new_class_h);
4495
4496    FixupTemporaryDeclaringClass(klass.Get(), new_class_h.Get());
4497
4498    mirror::Class* existing = UpdateClass(descriptor, new_class_h.Get(),
4499                                          ComputeModifiedUtf8Hash(descriptor));
4500    CHECK(existing == nullptr || existing == klass.Get());
4501
4502    // This will notify waiters on temp class that saw the not yet resolved class in the
4503    // class_table_ during EnsureResolved.
4504    klass->SetStatus(mirror::Class::kStatusRetired, self);
4505
4506    CHECK_EQ(new_class_h->GetStatus(), mirror::Class::kStatusResolving);
4507    // This will notify waiters on new_class that saw the not yet resolved
4508    // class in the class_table_ during EnsureResolved.
4509    new_class_h->SetStatus(mirror::Class::kStatusResolved, self);
4510  }
4511  return true;
4512}
4513
4514bool ClassLinker::LoadSuperAndInterfaces(Handle<mirror::Class> klass, const DexFile& dex_file) {
4515  CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
4516  const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
4517  uint16_t super_class_idx = class_def.superclass_idx_;
4518  if (super_class_idx != DexFile::kDexNoIndex16) {
4519    mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.Get());
4520    if (super_class == nullptr) {
4521      DCHECK(Thread::Current()->IsExceptionPending());
4522      return false;
4523    }
4524    // Verify
4525    if (!klass->CanAccess(super_class)) {
4526      ThrowIllegalAccessError(klass.Get(), "Class %s extended by class %s is inaccessible",
4527                              PrettyDescriptor(super_class).c_str(),
4528                              PrettyDescriptor(klass.Get()).c_str());
4529      return false;
4530    }
4531    CHECK(super_class->IsResolved());
4532    klass->SetSuperClass(super_class);
4533  }
4534  const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
4535  if (interfaces != nullptr) {
4536    for (size_t i = 0; i < interfaces->Size(); i++) {
4537      uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
4538      mirror::Class* interface = ResolveType(dex_file, idx, klass.Get());
4539      if (interface == nullptr) {
4540        DCHECK(Thread::Current()->IsExceptionPending());
4541        return false;
4542      }
4543      // Verify
4544      if (!klass->CanAccess(interface)) {
4545        // TODO: the RI seemed to ignore this in my testing.
4546        ThrowIllegalAccessError(klass.Get(), "Interface %s implemented by class %s is inaccessible",
4547                                PrettyDescriptor(interface).c_str(),
4548                                PrettyDescriptor(klass.Get()).c_str());
4549        return false;
4550      }
4551    }
4552  }
4553  // Mark the class as loaded.
4554  klass->SetStatus(mirror::Class::kStatusLoaded, nullptr);
4555  return true;
4556}
4557
4558bool ClassLinker::LinkSuperClass(Handle<mirror::Class> klass) {
4559  CHECK(!klass->IsPrimitive());
4560  mirror::Class* super = klass->GetSuperClass();
4561  if (klass.Get() == GetClassRoot(kJavaLangObject)) {
4562    if (super != nullptr) {
4563      ThrowClassFormatError(klass.Get(), "java.lang.Object must not have a superclass");
4564      return false;
4565    }
4566    return true;
4567  }
4568  if (super == nullptr) {
4569    ThrowLinkageError(klass.Get(), "No superclass defined for class %s",
4570                      PrettyDescriptor(klass.Get()).c_str());
4571    return false;
4572  }
4573  // Verify
4574  if (super->IsFinal() || super->IsInterface()) {
4575    ThrowIncompatibleClassChangeError(klass.Get(), "Superclass %s of %s is %s",
4576                                      PrettyDescriptor(super).c_str(),
4577                                      PrettyDescriptor(klass.Get()).c_str(),
4578                                      super->IsFinal() ? "declared final" : "an interface");
4579    return false;
4580  }
4581  if (!klass->CanAccess(super)) {
4582    ThrowIllegalAccessError(klass.Get(), "Superclass %s is inaccessible to class %s",
4583                            PrettyDescriptor(super).c_str(),
4584                            PrettyDescriptor(klass.Get()).c_str());
4585    return false;
4586  }
4587
4588  // Inherit kAccClassIsFinalizable from the superclass in case this
4589  // class doesn't override finalize.
4590  if (super->IsFinalizable()) {
4591    klass->SetFinalizable();
4592  }
4593
4594  // Inherit reference flags (if any) from the superclass.
4595  int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
4596  if (reference_flags != 0) {
4597    klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
4598  }
4599  // Disallow custom direct subclasses of java.lang.ref.Reference.
4600  if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
4601    ThrowLinkageError(klass.Get(),
4602                      "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
4603                      PrettyDescriptor(klass.Get()).c_str());
4604    return false;
4605  }
4606
4607  if (kIsDebugBuild) {
4608    // Ensure super classes are fully resolved prior to resolving fields..
4609    while (super != nullptr) {
4610      CHECK(super->IsResolved());
4611      super = super->GetSuperClass();
4612    }
4613  }
4614  return true;
4615}
4616
4617// Populate the class vtable and itable. Compute return type indices.
4618bool ClassLinker::LinkMethods(Thread* self, Handle<mirror::Class> klass,
4619                              Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4620                              StackHandleScope<mirror::Class::kImtSize>* out_imt) {
4621  self->AllowThreadSuspension();
4622  if (klass->IsInterface()) {
4623    // No vtable.
4624    size_t count = klass->NumVirtualMethods();
4625    if (!IsUint(16, count)) {
4626      ThrowClassFormatError(klass.Get(), "Too many methods on interface: %zd", count);
4627      return false;
4628    }
4629    for (size_t i = 0; i < count; ++i) {
4630      klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
4631    }
4632  } else if (!LinkVirtualMethods(self, klass)) {  // Link virtual methods first.
4633    return false;
4634  }
4635  return LinkInterfaceMethods(self, klass, interfaces, out_imt);  // Link interface method last.
4636}
4637
4638// Comparator for name and signature of a method, used in finding overriding methods. Implementation
4639// avoids the use of handles, if it didn't then rather than compare dex files we could compare dex
4640// caches in the implementation below.
4641class MethodNameAndSignatureComparator FINAL : public ValueObject {
4642 public:
4643  explicit MethodNameAndSignatureComparator(mirror::ArtMethod* method)
4644      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) :
4645      dex_file_(method->GetDexFile()), mid_(&dex_file_->GetMethodId(method->GetDexMethodIndex())),
4646      name_(nullptr), name_len_(0) {
4647    DCHECK(!method->IsProxyMethod()) << PrettyMethod(method);
4648  }
4649
4650  const char* GetName() {
4651    if (name_ == nullptr) {
4652      name_ = dex_file_->StringDataAndUtf16LengthByIdx(mid_->name_idx_, &name_len_);
4653    }
4654    return name_;
4655  }
4656
4657  bool HasSameNameAndSignature(mirror::ArtMethod* other)
4658      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4659    DCHECK(!other->IsProxyMethod()) << PrettyMethod(other);
4660    const DexFile* other_dex_file = other->GetDexFile();
4661    const DexFile::MethodId& other_mid = other_dex_file->GetMethodId(other->GetDexMethodIndex());
4662    if (dex_file_ == other_dex_file) {
4663      return mid_->name_idx_ == other_mid.name_idx_ && mid_->proto_idx_ == other_mid.proto_idx_;
4664    }
4665    GetName();  // Only used to make sure its calculated.
4666    uint32_t other_name_len;
4667    const char* other_name = other_dex_file->StringDataAndUtf16LengthByIdx(other_mid.name_idx_,
4668                                                                           &other_name_len);
4669    if (name_len_ != other_name_len || strcmp(name_, other_name) != 0) {
4670      return false;
4671    }
4672    return dex_file_->GetMethodSignature(*mid_) == other_dex_file->GetMethodSignature(other_mid);
4673  }
4674
4675 private:
4676  // Dex file for the method to compare against.
4677  const DexFile* const dex_file_;
4678  // MethodId for the method to compare against.
4679  const DexFile::MethodId* const mid_;
4680  // Lazily computed name from the dex file's strings.
4681  const char* name_;
4682  // Lazily computed name length.
4683  uint32_t name_len_;
4684};
4685
4686class LinkVirtualHashTable {
4687 public:
4688  LinkVirtualHashTable(Handle<mirror::Class> klass, size_t hash_size, uint32_t* hash_table)
4689     : klass_(klass), hash_size_(hash_size), hash_table_(hash_table) {
4690    std::fill(hash_table_, hash_table_ + hash_size_, invalid_index_);
4691  }
4692  void Add(uint32_t virtual_method_index) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4693    mirror::ArtMethod* local_method = klass_->GetVirtualMethodDuringLinking(virtual_method_index);
4694    const char* name = local_method->GetName();
4695    uint32_t hash = ComputeModifiedUtf8Hash(name);
4696    uint32_t index = hash % hash_size_;
4697    // Linear probe until we have an empty slot.
4698    while (hash_table_[index] != invalid_index_) {
4699      if (++index == hash_size_) {
4700        index = 0;
4701      }
4702    }
4703    hash_table_[index] = virtual_method_index;
4704  }
4705  uint32_t FindAndRemove(MethodNameAndSignatureComparator* comparator)
4706      SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
4707    const char* name = comparator->GetName();
4708    uint32_t hash = ComputeModifiedUtf8Hash(name);
4709    size_t index = hash % hash_size_;
4710    while (true) {
4711      const uint32_t value = hash_table_[index];
4712      // Since linear probe makes continuous blocks, hitting an invalid index means we are done
4713      // the block and can safely assume not found.
4714      if (value == invalid_index_) {
4715        break;
4716      }
4717      if (value != removed_index_) {  // This signifies not already overriden.
4718        mirror::ArtMethod* virtual_method =
4719            klass_->GetVirtualMethodDuringLinking(value);
4720        if (comparator->HasSameNameAndSignature(virtual_method->GetInterfaceMethodIfProxy())) {
4721          hash_table_[index] = removed_index_;
4722          return value;
4723        }
4724      }
4725      if (++index == hash_size_) {
4726        index = 0;
4727      }
4728    }
4729    return GetNotFoundIndex();
4730  }
4731  static uint32_t GetNotFoundIndex() {
4732    return invalid_index_;
4733  }
4734
4735 private:
4736  static const uint32_t invalid_index_;
4737  static const uint32_t removed_index_;
4738
4739  Handle<mirror::Class> klass_;
4740  const size_t hash_size_;
4741  uint32_t* const hash_table_;
4742};
4743
4744const uint32_t LinkVirtualHashTable::invalid_index_ = std::numeric_limits<uint32_t>::max();
4745const uint32_t LinkVirtualHashTable::removed_index_ = std::numeric_limits<uint32_t>::max() - 1;
4746
4747bool ClassLinker::LinkVirtualMethods(Thread* self, Handle<mirror::Class> klass) {
4748  const size_t num_virtual_methods = klass->NumVirtualMethods();
4749  if (klass->HasSuperClass()) {
4750    const size_t super_vtable_length = klass->GetSuperClass()->GetVTableLength();
4751    const size_t max_count = num_virtual_methods + super_vtable_length;
4752    StackHandleScope<2> hs(self);
4753    Handle<mirror::Class> super_class(hs.NewHandle(klass->GetSuperClass()));
4754    MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable;
4755    if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
4756      vtable = hs.NewHandle(AllocArtMethodArray(self, max_count));
4757      if (UNLIKELY(vtable.Get() == nullptr)) {
4758        CHECK(self->IsExceptionPending());  // OOME.
4759        return false;
4760      }
4761      for (size_t i = 0; i < super_vtable_length; i++) {
4762        vtable->SetWithoutChecks<false>(i, super_class->GetEmbeddedVTableEntry(i));
4763      }
4764      if (num_virtual_methods == 0) {
4765        klass->SetVTable(vtable.Get());
4766        return true;
4767      }
4768    } else {
4769      mirror::ObjectArray<mirror::ArtMethod>* super_vtable = super_class->GetVTable();
4770      CHECK(super_vtable != nullptr) << PrettyClass(super_class.Get());
4771      if (num_virtual_methods == 0) {
4772        klass->SetVTable(super_vtable);
4773        return true;
4774      }
4775      vtable = hs.NewHandle(super_vtable->CopyOf(self, max_count));
4776      if (UNLIKELY(vtable.Get() == nullptr)) {
4777        CHECK(self->IsExceptionPending());  // OOME.
4778        return false;
4779      }
4780    }
4781    // How the algorithm works:
4782    // 1. Populate hash table by adding num_virtual_methods from klass. The values in the hash
4783    // table are: invalid_index for unused slots, index super_vtable_length + i for a virtual
4784    // method which has not been matched to a vtable method, and j if the virtual method at the
4785    // index overrode the super virtual method at index j.
4786    // 2. Loop through super virtual methods, if they overwrite, update hash table to j
4787    // (j < super_vtable_length) to avoid redundant checks. (TODO maybe use this info for reducing
4788    // the need for the initial vtable which we later shrink back down).
4789    // 3. Add non overridden methods to the end of the vtable.
4790    static constexpr size_t kMaxStackHash = 250;
4791    const size_t hash_table_size = num_virtual_methods * 3;
4792    uint32_t* hash_table_ptr;
4793    std::unique_ptr<uint32_t[]> hash_heap_storage;
4794    if (hash_table_size <= kMaxStackHash) {
4795      hash_table_ptr = reinterpret_cast<uint32_t*>(
4796          alloca(hash_table_size * sizeof(*hash_table_ptr)));
4797    } else {
4798      hash_heap_storage.reset(new uint32_t[hash_table_size]);
4799      hash_table_ptr = hash_heap_storage.get();
4800    }
4801    LinkVirtualHashTable hash_table(klass, hash_table_size, hash_table_ptr);
4802    // Add virtual methods to the hash table.
4803    for (size_t i = 0; i < num_virtual_methods; ++i) {
4804      hash_table.Add(i);
4805    }
4806    // Loop through each super vtable method and see if they are overriden by a method we added to
4807    // the hash table.
4808    for (size_t j = 0; j < super_vtable_length; ++j) {
4809      // Search the hash table to see if we are overidden by any method.
4810      mirror::ArtMethod* super_method = vtable->GetWithoutChecks(j);
4811      MethodNameAndSignatureComparator super_method_name_comparator(
4812          super_method->GetInterfaceMethodIfProxy());
4813      uint32_t hash_index = hash_table.FindAndRemove(&super_method_name_comparator);
4814      if (hash_index != hash_table.GetNotFoundIndex()) {
4815        mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(hash_index);
4816        if (klass->CanAccessMember(super_method->GetDeclaringClass(),
4817                                   super_method->GetAccessFlags())) {
4818          if (super_method->IsFinal()) {
4819            ThrowLinkageError(klass.Get(), "Method %s overrides final method in class %s",
4820                              PrettyMethod(virtual_method).c_str(),
4821                              super_method->GetDeclaringClassDescriptor());
4822            return false;
4823          }
4824          vtable->SetWithoutChecks<false>(j, virtual_method);
4825          virtual_method->SetMethodIndex(j);
4826        } else {
4827          LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(virtual_method)
4828                       << " would have incorrectly overridden the package-private method in "
4829                       << PrettyDescriptor(super_method->GetDeclaringClassDescriptor());
4830        }
4831      }
4832    }
4833    // Add the non overridden methods at the end.
4834    size_t actual_count = super_vtable_length;
4835    for (size_t i = 0; i < num_virtual_methods; ++i) {
4836      mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
4837      size_t method_idx = local_method->GetMethodIndexDuringLinking();
4838      if (method_idx < super_vtable_length &&
4839          local_method == vtable->GetWithoutChecks(method_idx)) {
4840        continue;
4841      }
4842      vtable->SetWithoutChecks<false>(actual_count, local_method);
4843      local_method->SetMethodIndex(actual_count);
4844      ++actual_count;
4845    }
4846    if (!IsUint(16, actual_count)) {
4847      ThrowClassFormatError(klass.Get(), "Too many methods defined on class: %zd", actual_count);
4848      return false;
4849    }
4850    // Shrink vtable if possible
4851    CHECK_LE(actual_count, max_count);
4852    if (actual_count < max_count) {
4853      vtable.Assign(vtable->CopyOf(self, actual_count));
4854      if (UNLIKELY(vtable.Get() == nullptr)) {
4855        CHECK(self->IsExceptionPending());  // OOME.
4856        return false;
4857      }
4858    }
4859    klass->SetVTable(vtable.Get());
4860  } else {
4861    CHECK_EQ(klass.Get(), GetClassRoot(kJavaLangObject));
4862    if (!IsUint(16, num_virtual_methods)) {
4863      ThrowClassFormatError(klass.Get(), "Too many methods: %d",
4864                            static_cast<int>(num_virtual_methods));
4865      return false;
4866    }
4867    mirror::ObjectArray<mirror::ArtMethod>* vtable = AllocArtMethodArray(self, num_virtual_methods);
4868    if (UNLIKELY(vtable == nullptr)) {
4869      CHECK(self->IsExceptionPending());  // OOME.
4870      return false;
4871    }
4872    for (size_t i = 0; i < num_virtual_methods; ++i) {
4873      mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
4874      vtable->SetWithoutChecks<false>(i, virtual_method);
4875      virtual_method->SetMethodIndex(i & 0xFFFF);
4876    }
4877    klass->SetVTable(vtable);
4878  }
4879  return true;
4880}
4881
4882bool ClassLinker::LinkInterfaceMethods(Thread* self, Handle<mirror::Class> klass,
4883                                       Handle<mirror::ObjectArray<mirror::Class>> interfaces,
4884                                       StackHandleScope<mirror::Class::kImtSize>* out_imt) {
4885  StackHandleScope<3> hs(self);
4886  Runtime* const runtime = Runtime::Current();
4887  const bool has_superclass = klass->HasSuperClass();
4888  const size_t super_ifcount = has_superclass ? klass->GetSuperClass()->GetIfTableCount() : 0U;
4889  const bool have_interfaces = interfaces.Get() != nullptr;
4890  const size_t num_interfaces =
4891      have_interfaces ? interfaces->GetLength() : klass->NumDirectInterfaces();
4892  if (num_interfaces == 0) {
4893    if (super_ifcount == 0) {
4894      // Class implements no interfaces.
4895      DCHECK_EQ(klass->GetIfTableCount(), 0);
4896      DCHECK(klass->GetIfTable() == nullptr);
4897      return true;
4898    }
4899    // Class implements same interfaces as parent, are any of these not marker interfaces?
4900    bool has_non_marker_interface = false;
4901    mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
4902    for (size_t i = 0; i < super_ifcount; ++i) {
4903      if (super_iftable->GetMethodArrayCount(i) > 0) {
4904        has_non_marker_interface = true;
4905        break;
4906      }
4907    }
4908    // Class just inherits marker interfaces from parent so recycle parent's iftable.
4909    if (!has_non_marker_interface) {
4910      klass->SetIfTable(super_iftable);
4911      return true;
4912    }
4913  }
4914  size_t ifcount = super_ifcount + num_interfaces;
4915  for (size_t i = 0; i < num_interfaces; i++) {
4916    mirror::Class* interface = have_interfaces ?
4917        interfaces->GetWithoutChecks(i) : mirror::Class::GetDirectInterface(self, klass, i);
4918    DCHECK(interface != nullptr);
4919    if (UNLIKELY(!interface->IsInterface())) {
4920      std::string temp;
4921      ThrowIncompatibleClassChangeError(klass.Get(), "Class %s implements non-interface class %s",
4922                                        PrettyDescriptor(klass.Get()).c_str(),
4923                                        PrettyDescriptor(interface->GetDescriptor(&temp)).c_str());
4924      return false;
4925    }
4926    ifcount += interface->GetIfTableCount();
4927  }
4928  MutableHandle<mirror::IfTable> iftable(hs.NewHandle(AllocIfTable(self, ifcount)));
4929  if (UNLIKELY(iftable.Get() == nullptr)) {
4930    CHECK(self->IsExceptionPending());  // OOME.
4931    return false;
4932  }
4933  if (super_ifcount != 0) {
4934    mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
4935    for (size_t i = 0; i < super_ifcount; i++) {
4936      mirror::Class* super_interface = super_iftable->GetInterface(i);
4937      iftable->SetInterface(i, super_interface);
4938    }
4939  }
4940  self->AllowThreadSuspension();
4941  // Flatten the interface inheritance hierarchy.
4942  size_t idx = super_ifcount;
4943  for (size_t i = 0; i < num_interfaces; i++) {
4944    mirror::Class* interface = have_interfaces ? interfaces->Get(i) :
4945        mirror::Class::GetDirectInterface(self, klass, i);
4946    // Check if interface is already in iftable
4947    bool duplicate = false;
4948    for (size_t j = 0; j < idx; j++) {
4949      mirror::Class* existing_interface = iftable->GetInterface(j);
4950      if (existing_interface == interface) {
4951        duplicate = true;
4952        break;
4953      }
4954    }
4955    if (!duplicate) {
4956      // Add this non-duplicate interface.
4957      iftable->SetInterface(idx++, interface);
4958      // Add this interface's non-duplicate super-interfaces.
4959      for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
4960        mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
4961        bool super_duplicate = false;
4962        for (size_t k = 0; k < idx; k++) {
4963          mirror::Class* existing_interface = iftable->GetInterface(k);
4964          if (existing_interface == super_interface) {
4965            super_duplicate = true;
4966            break;
4967          }
4968        }
4969        if (!super_duplicate) {
4970          iftable->SetInterface(idx++, super_interface);
4971        }
4972      }
4973    }
4974  }
4975  self->AllowThreadSuspension();
4976  // Shrink iftable in case duplicates were found
4977  if (idx < ifcount) {
4978    DCHECK_NE(num_interfaces, 0U);
4979    iftable.Assign(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
4980    if (UNLIKELY(iftable.Get() == nullptr)) {
4981      CHECK(self->IsExceptionPending());  // OOME.
4982      return false;
4983    }
4984    ifcount = idx;
4985  } else {
4986    DCHECK_EQ(idx, ifcount);
4987  }
4988  klass->SetIfTable(iftable.Get());
4989  // If we're an interface, we don't need the vtable pointers, so we're done.
4990  if (klass->IsInterface()) {
4991    return true;
4992  }
4993  size_t miranda_list_size = 0;
4994  size_t max_miranda_methods = 0;  // The max size of miranda_list.
4995  for (size_t i = 0; i < ifcount; ++i) {
4996    max_miranda_methods += iftable->GetInterface(i)->NumVirtualMethods();
4997  }
4998  MutableHandle<mirror::ObjectArray<mirror::ArtMethod>>
4999      miranda_list(hs.NewHandle(AllocArtMethodArray(self, max_miranda_methods)));
5000  MutableHandle<mirror::ObjectArray<mirror::ArtMethod>> vtable(
5001      hs.NewHandle(klass->GetVTableDuringLinking()));
5002  // Copy the IMT from the super class if possible.
5003  bool extend_super_iftable = false;
5004  if (has_superclass) {
5005    mirror::Class* super_class = klass->GetSuperClass();
5006    extend_super_iftable = true;
5007    if (super_class->ShouldHaveEmbeddedImtAndVTable()) {
5008      for (size_t i = 0; i < mirror::Class::kImtSize; ++i) {
5009        out_imt->SetReference(i, super_class->GetEmbeddedImTableEntry(i));
5010      }
5011    } else {
5012      // No imt in the super class, need to reconstruct from the iftable.
5013      mirror::IfTable* if_table = super_class->GetIfTable();
5014      mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5015      const size_t length = super_class->GetIfTableCount();
5016      for (size_t i = 0; i < length; ++i) {
5017        mirror::Class* interface = iftable->GetInterface(i);
5018        const size_t num_virtuals = interface->NumVirtualMethods();
5019        const size_t method_array_count = if_table->GetMethodArrayCount(i);
5020        DCHECK_EQ(num_virtuals, method_array_count);
5021        if (method_array_count == 0) {
5022          continue;
5023        }
5024        mirror::ObjectArray<mirror::ArtMethod>* method_array = if_table->GetMethodArray(i);
5025        for (size_t j = 0; j < num_virtuals; ++j) {
5026          mirror::ArtMethod* method = method_array->GetWithoutChecks(j);
5027          if (method->IsMiranda()) {
5028            continue;
5029          }
5030          mirror::ArtMethod* interface_method = interface->GetVirtualMethod(j);
5031          uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5032          mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5033          if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5034            out_imt->SetReference(imt_index, method);
5035          } else if (imt_ref != conflict_method) {
5036            out_imt->SetReference(imt_index, conflict_method);
5037          }
5038        }
5039      }
5040    }
5041  }
5042  for (size_t i = 0; i < ifcount; ++i) {
5043    self->AllowThreadSuspension();
5044    size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
5045    if (num_methods > 0) {
5046      StackHandleScope<2> hs2(self);
5047      const bool is_super = i < super_ifcount;
5048      const bool super_interface = is_super && extend_super_iftable;
5049      Handle<mirror::ObjectArray<mirror::ArtMethod>> method_array;
5050      Handle<mirror::ObjectArray<mirror::ArtMethod>> input_array;
5051      if (super_interface) {
5052        mirror::IfTable* if_table = klass->GetSuperClass()->GetIfTable();
5053        DCHECK(if_table != nullptr);
5054        DCHECK(if_table->GetMethodArray(i) != nullptr);
5055        // If we are working on a super interface, try extending the existing method array.
5056        method_array = hs2.NewHandle(if_table->GetMethodArray(i)->Clone(self)->
5057            AsObjectArray<mirror::ArtMethod>());
5058        // We are overwriting a super class interface, try to only virtual methods instead of the
5059        // whole vtable.
5060        input_array = hs2.NewHandle(klass->GetVirtualMethods());
5061      } else {
5062        method_array = hs2.NewHandle(AllocArtMethodArray(self, num_methods));
5063        // A new interface, we need the whole vtable incase a new interface method is implemented
5064        // in the whole superclass.
5065        input_array = vtable;
5066      }
5067      if (UNLIKELY(method_array.Get() == nullptr)) {
5068        CHECK(self->IsExceptionPending());  // OOME.
5069        return false;
5070      }
5071      iftable->SetMethodArray(i, method_array.Get());
5072      if (input_array.Get() == nullptr) {
5073        // If the added virtual methods is empty, do nothing.
5074        DCHECK(super_interface);
5075        continue;
5076      }
5077      for (size_t j = 0; j < num_methods; ++j) {
5078        mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
5079        MethodNameAndSignatureComparator interface_name_comparator(
5080            interface_method->GetInterfaceMethodIfProxy());
5081        int32_t k;
5082        // For each method listed in the interface's method list, find the
5083        // matching method in our class's method list.  We want to favor the
5084        // subclass over the superclass, which just requires walking
5085        // back from the end of the vtable.  (This only matters if the
5086        // superclass defines a private method and this class redefines
5087        // it -- otherwise it would use the same vtable slot.  In .dex files
5088        // those don't end up in the virtual method table, so it shouldn't
5089        // matter which direction we go.  We walk it backward anyway.)
5090        for (k = input_array->GetLength() - 1; k >= 0; --k) {
5091          mirror::ArtMethod* vtable_method = input_array->GetWithoutChecks(k);
5092          mirror::ArtMethod* vtable_method_for_name_comparison =
5093              vtable_method->GetInterfaceMethodIfProxy();
5094          if (interface_name_comparator.HasSameNameAndSignature(
5095              vtable_method_for_name_comparison)) {
5096            if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
5097              ThrowIllegalAccessError(
5098                  klass.Get(),
5099                  "Method '%s' implementing interface method '%s' is not public",
5100                  PrettyMethod(vtable_method).c_str(),
5101                  PrettyMethod(interface_method).c_str());
5102              return false;
5103            }
5104            method_array->SetWithoutChecks<false>(j, vtable_method);
5105            // Place method in imt if entry is empty, place conflict otherwise.
5106            uint32_t imt_index = interface_method->GetDexMethodIndex() % mirror::Class::kImtSize;
5107            mirror::ArtMethod* imt_ref = out_imt->GetReference(imt_index)->AsArtMethod();
5108            mirror::ArtMethod* conflict_method = runtime->GetImtConflictMethod();
5109            if (imt_ref == runtime->GetImtUnimplementedMethod()) {
5110              out_imt->SetReference(imt_index, vtable_method);
5111            } else if (imt_ref != conflict_method) {
5112              // If we are not a conflict and we have the same signature and name as the imt entry,
5113              // it must be that we overwrote a superclass vtable entry.
5114              MethodNameAndSignatureComparator imt_ref_name_comparator(
5115                  imt_ref->GetInterfaceMethodIfProxy());
5116              if (imt_ref_name_comparator.HasSameNameAndSignature(
5117                  vtable_method_for_name_comparison)) {
5118                out_imt->SetReference(imt_index, vtable_method);
5119              } else {
5120                out_imt->SetReference(imt_index, conflict_method);
5121              }
5122            }
5123            break;
5124          }
5125        }
5126        if (k < 0 && !super_interface) {
5127          mirror::ArtMethod* miranda_method = nullptr;
5128          for (size_t l = 0; l < miranda_list_size; ++l) {
5129            mirror::ArtMethod* mir_method = miranda_list->Get(l);
5130            if (interface_name_comparator.HasSameNameAndSignature(mir_method)) {
5131              miranda_method = mir_method;
5132              break;
5133            }
5134          }
5135          if (miranda_method == nullptr) {
5136            // Point the interface table at a phantom slot.
5137            miranda_method = interface_method->Clone(self)->AsArtMethod();
5138            if (UNLIKELY(miranda_method == nullptr)) {
5139              CHECK(self->IsExceptionPending());  // OOME.
5140              return false;
5141            }
5142            DCHECK_LT(miranda_list_size, max_miranda_methods);
5143            miranda_list->Set<false>(miranda_list_size++, miranda_method);
5144          }
5145          method_array->SetWithoutChecks<false>(j, miranda_method);
5146        }
5147      }
5148    }
5149  }
5150  if (miranda_list_size > 0) {
5151    int old_method_count = klass->NumVirtualMethods();
5152    int new_method_count = old_method_count + miranda_list_size;
5153    mirror::ObjectArray<mirror::ArtMethod>* virtuals;
5154    if (old_method_count == 0) {
5155      virtuals = AllocArtMethodArray(self, new_method_count);
5156    } else {
5157      virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
5158    }
5159    if (UNLIKELY(virtuals == nullptr)) {
5160      CHECK(self->IsExceptionPending());  // OOME.
5161      return false;
5162    }
5163    klass->SetVirtualMethods(virtuals);
5164
5165    int old_vtable_count = vtable->GetLength();
5166    int new_vtable_count = old_vtable_count + miranda_list_size;
5167    vtable.Assign(vtable->CopyOf(self, new_vtable_count));
5168    if (UNLIKELY(vtable.Get() == nullptr)) {
5169      CHECK(self->IsExceptionPending());  // OOME.
5170      return false;
5171    }
5172    for (size_t i = 0; i < miranda_list_size; ++i) {
5173      mirror::ArtMethod* method = miranda_list->Get(i);
5174      // Leave the declaring class alone as type indices are relative to it
5175      method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
5176      method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
5177      klass->SetVirtualMethod(old_method_count + i, method);
5178      vtable->SetWithoutChecks<false>(old_vtable_count + i, method);
5179    }
5180    // TODO: do not assign to the vtable field until it is fully constructed.
5181    klass->SetVTable(vtable.Get());
5182  }
5183
5184  if (kIsDebugBuild) {
5185    mirror::ObjectArray<mirror::ArtMethod>* check_vtable = klass->GetVTableDuringLinking();
5186    for (int i = 0; i < check_vtable->GetLength(); ++i) {
5187      CHECK(check_vtable->GetWithoutChecks(i) != nullptr);
5188    }
5189  }
5190
5191  self->AllowThreadSuspension();
5192  return true;
5193}
5194
5195bool ClassLinker::LinkInstanceFields(Thread* self, Handle<mirror::Class> klass) {
5196  CHECK(klass.Get() != nullptr);
5197  return LinkFields(self, klass, false, nullptr);
5198}
5199
5200bool ClassLinker::LinkStaticFields(Thread* self, Handle<mirror::Class> klass, size_t* class_size) {
5201  CHECK(klass.Get() != nullptr);
5202  return LinkFields(self, klass, true, class_size);
5203}
5204
5205struct LinkFieldsComparator {
5206  explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
5207  }
5208  // No thread safety analysis as will be called from STL. Checked lock held in constructor.
5209  bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
5210      NO_THREAD_SAFETY_ANALYSIS {
5211    // First come reference fields, then 64-bit, then 32-bit, and then 16-bit, then finally 8-bit.
5212    Primitive::Type type1 = field1->GetTypeAsPrimitiveType();
5213    Primitive::Type type2 = field2->GetTypeAsPrimitiveType();
5214    if (type1 != type2) {
5215      if (type1 == Primitive::kPrimNot) {
5216        // Reference always goes first.
5217        return true;
5218      }
5219      if (type2 == Primitive::kPrimNot) {
5220        // Reference always goes first.
5221        return false;
5222      }
5223      size_t size1 = Primitive::ComponentSize(type1);
5224      size_t size2 = Primitive::ComponentSize(type2);
5225      if (size1 != size2) {
5226        // Larger primitive types go first.
5227        return size1 > size2;
5228      }
5229      // Primitive types differ but sizes match. Arbitrarily order by primitive type.
5230      return type1 < type2;
5231    }
5232    // Same basic group? Then sort by dex field index. This is guaranteed to be sorted
5233    // by name and for equal names by type id index.
5234    // NOTE: This works also for proxies. Their static fields are assigned appropriate indexes.
5235    return field1->GetDexFieldIndex() < field2->GetDexFieldIndex();
5236  }
5237};
5238
5239bool ClassLinker::LinkFields(Thread* self, Handle<mirror::Class> klass, bool is_static,
5240                             size_t* class_size) {
5241  self->AllowThreadSuspension();
5242  size_t num_fields =
5243      is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
5244
5245  mirror::ObjectArray<mirror::ArtField>* fields =
5246      is_static ? klass->GetSFields() : klass->GetIFields();
5247
5248  // Initialize field_offset
5249  MemberOffset field_offset(0);
5250  if (is_static) {
5251    field_offset = klass->GetFirstReferenceStaticFieldOffsetDuringLinking();
5252  } else {
5253    mirror::Class* super_class = klass->GetSuperClass();
5254    if (super_class != nullptr) {
5255      CHECK(super_class->IsResolved())
5256          << PrettyClass(klass.Get()) << " " << PrettyClass(super_class);
5257      field_offset = MemberOffset(super_class->GetObjectSize());
5258    }
5259  }
5260
5261  CHECK_EQ(num_fields == 0, fields == nullptr) << PrettyClass(klass.Get());
5262
5263  // we want a relatively stable order so that adding new fields
5264  // minimizes disruption of C++ version such as Class and Method.
5265  std::deque<mirror::ArtField*> grouped_and_sorted_fields;
5266  const char* old_no_suspend_cause = self->StartAssertNoThreadSuspension(
5267      "Naked ArtField references in deque");
5268  for (size_t i = 0; i < num_fields; i++) {
5269    mirror::ArtField* f = fields->Get(i);
5270    CHECK(f != nullptr) << PrettyClass(klass.Get());
5271    grouped_and_sorted_fields.push_back(f);
5272  }
5273  std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
5274            LinkFieldsComparator());
5275
5276  // References should be at the front.
5277  size_t current_field = 0;
5278  size_t num_reference_fields = 0;
5279  FieldGaps gaps;
5280
5281  for (; current_field < num_fields; current_field++) {
5282    mirror::ArtField* field = grouped_and_sorted_fields.front();
5283    Primitive::Type type = field->GetTypeAsPrimitiveType();
5284    bool isPrimitive = type != Primitive::kPrimNot;
5285    if (isPrimitive) {
5286      break;  // past last reference, move on to the next phase
5287    }
5288    if (UNLIKELY(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(
5289        field_offset.Uint32Value()))) {
5290      MemberOffset old_offset = field_offset;
5291      field_offset = MemberOffset(RoundUp(field_offset.Uint32Value(), 4));
5292      AddFieldGap(old_offset.Uint32Value(), field_offset.Uint32Value(), &gaps);
5293    }
5294    DCHECK(IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(field_offset.Uint32Value()));
5295    grouped_and_sorted_fields.pop_front();
5296    num_reference_fields++;
5297    field->SetOffset(field_offset);
5298    field_offset = MemberOffset(field_offset.Uint32Value() +
5299                                sizeof(mirror::HeapReference<mirror::Object>));
5300  }
5301  // Gaps are stored as a max heap which means that we must shuffle from largest to smallest
5302  // otherwise we could end up with suboptimal gap fills.
5303  ShuffleForward<8>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5304  ShuffleForward<4>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5305  ShuffleForward<2>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5306  ShuffleForward<1>(&current_field, &field_offset, &grouped_and_sorted_fields, &gaps);
5307  CHECK(grouped_and_sorted_fields.empty()) << "Missed " << grouped_and_sorted_fields.size() <<
5308      " fields.";
5309  self->EndAssertNoThreadSuspension(old_no_suspend_cause);
5310
5311  // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
5312  if (!is_static && klass->DescriptorEquals("Ljava/lang/ref/Reference;")) {
5313    // We know there are no non-reference fields in the Reference classes, and we know
5314    // that 'referent' is alphabetically last, so this is easy...
5315    CHECK_EQ(num_reference_fields, num_fields) << PrettyClass(klass.Get());
5316    CHECK_STREQ(fields->Get(num_fields - 1)->GetName(), "referent") << PrettyClass(klass.Get());
5317    --num_reference_fields;
5318  }
5319
5320  size_t size = field_offset.Uint32Value();
5321  // Update klass
5322  if (is_static) {
5323    klass->SetNumReferenceStaticFields(num_reference_fields);
5324    *class_size = size;
5325  } else {
5326    klass->SetNumReferenceInstanceFields(num_reference_fields);
5327    if (!klass->IsVariableSize()) {
5328      if (klass->DescriptorEquals("Ljava/lang/reflect/ArtMethod;")) {
5329        klass->SetObjectSize(mirror::ArtMethod::InstanceSize(sizeof(void*)));
5330      } else {
5331        std::string temp;
5332        DCHECK_GE(size, sizeof(mirror::Object)) << klass->GetDescriptor(&temp);
5333        size_t previous_size = klass->GetObjectSize();
5334        if (previous_size != 0) {
5335          // Make sure that we didn't originally have an incorrect size.
5336          CHECK_EQ(previous_size, size) << klass->GetDescriptor(&temp);
5337        }
5338        klass->SetObjectSize(size);
5339      }
5340    }
5341  }
5342
5343  if (kIsDebugBuild) {
5344    // Make sure that the fields array is ordered by name but all reference
5345    // offsets are at the beginning as far as alignment allows.
5346    MemberOffset start_ref_offset = is_static
5347        ? klass->GetFirstReferenceStaticFieldOffsetDuringLinking()
5348        : klass->GetFirstReferenceInstanceFieldOffset();
5349    MemberOffset end_ref_offset(start_ref_offset.Uint32Value() +
5350                                num_reference_fields *
5351                                    sizeof(mirror::HeapReference<mirror::Object>));
5352    MemberOffset current_ref_offset = start_ref_offset;
5353    for (size_t i = 0; i < num_fields; i++) {
5354      mirror::ArtField* field = fields->Get(i);
5355      if ((false)) {  // enable to debug field layout
5356        LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
5357                    << " class=" << PrettyClass(klass.Get())
5358                    << " field=" << PrettyField(field)
5359                    << " offset="
5360                    << field->GetField32(mirror::ArtField::OffsetOffset());
5361      }
5362      if (i != 0) {
5363        mirror::ArtField* prev_field = fields->Get(i - 1u);
5364        // NOTE: The field names can be the same. This is not possible in the Java language
5365        // but it's valid Java/dex bytecode and for example proguard can generate such bytecode.
5366        CHECK_LE(strcmp(prev_field->GetName(), field->GetName()), 0);
5367      }
5368      Primitive::Type type = field->GetTypeAsPrimitiveType();
5369      bool is_primitive = type != Primitive::kPrimNot;
5370      if (klass->DescriptorEquals("Ljava/lang/ref/Reference;") &&
5371          strcmp("referent", field->GetName()) == 0) {
5372        is_primitive = true;  // We lied above, so we have to expect a lie here.
5373      }
5374      MemberOffset offset = field->GetOffsetDuringLinking();
5375      if (is_primitive) {
5376        if (offset.Uint32Value() < end_ref_offset.Uint32Value()) {
5377          // Shuffled before references.
5378          size_t type_size = Primitive::ComponentSize(type);
5379          CHECK_LT(type_size, sizeof(mirror::HeapReference<mirror::Object>));
5380          CHECK_LT(offset.Uint32Value(), start_ref_offset.Uint32Value());
5381          CHECK_LE(offset.Uint32Value() + type_size, start_ref_offset.Uint32Value());
5382          CHECK(!IsAligned<sizeof(mirror::HeapReference<mirror::Object>)>(offset.Uint32Value()));
5383        }
5384      } else {
5385        CHECK_EQ(current_ref_offset.Uint32Value(), offset.Uint32Value());
5386        current_ref_offset = MemberOffset(current_ref_offset.Uint32Value() +
5387                                          sizeof(mirror::HeapReference<mirror::Object>));
5388      }
5389    }
5390    CHECK_EQ(current_ref_offset.Uint32Value(), end_ref_offset.Uint32Value());
5391  }
5392  return true;
5393}
5394
5395//  Set the bitmap of reference instance field offsets.
5396void ClassLinker::CreateReferenceInstanceOffsets(Handle<mirror::Class> klass) {
5397  uint32_t reference_offsets = 0;
5398  mirror::Class* super_class = klass->GetSuperClass();
5399  // Leave the reference offsets as 0 for mirror::Object (the class field is handled specially).
5400  if (super_class != nullptr) {
5401    reference_offsets = super_class->GetReferenceInstanceOffsets();
5402    // Compute reference offsets unless our superclass overflowed.
5403    if (reference_offsets != mirror::Class::kClassWalkSuper) {
5404      size_t num_reference_fields = klass->NumReferenceInstanceFieldsDuringLinking();
5405      if (num_reference_fields != 0u) {
5406        // All of the fields that contain object references are guaranteed be grouped in memory
5407        // starting at an appropriately aligned address after super class object data.
5408        uint32_t start_offset = RoundUp(super_class->GetObjectSize(),
5409                                        sizeof(mirror::HeapReference<mirror::Object>));
5410        uint32_t start_bit = (start_offset - mirror::kObjectHeaderSize) /
5411            sizeof(mirror::HeapReference<mirror::Object>);
5412        if (start_bit + num_reference_fields > 32) {
5413          reference_offsets = mirror::Class::kClassWalkSuper;
5414        } else {
5415          reference_offsets |= (0xffffffffu << start_bit) &
5416                               (0xffffffffu >> (32 - (start_bit + num_reference_fields)));
5417        }
5418      }
5419    }
5420  }
5421  klass->SetReferenceInstanceOffsets(reference_offsets);
5422}
5423
5424mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
5425                                           Handle<mirror::DexCache> dex_cache) {
5426  DCHECK(dex_cache.Get() != nullptr);
5427  mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
5428  if (resolved != nullptr) {
5429    return resolved;
5430  }
5431  uint32_t utf16_length;
5432  const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
5433  mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
5434  dex_cache->SetResolvedString(string_idx, string);
5435  return string;
5436}
5437
5438mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
5439                                        mirror::Class* referrer) {
5440  StackHandleScope<2> hs(Thread::Current());
5441  Handle<mirror::DexCache> dex_cache(hs.NewHandle(referrer->GetDexCache()));
5442  Handle<mirror::ClassLoader> class_loader(hs.NewHandle(referrer->GetClassLoader()));
5443  return ResolveType(dex_file, type_idx, dex_cache, class_loader);
5444}
5445
5446mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
5447                                        Handle<mirror::DexCache> dex_cache,
5448                                        Handle<mirror::ClassLoader> class_loader) {
5449  DCHECK(dex_cache.Get() != nullptr);
5450  mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
5451  if (resolved == nullptr) {
5452    Thread* self = Thread::Current();
5453    const char* descriptor = dex_file.StringByTypeIdx(type_idx);
5454    resolved = FindClass(self, descriptor, class_loader);
5455    if (resolved != nullptr) {
5456      // TODO: we used to throw here if resolved's class loader was not the
5457      //       boot class loader. This was to permit different classes with the
5458      //       same name to be loaded simultaneously by different loaders
5459      dex_cache->SetResolvedType(type_idx, resolved);
5460    } else {
5461      CHECK(self->IsExceptionPending())
5462          << "Expected pending exception for failed resolution of: " << descriptor;
5463      // Convert a ClassNotFoundException to a NoClassDefFoundError.
5464      StackHandleScope<1> hs(self);
5465      Handle<mirror::Throwable> cause(hs.NewHandle(self->GetException(nullptr)));
5466      if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
5467        DCHECK(resolved == nullptr);  // No Handle needed to preserve resolved.
5468        self->ClearException();
5469        ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
5470        self->GetException(nullptr)->SetCause(cause.Get());
5471      }
5472    }
5473  }
5474  DCHECK((resolved == nullptr) || resolved->IsResolved() || resolved->IsErroneous())
5475          << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
5476  return resolved;
5477}
5478
5479mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file, uint32_t method_idx,
5480                                              Handle<mirror::DexCache> dex_cache,
5481                                              Handle<mirror::ClassLoader> class_loader,
5482                                              Handle<mirror::ArtMethod> referrer,
5483                                              InvokeType type) {
5484  DCHECK(dex_cache.Get() != nullptr);
5485  // Check for hit in the dex cache.
5486  mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
5487  if (resolved != nullptr && !resolved->IsRuntimeMethod()) {
5488    return resolved;
5489  }
5490  // Fail, get the declaring class.
5491  const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
5492  mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
5493  if (klass == nullptr) {
5494    DCHECK(Thread::Current()->IsExceptionPending());
5495    return nullptr;
5496  }
5497  // Scan using method_idx, this saves string compares but will only hit for matching dex
5498  // caches/files.
5499  switch (type) {
5500    case kDirect:  // Fall-through.
5501    case kStatic:
5502      resolved = klass->FindDirectMethod(dex_cache.Get(), method_idx);
5503      break;
5504    case kInterface:
5505      resolved = klass->FindInterfaceMethod(dex_cache.Get(), method_idx);
5506      DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
5507      break;
5508    case kSuper:  // Fall-through.
5509    case kVirtual:
5510      resolved = klass->FindVirtualMethod(dex_cache.Get(), method_idx);
5511      break;
5512    default:
5513      LOG(FATAL) << "Unreachable - invocation type: " << type;
5514      UNREACHABLE();
5515  }
5516  if (resolved == nullptr) {
5517    // Search by name, which works across dex files.
5518    const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5519    const Signature signature = dex_file.GetMethodSignature(method_id);
5520    switch (type) {
5521      case kDirect:  // Fall-through.
5522      case kStatic:
5523        resolved = klass->FindDirectMethod(name, signature);
5524        break;
5525      case kInterface:
5526        resolved = klass->FindInterfaceMethod(name, signature);
5527        DCHECK(resolved == nullptr || resolved->GetDeclaringClass()->IsInterface());
5528        break;
5529      case kSuper:  // Fall-through.
5530      case kVirtual:
5531        resolved = klass->FindVirtualMethod(name, signature);
5532        break;
5533    }
5534  }
5535  // If we found a method, check for incompatible class changes.
5536  if (LIKELY(resolved != nullptr && !resolved->CheckIncompatibleClassChange(type))) {
5537    // Be a good citizen and update the dex cache to speed subsequent calls.
5538    dex_cache->SetResolvedMethod(method_idx, resolved);
5539    return resolved;
5540  } else {
5541    // If we had a method, it's an incompatible-class-change error.
5542    if (resolved != nullptr) {
5543      ThrowIncompatibleClassChangeError(type, resolved->GetInvokeType(), resolved, referrer.Get());
5544    } else {
5545      // We failed to find the method which means either an access error, an incompatible class
5546      // change, or no such method. First try to find the method among direct and virtual methods.
5547      const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
5548      const Signature signature = dex_file.GetMethodSignature(method_id);
5549      switch (type) {
5550        case kDirect:
5551        case kStatic:
5552          resolved = klass->FindVirtualMethod(name, signature);
5553          // Note: kDirect and kStatic are also mutually exclusive, but in that case we would
5554          //       have had a resolved method before, which triggers the "true" branch above.
5555          break;
5556        case kInterface:
5557        case kVirtual:
5558        case kSuper:
5559          resolved = klass->FindDirectMethod(name, signature);
5560          break;
5561      }
5562
5563      // If we found something, check that it can be accessed by the referrer.
5564      if (resolved != nullptr && referrer.Get() != nullptr) {
5565        mirror::Class* methods_class = resolved->GetDeclaringClass();
5566        mirror::Class* referring_class = referrer->GetDeclaringClass();
5567        if (!referring_class->CanAccess(methods_class)) {
5568          ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
5569                                                        resolved, type);
5570          return nullptr;
5571        } else if (!referring_class->CanAccessMember(methods_class,
5572                                                     resolved->GetAccessFlags())) {
5573          ThrowIllegalAccessErrorMethod(referring_class, resolved);
5574          return nullptr;
5575        }
5576      }
5577
5578      // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
5579      // methods and throw if we find the method there. If we find nothing, throw a
5580      // NoSuchMethodError.
5581      switch (type) {
5582        case kDirect:
5583        case kStatic:
5584          if (resolved != nullptr) {
5585            ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5586          } else {
5587            resolved = klass->FindInterfaceMethod(name, signature);
5588            if (resolved != nullptr) {
5589              ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5590            } else {
5591              ThrowNoSuchMethodError(type, klass, name, signature);
5592            }
5593          }
5594          break;
5595        case kInterface:
5596          if (resolved != nullptr) {
5597            ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5598          } else {
5599            resolved = klass->FindVirtualMethod(name, signature);
5600            if (resolved != nullptr) {
5601              ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer.Get());
5602            } else {
5603              ThrowNoSuchMethodError(type, klass, name, signature);
5604            }
5605          }
5606          break;
5607        case kSuper:
5608          if (resolved != nullptr) {
5609            ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5610          } else {
5611            ThrowNoSuchMethodError(type, klass, name, signature);
5612          }
5613          break;
5614        case kVirtual:
5615          if (resolved != nullptr) {
5616            ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer.Get());
5617          } else {
5618            resolved = klass->FindInterfaceMethod(name, signature);
5619            if (resolved != nullptr) {
5620              ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer.Get());
5621            } else {
5622              ThrowNoSuchMethodError(type, klass, name, signature);
5623            }
5624          }
5625          break;
5626      }
5627    }
5628    DCHECK(Thread::Current()->IsExceptionPending());
5629    return nullptr;
5630  }
5631}
5632
5633mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
5634                                            Handle<mirror::DexCache> dex_cache,
5635                                            Handle<mirror::ClassLoader> class_loader,
5636                                            bool is_static) {
5637  DCHECK(dex_cache.Get() != nullptr);
5638  mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
5639  if (resolved != nullptr) {
5640    return resolved;
5641  }
5642  const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
5643  Thread* const self = Thread::Current();
5644  StackHandleScope<1> hs(self);
5645  Handle<mirror::Class> klass(
5646      hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
5647  if (klass.Get() == nullptr) {
5648    DCHECK(Thread::Current()->IsExceptionPending());
5649    return nullptr;
5650  }
5651
5652  if (is_static) {
5653    resolved = mirror::Class::FindStaticField(self, klass, dex_cache.Get(), field_idx);
5654  } else {
5655    resolved = klass->FindInstanceField(dex_cache.Get(), field_idx);
5656  }
5657
5658  if (resolved == nullptr) {
5659    const char* name = dex_file.GetFieldName(field_id);
5660    const char* type = dex_file.GetFieldTypeDescriptor(field_id);
5661    if (is_static) {
5662      resolved = mirror::Class::FindStaticField(self, klass, name, type);
5663    } else {
5664      resolved = klass->FindInstanceField(name, type);
5665    }
5666    if (resolved == nullptr) {
5667      ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass.Get(), type, name);
5668      return nullptr;
5669    }
5670  }
5671  dex_cache->SetResolvedField(field_idx, resolved);
5672  return resolved;
5673}
5674
5675mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
5676                                               uint32_t field_idx,
5677                                               Handle<mirror::DexCache> dex_cache,
5678                                               Handle<mirror::ClassLoader> class_loader) {
5679  DCHECK(dex_cache.Get() != nullptr);
5680  mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
5681  if (resolved != nullptr) {
5682    return resolved;
5683  }
5684  const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
5685  Thread* self = Thread::Current();
5686  StackHandleScope<1> hs(self);
5687  Handle<mirror::Class> klass(
5688      hs.NewHandle(ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader)));
5689  if (klass.Get() == nullptr) {
5690    DCHECK(Thread::Current()->IsExceptionPending());
5691    return nullptr;
5692  }
5693
5694  StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
5695  StringPiece type(dex_file.StringDataByIdx(
5696      dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
5697  resolved = mirror::Class::FindField(self, klass, name, type);
5698  if (resolved != nullptr) {
5699    dex_cache->SetResolvedField(field_idx, resolved);
5700  } else {
5701    ThrowNoSuchFieldError("", klass.Get(), type, name);
5702  }
5703  return resolved;
5704}
5705
5706const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
5707                                      uint32_t* length) {
5708  mirror::Class* declaring_class = referrer->GetDeclaringClass();
5709  mirror::DexCache* dex_cache = declaring_class->GetDexCache();
5710  const DexFile& dex_file = *dex_cache->GetDexFile();
5711  const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
5712  return dex_file.GetMethodShorty(method_id, length);
5713}
5714
5715void ClassLinker::DumpAllClasses(int flags) {
5716  if (dex_cache_image_class_lookup_required_) {
5717    MoveImageClassesToClassTable();
5718  }
5719  // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
5720  // lock held, because it might need to resolve a field's type, which would try to take the lock.
5721  std::vector<mirror::Class*> all_classes;
5722  {
5723    ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
5724    for (GcRoot<mirror::Class>& it : class_table_) {
5725      all_classes.push_back(it.Read());
5726    }
5727  }
5728
5729  for (size_t i = 0; i < all_classes.size(); ++i) {
5730    all_classes[i]->DumpClass(std::cerr, flags);
5731  }
5732}
5733
5734static OatFile::OatMethod CreateOatMethod(const void* code, const uint8_t* gc_map,
5735                                          bool is_portable) {
5736  CHECK_EQ(kUsePortableCompiler, is_portable);
5737  CHECK(code != nullptr);
5738  const uint8_t* base;
5739  uint32_t code_offset, gc_map_offset;
5740  if (gc_map == nullptr) {
5741    base = reinterpret_cast<const uint8_t*>(code);  // Base of data points at code.
5742    base -= sizeof(void*);  // Move backward so that code_offset != 0.
5743    code_offset = sizeof(void*);
5744    gc_map_offset = 0;
5745  } else {
5746    // TODO: 64bit support.
5747    base = nullptr;  // Base of data in oat file, ie 0.
5748    code_offset = PointerToLowMemUInt32(code);
5749    gc_map_offset = PointerToLowMemUInt32(gc_map);
5750  }
5751  return OatFile::OatMethod(base, code_offset, gc_map_offset);
5752}
5753
5754bool ClassLinker::IsPortableResolutionStub(const void* entry_point) const {
5755  return (entry_point == GetPortableResolutionStub()) ||
5756      (portable_resolution_trampoline_ == entry_point);
5757}
5758
5759bool ClassLinker::IsQuickResolutionStub(const void* entry_point) const {
5760  return (entry_point == GetQuickResolutionStub()) ||
5761      (quick_resolution_trampoline_ == entry_point);
5762}
5763
5764bool ClassLinker::IsPortableToInterpreterBridge(const void* entry_point) const {
5765  return (entry_point == GetPortableToInterpreterBridge());
5766  // TODO: portable_to_interpreter_bridge_trampoline_ == entry_point;
5767}
5768
5769bool ClassLinker::IsQuickToInterpreterBridge(const void* entry_point) const {
5770  return (entry_point == GetQuickToInterpreterBridge()) ||
5771      (quick_to_interpreter_bridge_trampoline_ == entry_point);
5772}
5773
5774bool ClassLinker::IsQuickGenericJniStub(const void* entry_point) const {
5775  return (entry_point == GetQuickGenericJniStub()) ||
5776      (quick_generic_jni_trampoline_ == entry_point);
5777}
5778
5779const void* ClassLinker::GetRuntimeQuickGenericJniStub() const {
5780  return GetQuickGenericJniStub();
5781}
5782
5783void ClassLinker::SetEntryPointsToCompiledCode(mirror::ArtMethod* method, const void* method_code,
5784                                               bool is_portable) const {
5785  OatFile::OatMethod oat_method = CreateOatMethod(method_code, nullptr, is_portable);
5786  oat_method.LinkMethod(method);
5787  method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5788  // Create bridges to transition between different kinds of compiled bridge.
5789  if (method->GetEntryPointFromPortableCompiledCode() == nullptr) {
5790    method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5791  } else {
5792    CHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
5793    method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
5794    method->SetIsPortableCompiled();
5795  }
5796}
5797
5798void ClassLinker::SetEntryPointsToInterpreter(mirror::ArtMethod* method) const {
5799  if (!method->IsNative()) {
5800    method->SetEntryPointFromInterpreter(artInterpreterToInterpreterBridge);
5801    method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
5802    method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
5803  } else {
5804    const void* quick_method_code = GetQuickGenericJniStub();
5805    OatFile::OatMethod oat_method = CreateOatMethod(quick_method_code, nullptr, false);
5806    oat_method.LinkMethod(method);
5807    method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
5808    method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
5809  }
5810}
5811
5812void ClassLinker::DumpForSigQuit(std::ostream& os) {
5813  Thread* self = Thread::Current();
5814  if (dex_cache_image_class_lookup_required_) {
5815    ScopedObjectAccess soa(self);
5816    MoveImageClassesToClassTable();
5817  }
5818  ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
5819  os << "Zygote loaded classes=" << pre_zygote_class_table_.Size() << " post zygote classes="
5820     << class_table_.Size() << "\n";
5821}
5822
5823size_t ClassLinker::NumLoadedClasses() {
5824  if (dex_cache_image_class_lookup_required_) {
5825    MoveImageClassesToClassTable();
5826  }
5827  ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
5828  // Only return non zygote classes since these are the ones which apps which care about.
5829  return class_table_.Size();
5830}
5831
5832pid_t ClassLinker::GetClassesLockOwner() {
5833  return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
5834}
5835
5836pid_t ClassLinker::GetDexLockOwner() {
5837  return dex_lock_.GetExclusiveOwnerTid();
5838}
5839
5840void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
5841  DCHECK(!init_done_);
5842
5843  DCHECK(klass != nullptr);
5844  DCHECK(klass->GetClassLoader() == nullptr);
5845
5846  mirror::ObjectArray<mirror::Class>* class_roots = class_roots_.Read();
5847  DCHECK(class_roots != nullptr);
5848  DCHECK(class_roots->Get(class_root) == nullptr);
5849  class_roots->Set<false>(class_root, klass);
5850}
5851
5852const char* ClassLinker::GetClassRootDescriptor(ClassRoot class_root) {
5853  static const char* class_roots_descriptors[] = {
5854    "Ljava/lang/Class;",
5855    "Ljava/lang/Object;",
5856    "[Ljava/lang/Class;",
5857    "[Ljava/lang/Object;",
5858    "Ljava/lang/String;",
5859    "Ljava/lang/DexCache;",
5860    "Ljava/lang/ref/Reference;",
5861    "Ljava/lang/reflect/ArtField;",
5862    "Ljava/lang/reflect/ArtMethod;",
5863    "Ljava/lang/reflect/Proxy;",
5864    "[Ljava/lang/String;",
5865    "[Ljava/lang/reflect/ArtField;",
5866    "[Ljava/lang/reflect/ArtMethod;",
5867    "Ljava/lang/ClassLoader;",
5868    "Ljava/lang/Throwable;",
5869    "Ljava/lang/ClassNotFoundException;",
5870    "Ljava/lang/StackTraceElement;",
5871    "Z",
5872    "B",
5873    "C",
5874    "D",
5875    "F",
5876    "I",
5877    "J",
5878    "S",
5879    "V",
5880    "[Z",
5881    "[B",
5882    "[C",
5883    "[D",
5884    "[F",
5885    "[I",
5886    "[J",
5887    "[S",
5888    "[Ljava/lang/StackTraceElement;",
5889  };
5890  static_assert(arraysize(class_roots_descriptors) == size_t(kClassRootsMax),
5891                "Mismatch between class descriptors and class-root enum");
5892
5893  const char* descriptor = class_roots_descriptors[class_root];
5894  CHECK(descriptor != nullptr);
5895  return descriptor;
5896}
5897
5898std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& root)
5899    const {
5900  std::string temp;
5901  return ComputeModifiedUtf8Hash(root.Read()->GetDescriptor(&temp));
5902}
5903
5904bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5905                                                        const GcRoot<mirror::Class>& b) {
5906  if (a.Read()->GetClassLoader() != b.Read()->GetClassLoader()) {
5907    return false;
5908  }
5909  std::string temp;
5910  return a.Read()->DescriptorEquals(b.Read()->GetDescriptor(&temp));
5911}
5912
5913std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(
5914    const std::pair<const char*, mirror::ClassLoader*>& element) const {
5915  return ComputeModifiedUtf8Hash(element.first);
5916}
5917
5918bool ClassLinker::ClassDescriptorHashEquals::operator()(
5919    const GcRoot<mirror::Class>& a, const std::pair<const char*, mirror::ClassLoader*>& b) {
5920  if (a.Read()->GetClassLoader() != b.second) {
5921    return false;
5922  }
5923  return a.Read()->DescriptorEquals(b.first);
5924}
5925
5926bool ClassLinker::ClassDescriptorHashEquals::operator()(const GcRoot<mirror::Class>& a,
5927                                                        const char* descriptor) {
5928  return a.Read()->DescriptorEquals(descriptor);
5929}
5930
5931std::size_t ClassLinker::ClassDescriptorHashEquals::operator()(const char* descriptor) const {
5932  return ComputeModifiedUtf8Hash(descriptor);
5933}
5934
5935}  // namespace art
5936