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