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