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