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