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