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