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