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