class_linker.cc revision 0177e53ea521ad58b70c305700dab32f1ac773b7
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 <sys/types.h>
23#include <sys/wait.h>
24
25#include <deque>
26#include <string>
27#include <utility>
28#include <vector>
29
30#include "base/casts.h"
31#include "base/logging.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/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
40#include "gc/heap.h"
41#include "gc/space/image_space.h"
42#include "intern_table.h"
43#include "interpreter/interpreter.h"
44#include "leb128.h"
45#include "oat.h"
46#include "oat_file.h"
47#include "mirror/art_field-inl.h"
48#include "mirror/art_method-inl.h"
49#include "mirror/class.h"
50#include "mirror/class-inl.h"
51#include "mirror/class_loader.h"
52#include "mirror/dex_cache-inl.h"
53#include "mirror/iftable-inl.h"
54#include "mirror/object-inl.h"
55#include "mirror/object_array-inl.h"
56#include "mirror/proxy.h"
57#include "mirror/stack_trace_element.h"
58#include "object_utils.h"
59#include "os.h"
60#include "runtime.h"
61#include "entrypoints/entrypoint_utils.h"
62#include "ScopedLocalRef.h"
63#include "scoped_thread_state_change.h"
64#include "sirt_ref.h"
65#include "stack_indirect_reference_table.h"
66#include "thread.h"
67#include "UniquePtr.h"
68#include "utils.h"
69#include "verifier/method_verifier.h"
70#include "well_known_classes.h"
71
72namespace art {
73
74static void ThrowNoClassDefFoundError(const char* fmt, ...)
75    __attribute__((__format__(__printf__, 1, 2)))
76    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
77static void ThrowNoClassDefFoundError(const char* fmt, ...) {
78  va_list args;
79  va_start(args, fmt);
80  Thread* self = Thread::Current();
81  ThrowLocation throw_location = self->GetCurrentLocationForThrow();
82  self->ThrowNewExceptionV(throw_location, "Ljava/lang/NoClassDefFoundError;", fmt, args);
83  va_end(args);
84}
85
86static void ThrowEarlierClassFailure(mirror::Class* c)
87    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
88  // The class failed to initialize on a previous attempt, so we want to throw
89  // a NoClassDefFoundError (v2 2.17.5).  The exception to this rule is if we
90  // failed in verification, in which case v2 5.4.1 says we need to re-throw
91  // the previous error.
92  if (!Runtime::Current()->IsCompiler()) {  // Give info if this occurs at runtime.
93    LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
94  }
95
96  CHECK(c->IsErroneous()) << PrettyClass(c) << " " << c->GetStatus();
97  Thread* self = Thread::Current();
98  ThrowLocation throw_location = self->GetCurrentLocationForThrow();
99  if (c->GetVerifyErrorClass() != NULL) {
100    // TODO: change the verifier to store an _instance_, with a useful detail message?
101    ClassHelper ve_ch(c->GetVerifyErrorClass());
102    self->ThrowNewException(throw_location, ve_ch.GetDescriptor(), PrettyDescriptor(c).c_str());
103  } else {
104    self->ThrowNewException(throw_location, "Ljava/lang/NoClassDefFoundError;",
105                            PrettyDescriptor(c).c_str());
106  }
107}
108
109static void WrapExceptionInInitializer() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
110  Thread* self = Thread::Current();
111  JNIEnv* env = self->GetJniEnv();
112
113  ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
114  CHECK(cause.get() != NULL);
115
116  env->ExceptionClear();
117  bool is_error = env->IsInstanceOf(cause.get(), WellKnownClasses::java_lang_Error);
118  env->Throw(cause.get());
119
120  // We only wrap non-Error exceptions; an Error can just be used as-is.
121  if (!is_error) {
122    ThrowLocation throw_location = self->GetCurrentLocationForThrow();
123    self->ThrowNewWrappedException(throw_location, "Ljava/lang/ExceptionInInitializerError;", NULL);
124  }
125}
126
127static size_t Hash(const char* s) {
128  // This is the java.lang.String hashcode for convenience, not interoperability.
129  size_t hash = 0;
130  for (; *s != '\0'; ++s) {
131    hash = hash * 31 + *s;
132  }
133  return hash;
134}
135
136const char* ClassLinker::class_roots_descriptors_[] = {
137  "Ljava/lang/Class;",
138  "Ljava/lang/Object;",
139  "[Ljava/lang/Class;",
140  "[Ljava/lang/Object;",
141  "Ljava/lang/String;",
142  "Ljava/lang/DexCache;",
143  "Ljava/lang/ref/Reference;",
144  "Ljava/lang/reflect/ArtField;",
145  "Ljava/lang/reflect/ArtMethod;",
146  "Ljava/lang/reflect/Proxy;",
147  "[Ljava/lang/String;",
148  "[Ljava/lang/reflect/ArtField;",
149  "[Ljava/lang/reflect/ArtMethod;",
150  "Ljava/lang/ClassLoader;",
151  "Ljava/lang/Throwable;",
152  "Ljava/lang/ClassNotFoundException;",
153  "Ljava/lang/StackTraceElement;",
154  "Z",
155  "B",
156  "C",
157  "D",
158  "F",
159  "I",
160  "J",
161  "S",
162  "V",
163  "[Z",
164  "[B",
165  "[C",
166  "[D",
167  "[F",
168  "[I",
169  "[J",
170  "[S",
171  "[Ljava/lang/StackTraceElement;",
172};
173
174ClassLinker::ClassLinker(InternTable* intern_table)
175    // dex_lock_ is recursive as it may be used in stack dumping.
176    : dex_lock_("ClassLinker dex lock", kDefaultMutexLevel),
177      dex_cache_image_class_lookup_required_(false),
178      failed_dex_cache_class_lookups_(0),
179      class_roots_(NULL),
180      array_iftable_(NULL),
181      init_done_(false),
182      dex_caches_dirty_(false),
183      class_table_dirty_(false),
184      intern_table_(intern_table),
185      portable_resolution_trampoline_(NULL),
186      quick_resolution_trampoline_(NULL),
187      portable_imt_conflict_trampoline_(NULL),
188      quick_imt_conflict_trampoline_(NULL) {
189  CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
190}
191
192void ClassLinker::InitFromCompiler(const std::vector<const DexFile*>& boot_class_path) {
193  VLOG(startup) << "ClassLinker::Init";
194  CHECK(Runtime::Current()->IsCompiler());
195
196  CHECK(!init_done_);
197
198  // java_lang_Class comes first, it's needed for AllocClass
199  Thread* self = Thread::Current();
200  gc::Heap* heap = Runtime::Current()->GetHeap();
201  // The GC can't handle an object with a null class since we can't get the size of this object.
202  heap->IncrementDisableMovingGC(self);
203  SirtRef<mirror::Class> java_lang_Class(self, down_cast<mirror::Class*>(
204      heap->AllocNonMovableObject<true>(self, nullptr, sizeof(mirror::ClassClass))));
205  CHECK(java_lang_Class.get() != NULL);
206  mirror::Class::SetClassClass(java_lang_Class.get());
207  java_lang_Class->SetClass(java_lang_Class.get());
208  java_lang_Class->SetClassSize(sizeof(mirror::ClassClass));
209  heap->DecrementDisableMovingGC(self);
210  // AllocClass(mirror::Class*) can now be used
211
212  // Class[] is used for reflection support.
213  SirtRef<mirror::Class> class_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class)));
214  class_array_class->SetComponentType(java_lang_Class.get());
215
216  // java_lang_Object comes next so that object_array_class can be created.
217  SirtRef<mirror::Class> java_lang_Object(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class)));
218  CHECK(java_lang_Object.get() != NULL);
219  // backfill Object as the super class of Class.
220  java_lang_Class->SetSuperClass(java_lang_Object.get());
221  java_lang_Object->SetStatus(mirror::Class::kStatusLoaded, self);
222
223  // Object[] next to hold class roots.
224  SirtRef<mirror::Class> object_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class)));
225  object_array_class->SetComponentType(java_lang_Object.get());
226
227  // Setup the char class to be used for char[].
228  SirtRef<mirror::Class> char_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class)));
229
230  // Setup the char[] class to be used for String.
231  SirtRef<mirror::Class> char_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class)));
232  char_array_class->SetComponentType(char_class.get());
233  mirror::CharArray::SetArrayClass(char_array_class.get());
234
235  // Setup String.
236  SirtRef<mirror::Class> java_lang_String(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::StringClass)));
237  mirror::String::SetClass(java_lang_String.get());
238  java_lang_String->SetObjectSize(sizeof(mirror::String));
239  java_lang_String->SetStatus(mirror::Class::kStatusResolved, self);
240
241  // Create storage for root classes, save away our work so far (requires descriptors).
242  class_roots_ = mirror::ObjectArray<mirror::Class>::Alloc(self, object_array_class.get(),
243                                                           kClassRootsMax);
244  CHECK(class_roots_ != NULL);
245  SetClassRoot(kJavaLangClass, java_lang_Class.get());
246  SetClassRoot(kJavaLangObject, java_lang_Object.get());
247  SetClassRoot(kClassArrayClass, class_array_class.get());
248  SetClassRoot(kObjectArrayClass, object_array_class.get());
249  SetClassRoot(kCharArrayClass, char_array_class.get());
250  SetClassRoot(kJavaLangString, java_lang_String.get());
251
252  // Setup the primitive type classes.
253  SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass(self, Primitive::kPrimBoolean));
254  SetClassRoot(kPrimitiveByte, CreatePrimitiveClass(self, Primitive::kPrimByte));
255  SetClassRoot(kPrimitiveShort, CreatePrimitiveClass(self, Primitive::kPrimShort));
256  SetClassRoot(kPrimitiveInt, CreatePrimitiveClass(self, Primitive::kPrimInt));
257  SetClassRoot(kPrimitiveLong, CreatePrimitiveClass(self, Primitive::kPrimLong));
258  SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass(self, Primitive::kPrimFloat));
259  SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass(self, Primitive::kPrimDouble));
260  SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass(self, Primitive::kPrimVoid));
261
262  // Create array interface entries to populate once we can load system classes.
263  array_iftable_ = AllocIfTable(self, 2);
264
265  // Create int array type for AllocDexCache (done in AppendToBootClassPath).
266  SirtRef<mirror::Class> int_array_class(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::Class)));
267  int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
268  mirror::IntArray::SetArrayClass(int_array_class.get());
269  SetClassRoot(kIntArrayClass, int_array_class.get());
270
271  // now that these are registered, we can use AllocClass() and AllocObjectArray
272
273  // Set up DexCache. This cannot be done later since AppendToBootClassPath calls AllocDexCache.
274  SirtRef<mirror::Class>
275      java_lang_DexCache(self, AllocClass(self, java_lang_Class.get(), sizeof(mirror::DexCacheClass)));
276  SetClassRoot(kJavaLangDexCache, java_lang_DexCache.get());
277  java_lang_DexCache->SetObjectSize(sizeof(mirror::DexCache));
278  java_lang_DexCache->SetStatus(mirror::Class::kStatusResolved, self);
279
280  // Constructor, Field, Method, and AbstractMethod are necessary so that FindClass can link members.
281  SirtRef<mirror::Class> java_lang_reflect_ArtField(self, AllocClass(self, java_lang_Class.get(),
282                                                                     sizeof(mirror::ArtFieldClass)));
283  CHECK(java_lang_reflect_ArtField.get() != NULL);
284  java_lang_reflect_ArtField->SetObjectSize(sizeof(mirror::ArtField));
285  SetClassRoot(kJavaLangReflectArtField, java_lang_reflect_ArtField.get());
286  java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusResolved, self);
287  mirror::ArtField::SetClass(java_lang_reflect_ArtField.get());
288
289  SirtRef<mirror::Class> java_lang_reflect_ArtMethod(self, AllocClass(self, java_lang_Class.get(),
290                                                                      sizeof(mirror::ArtMethodClass)));
291  CHECK(java_lang_reflect_ArtMethod.get() != NULL);
292  java_lang_reflect_ArtMethod->SetObjectSize(sizeof(mirror::ArtMethod));
293  SetClassRoot(kJavaLangReflectArtMethod, java_lang_reflect_ArtMethod.get());
294  java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusResolved, self);
295
296  mirror::ArtMethod::SetClass(java_lang_reflect_ArtMethod.get());
297
298  // Set up array classes for string, field, method
299  SirtRef<mirror::Class> object_array_string(self, AllocClass(self, java_lang_Class.get(),
300                                                              sizeof(mirror::Class)));
301  object_array_string->SetComponentType(java_lang_String.get());
302  SetClassRoot(kJavaLangStringArrayClass, object_array_string.get());
303
304  SirtRef<mirror::Class> object_array_art_method(self, AllocClass(self, java_lang_Class.get(),
305                                                                  sizeof(mirror::Class)));
306  object_array_art_method->SetComponentType(java_lang_reflect_ArtMethod.get());
307  SetClassRoot(kJavaLangReflectArtMethodArrayClass, object_array_art_method.get());
308
309  SirtRef<mirror::Class> object_array_art_field(self, AllocClass(self, java_lang_Class.get(),
310                                                                 sizeof(mirror::Class)));
311  object_array_art_field->SetComponentType(java_lang_reflect_ArtField.get());
312  SetClassRoot(kJavaLangReflectArtFieldArrayClass, object_array_art_field.get());
313
314  // Setup boot_class_path_ and register class_path now that we can use AllocObjectArray to create
315  // DexCache instances. Needs to be after String, Field, Method arrays since AllocDexCache uses
316  // these roots.
317  CHECK_NE(0U, boot_class_path.size());
318  for (size_t i = 0; i != boot_class_path.size(); ++i) {
319    const DexFile* dex_file = boot_class_path[i];
320    CHECK(dex_file != NULL);
321    AppendToBootClassPath(*dex_file);
322  }
323
324  // now we can use FindSystemClass
325
326  // run char class through InitializePrimitiveClass to finish init
327  InitializePrimitiveClass(char_class.get(), Primitive::kPrimChar);
328  SetClassRoot(kPrimitiveChar, char_class.get());  // needs descriptor
329
330  // Create runtime resolution and imt conflict methods. Also setup the default imt.
331  Runtime* runtime = Runtime::Current();
332  runtime->SetResolutionMethod(runtime->CreateResolutionMethod());
333  runtime->SetImtConflictMethod(runtime->CreateImtConflictMethod());
334  runtime->SetDefaultImt(runtime->CreateDefaultImt(this));
335
336  // Object, String and DexCache need to be rerun through FindSystemClass to finish init
337  java_lang_Object->SetStatus(mirror::Class::kStatusNotReady, self);
338  mirror::Class* Object_class = FindSystemClass("Ljava/lang/Object;");
339  CHECK_EQ(java_lang_Object.get(), Object_class);
340  CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(mirror::Object));
341  java_lang_String->SetStatus(mirror::Class::kStatusNotReady, self);
342  mirror::Class* String_class = FindSystemClass("Ljava/lang/String;");
343  CHECK_EQ(java_lang_String.get(), String_class);
344  CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(mirror::String));
345  java_lang_DexCache->SetStatus(mirror::Class::kStatusNotReady, self);
346  mirror::Class* DexCache_class = FindSystemClass("Ljava/lang/DexCache;");
347  CHECK_EQ(java_lang_String.get(), String_class);
348  CHECK_EQ(java_lang_DexCache.get(), DexCache_class);
349  CHECK_EQ(java_lang_DexCache->GetObjectSize(), sizeof(mirror::DexCache));
350
351  // Setup the primitive array type classes - can't be done until Object has a vtable.
352  SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
353  mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
354
355  SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
356  mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
357
358  mirror::Class* found_char_array_class = FindSystemClass("[C");
359  CHECK_EQ(char_array_class.get(), found_char_array_class);
360
361  SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
362  mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
363
364  mirror::Class* found_int_array_class = FindSystemClass("[I");
365  CHECK_EQ(int_array_class.get(), found_int_array_class);
366
367  SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
368  mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
369
370  SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
371  mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
372
373  SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
374  mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
375
376  mirror::Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
377  CHECK_EQ(class_array_class.get(), found_class_array_class);
378
379  mirror::Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
380  CHECK_EQ(object_array_class.get(), found_object_array_class);
381
382  // Setup the single, global copy of "iftable".
383  mirror::Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
384  CHECK(java_lang_Cloneable != NULL);
385  mirror::Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
386  CHECK(java_io_Serializable != NULL);
387  // We assume that Cloneable/Serializable don't have superinterfaces -- normally we'd have to
388  // crawl up and explicitly list all of the supers as well.
389  array_iftable_->SetInterface(0, java_lang_Cloneable);
390  array_iftable_->SetInterface(1, java_io_Serializable);
391
392  // Sanity check Class[] and Object[]'s interfaces.
393  ClassHelper kh(class_array_class.get());
394  CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0));
395  CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1));
396  kh.ChangeClass(object_array_class.get());
397  CHECK_EQ(java_lang_Cloneable, kh.GetDirectInterface(0));
398  CHECK_EQ(java_io_Serializable, kh.GetDirectInterface(1));
399  // Run Class, ArtField, and ArtMethod through FindSystemClass. This initializes their
400  // dex_cache_ fields and register them in class_table_.
401  mirror::Class* Class_class = FindSystemClass("Ljava/lang/Class;");
402  CHECK_EQ(java_lang_Class.get(), Class_class);
403
404  java_lang_reflect_ArtMethod->SetStatus(mirror::Class::kStatusNotReady, self);
405  mirror::Class* Art_method_class = FindSystemClass("Ljava/lang/reflect/ArtMethod;");
406  CHECK_EQ(java_lang_reflect_ArtMethod.get(), Art_method_class);
407
408  java_lang_reflect_ArtField->SetStatus(mirror::Class::kStatusNotReady, self);
409  mirror::Class* Art_field_class = FindSystemClass("Ljava/lang/reflect/ArtField;");
410  CHECK_EQ(java_lang_reflect_ArtField.get(), Art_field_class);
411
412  mirror::Class* String_array_class = FindSystemClass(class_roots_descriptors_[kJavaLangStringArrayClass]);
413  CHECK_EQ(object_array_string.get(), String_array_class);
414
415  mirror::Class* Art_method_array_class =
416      FindSystemClass(class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]);
417  CHECK_EQ(object_array_art_method.get(), Art_method_array_class);
418
419  mirror::Class* Art_field_array_class =
420      FindSystemClass(class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]);
421  CHECK_EQ(object_array_art_field.get(), Art_field_array_class);
422
423  // End of special init trickery, subsequent classes may be loaded via FindSystemClass.
424
425  // Create java.lang.reflect.Proxy root.
426  mirror::Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
427  SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
428
429  // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
430  mirror::Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
431  SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
432  mirror::Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
433  java_lang_ref_FinalizerReference->SetAccessFlags(
434      java_lang_ref_FinalizerReference->GetAccessFlags() |
435          kAccClassIsReference | kAccClassIsFinalizerReference);
436  mirror::Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
437  java_lang_ref_PhantomReference->SetAccessFlags(
438      java_lang_ref_PhantomReference->GetAccessFlags() |
439          kAccClassIsReference | kAccClassIsPhantomReference);
440  mirror::Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
441  java_lang_ref_SoftReference->SetAccessFlags(
442      java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
443  mirror::Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
444  java_lang_ref_WeakReference->SetAccessFlags(
445      java_lang_ref_WeakReference->GetAccessFlags() |
446          kAccClassIsReference | kAccClassIsWeakReference);
447
448  // Setup the ClassLoader, verifying the object_size_.
449  mirror::Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
450  CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(mirror::ClassLoader));
451  SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
452
453  // Set up java.lang.Throwable, java.lang.ClassNotFoundException, and
454  // java.lang.StackTraceElement as a convenience.
455  SetClassRoot(kJavaLangThrowable, FindSystemClass("Ljava/lang/Throwable;"));
456  mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
457  SetClassRoot(kJavaLangClassNotFoundException, FindSystemClass("Ljava/lang/ClassNotFoundException;"));
458  SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
459  SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
460  mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
461
462  FinishInit();
463
464  VLOG(startup) << "ClassLinker::InitFromCompiler exiting";
465}
466
467void ClassLinker::FinishInit() {
468  VLOG(startup) << "ClassLinker::FinishInit entering";
469
470  // Let the heap know some key offsets into java.lang.ref instances
471  // Note: we hard code the field indexes here rather than using FindInstanceField
472  // as the types of the field can't be resolved prior to the runtime being
473  // fully initialized
474  mirror::Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
475  mirror::Class* java_lang_ref_FinalizerReference =
476      FindSystemClass("Ljava/lang/ref/FinalizerReference;");
477
478  mirror::ArtField* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
479  FieldHelper fh(pendingNext);
480  CHECK_STREQ(fh.GetName(), "pendingNext");
481  CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
482
483  mirror::ArtField* queue = java_lang_ref_Reference->GetInstanceField(1);
484  fh.ChangeField(queue);
485  CHECK_STREQ(fh.GetName(), "queue");
486  CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/ref/ReferenceQueue;");
487
488  mirror::ArtField* queueNext = java_lang_ref_Reference->GetInstanceField(2);
489  fh.ChangeField(queueNext);
490  CHECK_STREQ(fh.GetName(), "queueNext");
491  CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/ref/Reference;");
492
493  mirror::ArtField* referent = java_lang_ref_Reference->GetInstanceField(3);
494  fh.ChangeField(referent);
495  CHECK_STREQ(fh.GetName(), "referent");
496  CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/Object;");
497
498  mirror::ArtField* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
499  fh.ChangeField(zombie);
500  CHECK_STREQ(fh.GetName(), "zombie");
501  CHECK_STREQ(fh.GetTypeDescriptor(), "Ljava/lang/Object;");
502
503  gc::Heap* heap = Runtime::Current()->GetHeap();
504  heap->SetReferenceOffsets(referent->GetOffset(),
505                            queue->GetOffset(),
506                            queueNext->GetOffset(),
507                            pendingNext->GetOffset(),
508                            zombie->GetOffset());
509
510  // ensure all class_roots_ are initialized
511  for (size_t i = 0; i < kClassRootsMax; i++) {
512    ClassRoot class_root = static_cast<ClassRoot>(i);
513    mirror::Class* klass = GetClassRoot(class_root);
514    CHECK(klass != NULL);
515    DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
516    // note SetClassRoot does additional validation.
517    // if possible add new checks there to catch errors early
518  }
519
520  CHECK(array_iftable_ != NULL);
521
522  // disable the slow paths in FindClass and CreatePrimitiveClass now
523  // that Object, Class, and Object[] are setup
524  init_done_ = true;
525
526  VLOG(startup) << "ClassLinker::FinishInit exiting";
527}
528
529void ClassLinker::RunRootClinits() {
530  Thread* self = Thread::Current();
531  for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
532    mirror::Class* c = GetClassRoot(ClassRoot(i));
533    if (!c->IsArrayClass() && !c->IsPrimitive()) {
534      SirtRef<mirror::Class> sirt_class(self, GetClassRoot(ClassRoot(i)));
535      EnsureInitialized(sirt_class, true, true);
536      self->AssertNoPendingException();
537    }
538  }
539}
540
541bool ClassLinker::GenerateOatFile(const char* dex_filename,
542                                  int oat_fd,
543                                  const char* oat_cache_filename,
544                                  std::string* error_msg) {
545  Locks::mutator_lock_->AssertNotHeld(Thread::Current());  // Avoid starving GC.
546  std::string dex2oat_string(GetAndroidRoot());
547  dex2oat_string += (kIsDebugBuild ? "/bin/dex2oatd" : "/bin/dex2oat");
548  const char* dex2oat = dex2oat_string.c_str();
549
550  const char* class_path = Runtime::Current()->GetClassPathString().c_str();
551
552  gc::Heap* heap = Runtime::Current()->GetHeap();
553  std::string boot_image_option_string("--boot-image=");
554  boot_image_option_string += heap->GetImageSpace()->GetImageFilename();
555  const char* boot_image_option = boot_image_option_string.c_str();
556
557  std::string dex_file_option_string("--dex-file=");
558  dex_file_option_string += dex_filename;
559  const char* dex_file_option = dex_file_option_string.c_str();
560
561  std::string oat_fd_option_string("--oat-fd=");
562  StringAppendF(&oat_fd_option_string, "%d", oat_fd);
563  const char* oat_fd_option = oat_fd_option_string.c_str();
564
565  std::string oat_location_option_string("--oat-location=");
566  oat_location_option_string += oat_cache_filename;
567  const char* oat_location_option = oat_location_option_string.c_str();
568
569  std::string oat_compiler_filter_string("-compiler-filter:");
570  Runtime::CompilerFilter filter = Runtime::Current()->GetCompilerFilter();
571  switch (filter) {
572    case Runtime::kInterpretOnly:
573      oat_compiler_filter_string += "interpret-only";
574      break;
575    case Runtime::kSpace:
576      oat_compiler_filter_string += "space";
577      break;
578    case Runtime::kBalanced:
579      oat_compiler_filter_string += "balanced";
580      break;
581    case Runtime::kSpeed:
582      oat_compiler_filter_string += "speed";
583      break;
584    case Runtime::kEverything:
585      oat_compiler_filter_string += "everything";
586      break;
587    default:
588      LOG(FATAL) << "Unexpected case: " << filter;
589  }
590  const char* oat_compiler_filter_option = oat_compiler_filter_string.c_str();
591
592  // fork and exec dex2oat
593  pid_t pid = fork();
594  if (pid == 0) {
595    // no allocation allowed between fork and exec
596
597    // change process groups, so we don't get reaped by ProcessManager
598    setpgid(0, 0);
599
600    // gLogVerbosity.class_linker = true;
601    VLOG(class_linker) << dex2oat
602                       << " --runtime-arg -Xms64m"
603                       << " --runtime-arg -Xmx64m"
604                       << " --runtime-arg -classpath"
605                       << " --runtime-arg " << class_path
606                       << " --runtime-arg " << oat_compiler_filter_option
607#if !defined(ART_TARGET)
608                       << " --host"
609#endif
610                       << " " << boot_image_option
611                       << " " << dex_file_option
612                       << " " << oat_fd_option
613                       << " " << oat_location_option;
614
615    execl(dex2oat, dex2oat,
616          "--runtime-arg", "-Xms64m",
617          "--runtime-arg", "-Xmx64m",
618          "--runtime-arg", "-classpath",
619          "--runtime-arg", class_path,
620          "--runtime-arg", oat_compiler_filter_option,
621#if !defined(ART_TARGET)
622          "--host",
623#endif
624          boot_image_option,
625          dex_file_option,
626          oat_fd_option,
627          oat_location_option,
628          NULL);
629
630    PLOG(FATAL) << "execl(" << dex2oat << ") failed";
631    return false;
632  } else {
633    // wait for dex2oat to finish
634    int status;
635    pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
636    if (got_pid != pid) {
637      *error_msg = StringPrintf("Failed to create oat file. Waitpid failed: wanted %d, got %d",
638                                pid, got_pid);
639      return false;
640    }
641    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
642      *error_msg = StringPrintf("Failed to create oat file. %s failed with dex-file '%s'",
643                                dex2oat, dex_filename);
644      return false;
645    }
646  }
647  return true;
648}
649
650const OatFile* ClassLinker::RegisterOatFile(const OatFile* oat_file) {
651  WriterMutexLock mu(Thread::Current(), dex_lock_);
652  if (kIsDebugBuild) {
653    for (size_t i = 0; i < oat_files_.size(); ++i) {
654      CHECK_NE(oat_file, oat_files_[i]) << oat_file->GetLocation();
655    }
656  }
657  VLOG(class_linker) << "Registering " << oat_file->GetLocation();
658  oat_files_.push_back(oat_file);
659  return oat_file;
660}
661
662OatFile& ClassLinker::GetImageOatFile(gc::space::ImageSpace* space) {
663  VLOG(startup) << "ClassLinker::GetImageOatFile entering";
664  OatFile* oat_file = space->ReleaseOatFile();
665  CHECK_EQ(RegisterOatFile(oat_file), oat_file);
666  VLOG(startup) << "ClassLinker::GetImageOatFile exiting";
667  return *oat_file;
668}
669
670const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
671  const char* dex_location = dex_file.GetLocation().c_str();
672  uint32_t dex_location_checksum = dex_file.GetLocationChecksum();
673  return FindOpenedOatFileFromDexLocation(dex_location, &dex_location_checksum);
674}
675
676const OatFile* ClassLinker::FindOpenedOatFileFromDexLocation(const char* dex_location,
677                                                             const uint32_t* const dex_location_checksum) {
678  ReaderMutexLock mu(Thread::Current(), dex_lock_);
679  for (size_t i = 0; i < oat_files_.size(); i++) {
680    const OatFile* oat_file = oat_files_[i];
681    DCHECK(oat_file != NULL);
682    const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
683                                                                      dex_location_checksum,
684                                                                      false);
685    if (oat_dex_file != NULL) {
686      return oat_file;
687    }
688  }
689  return NULL;
690}
691
692const DexFile* ClassLinker::FindDexFileInOatLocation(const char* dex_location,
693                                                     uint32_t dex_location_checksum,
694                                                     const char* oat_location,
695                                                     std::string* error_msg) {
696  UniquePtr<OatFile> oat_file(OatFile::Open(oat_location, oat_location, NULL,
697                                            !Runtime::Current()->IsCompiler(),
698                                            error_msg));
699  if (oat_file.get() == nullptr) {
700    *error_msg = StringPrintf("Failed to find existing oat file at %s: %s", oat_location,
701                              error_msg->c_str());
702    return nullptr;
703  }
704  Runtime* runtime = Runtime::Current();
705  const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
706  uint32_t expected_image_oat_checksum = image_header.GetOatChecksum();
707  uint32_t actual_image_oat_checksum = oat_file->GetOatHeader().GetImageFileLocationOatChecksum();
708  if (expected_image_oat_checksum != actual_image_oat_checksum) {
709    *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat checksum of "
710                              "0x%x, found 0x%x", oat_location, expected_image_oat_checksum,
711                              actual_image_oat_checksum);
712    return nullptr;
713  }
714
715  uintptr_t expected_image_oat_offset = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
716  uint32_t actual_image_oat_offset = oat_file->GetOatHeader().GetImageFileLocationOatDataBegin();
717  if (expected_image_oat_offset != actual_image_oat_offset) {
718    *error_msg = StringPrintf("Failed to find oat file at '%s' with expected image oat offset %"
719                              PRIuPTR ", found %ud", oat_location, expected_image_oat_offset,
720                              actual_image_oat_offset);
721    return nullptr;
722  }
723  // TODO: this registers the oat file now as we may use the oat_dex_file later and we want the
724  //       intern behavior of RegisterOatFile. However, if we take an early return we could remove
725  //       the oat file.
726  const OatFile* opened_oat_file = RegisterOatFile(oat_file.release());
727  const OatFile::OatDexFile* oat_dex_file = opened_oat_file->GetOatDexFile(dex_location,
728                                                                           &dex_location_checksum);
729  if (oat_dex_file == nullptr) {
730    *error_msg = StringPrintf("Failed to find oat file at '%s' containing '%s'", oat_location,
731                              dex_location);
732    return nullptr;
733  }
734  uint32_t expected_dex_checksum = dex_location_checksum;
735  uint32_t actual_dex_checksum = oat_dex_file->GetDexFileLocationChecksum();
736  if (expected_dex_checksum != actual_dex_checksum) {
737    *error_msg = StringPrintf("Failed to find oat file at '%s' with expected dex checksum of 0x%x, "
738                              "found 0x%x", oat_location, expected_dex_checksum,
739                              actual_dex_checksum);
740    return nullptr;
741  }
742  return oat_dex_file->OpenDexFile(error_msg);
743}
744
745class ScopedFlock {
746 public:
747  ScopedFlock() {}
748
749  bool Init(const char* filename, std::string* error_msg) {
750    while (true) {
751      file_.reset(OS::OpenFileWithFlags(filename, O_CREAT | O_RDWR));
752      if (file_.get() == NULL) {
753        *error_msg = StringPrintf("Failed to open file '%s'", filename);
754        return false;
755      }
756      int flock_result = TEMP_FAILURE_RETRY(flock(file_->Fd(), LOCK_EX));
757      if (flock_result != 0) {
758        *error_msg = StringPrintf("Failed to lock file '%s': %s", filename, strerror(errno));
759        return false;
760      }
761      struct stat fstat_stat;
762      int fstat_result = TEMP_FAILURE_RETRY(fstat(file_->Fd(), &fstat_stat));
763      if (fstat_result != 0) {
764        *error_msg = StringPrintf("Failed to fstat file '%s': %s", filename, strerror(errno));
765        return false;
766      }
767      struct stat stat_stat;
768      int stat_result = TEMP_FAILURE_RETRY(stat(filename, &stat_stat));
769      if (stat_result != 0) {
770        PLOG(WARNING) << "Failed to stat, will retry: " << filename;
771        // ENOENT can happen if someone racing with us unlinks the file we created so just retry.
772        continue;
773      }
774      if (fstat_stat.st_dev != stat_stat.st_dev || fstat_stat.st_ino != stat_stat.st_ino) {
775        LOG(WARNING) << "File changed while locking, will retry: " << filename;
776        continue;
777      }
778      return true;
779    }
780  }
781
782  File& GetFile() {
783    return *file_;
784  }
785
786  ~ScopedFlock() {
787    if (file_.get() != NULL) {
788      int flock_result = TEMP_FAILURE_RETRY(flock(file_->Fd(), LOCK_UN));
789      CHECK_EQ(0, flock_result);
790    }
791  }
792
793 private:
794  UniquePtr<File> file_;
795
796  DISALLOW_COPY_AND_ASSIGN(ScopedFlock);
797};
798
799const DexFile* ClassLinker::FindOrCreateOatFileForDexLocation(const char* dex_location,
800                                                              uint32_t dex_location_checksum,
801                                                              const char* oat_location,
802                                                              std::string* error_msg) {
803  // We play a locking game here so that if two different processes
804  // race to generate (or worse, one tries to open a partial generated
805  // file) we will be okay. This is actually common with apps that use
806  // DexClassLoader to work around the dex method reference limit and
807  // that have a background service running in a separate process.
808  ScopedFlock scoped_flock;
809  if (!scoped_flock.Init(oat_location, error_msg)) {
810    return nullptr;
811  }
812
813  // Check if we already have an up-to-date output file
814  const DexFile* dex_file = FindDexFileInOatLocation(dex_location, dex_location_checksum,
815                                                     oat_location, error_msg);
816  if (dex_file != nullptr) {
817    return dex_file;
818  }
819  VLOG(class_linker) << "Failed to find dex file '" << dex_location << "' in oat location '"
820      << oat_location << "': " << *error_msg;
821  error_msg->clear();
822
823  // Generate the output oat file for the dex file
824  VLOG(class_linker) << "Generating oat file " << oat_location << " for " << dex_location;
825  if (!GenerateOatFile(dex_location, scoped_flock.GetFile().Fd(), oat_location, error_msg)) {
826    CHECK(!error_msg->empty());
827    return nullptr;
828  }
829  const OatFile* oat_file = OatFile::Open(oat_location, oat_location, NULL,
830                                          !Runtime::Current()->IsCompiler(),
831                                          error_msg);
832  if (oat_file == nullptr) {
833    *error_msg = StringPrintf("Failed to open generated oat file '%s': %s",
834                              oat_location, error_msg->c_str());
835    return nullptr;
836  }
837  oat_file = RegisterOatFile(oat_file);
838  const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location,
839                                                                    &dex_location_checksum);
840  if (oat_dex_file == nullptr) {
841    *error_msg = StringPrintf("Failed to find dex file '%s' (checksum 0x%x) in generated out file "
842                              "'%s'", dex_location, dex_location_checksum, oat_location);
843    return nullptr;
844  }
845  const DexFile* result = oat_dex_file->OpenDexFile(error_msg);
846  CHECK(result != nullptr) << *error_msg;
847  CHECK_EQ(dex_location_checksum, result->GetLocationChecksum())
848          << "dex_location=" << dex_location << " oat_location=" << oat_location << std::hex
849          << " dex_location_checksum=" << dex_location_checksum
850          << " DexFile::GetLocationChecksum()=" << result->GetLocationChecksum();
851  return result;
852}
853
854bool ClassLinker::VerifyOatFileChecksums(const OatFile* oat_file,
855                                         const char* dex_location,
856                                         uint32_t dex_location_checksum,
857                                         std::string* error_msg) {
858  Runtime* runtime = Runtime::Current();
859  const ImageHeader& image_header = runtime->GetHeap()->GetImageSpace()->GetImageHeader();
860  uint32_t image_oat_checksum = image_header.GetOatChecksum();
861  uintptr_t image_oat_data_begin = reinterpret_cast<uintptr_t>(image_header.GetOatDataBegin());
862  bool image_check = ((oat_file->GetOatHeader().GetImageFileLocationOatChecksum() == image_oat_checksum)
863                      && (oat_file->GetOatHeader().GetImageFileLocationOatDataBegin() == image_oat_data_begin));
864
865  const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_location, &dex_location_checksum);
866  if (oat_dex_file == NULL) {
867    *error_msg = StringPrintf("oat file '%s' does not contain contents for '%s' with checksum 0x%x",
868                              oat_file->GetLocation().c_str(), dex_location, dex_location_checksum);
869    std::vector<const OatFile::OatDexFile*> oat_dex_files = oat_file->GetOatDexFiles();
870    for (size_t i = 0; i < oat_dex_files.size(); i++) {
871      const OatFile::OatDexFile* oat_dex_file = oat_dex_files[i];
872      *error_msg  += StringPrintf("\noat file '%s' contains contents for '%s'",
873                                  oat_file->GetLocation().c_str(),
874                                  oat_dex_file->GetDexFileLocation().c_str());
875    }
876    return false;
877  }
878  bool dex_check = dex_location_checksum == oat_dex_file->GetDexFileLocationChecksum();
879
880  if (image_check && dex_check) {
881    return true;
882  }
883
884  if (!image_check) {
885    ScopedObjectAccess soa(Thread::Current());
886    mirror::String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
887    std::string image_file(oat_location->ToModifiedUtf8());
888    *error_msg = StringPrintf("oat file '%s' mismatch (0x%x, %d) with '%s' (0x%x, %" PRIdPTR ")",
889                              oat_file->GetLocation().c_str(),
890                              oat_file->GetOatHeader().GetImageFileLocationOatChecksum(),
891                              oat_file->GetOatHeader().GetImageFileLocationOatDataBegin(),
892                              image_file.c_str(), image_oat_checksum, image_oat_data_begin);
893  }
894  if (!dex_check) {
895    *error_msg = StringPrintf("oat file '%s' mismatch (0x%x) with '%s' (0x%x)",
896                              oat_file->GetLocation().c_str(),
897                              oat_dex_file->GetDexFileLocationChecksum(),
898                              dex_location, dex_location_checksum);
899  }
900  return false;
901}
902
903const DexFile* ClassLinker::VerifyAndOpenDexFileFromOatFile(const std::string& oat_file_location,
904                                                            const char* dex_location,
905                                                            std::string* error_msg,
906                                                            bool* open_failed) {
907  UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_file_location, error_msg));
908  if (oat_file.get() == nullptr) {
909    *open_failed = true;
910    return nullptr;
911  }
912  *open_failed = false;
913  uint32_t dex_location_checksum;
914  if (!DexFile::GetChecksum(dex_location, &dex_location_checksum, error_msg)) {
915    // If no classes.dex found in dex_location, it has been stripped or is corrupt, assume oat is
916    // up-to-date. This is the common case in user builds for jar's and apk's in the /system
917    // directory.
918    const OatFile* opened_oat_file = oat_file.release();
919    opened_oat_file = RegisterOatFile(opened_oat_file);
920    const OatFile::OatDexFile* oat_dex_file = opened_oat_file->GetOatDexFile(dex_location, NULL);
921    if (oat_dex_file == nullptr) {
922      *error_msg = StringPrintf("Dex checksum mismatch for location '%s' and failed to find oat "
923                                "dex file '%s': %s", oat_file_location.c_str(), dex_location,
924                                error_msg->c_str());
925      return nullptr;
926    }
927    return oat_dex_file->OpenDexFile(error_msg);
928  }
929
930  bool verified = VerifyOatFileChecksums(oat_file.get(), dex_location, dex_location_checksum,
931                                         error_msg);
932  if (!verified) {
933    return nullptr;
934  }
935  const OatFile* opened_oat_file = oat_file.release();
936  opened_oat_file = RegisterOatFile(opened_oat_file);
937  return opened_oat_file->GetOatDexFile(dex_location,
938                                        &dex_location_checksum)->OpenDexFile(error_msg);
939}
940
941const DexFile* ClassLinker::FindDexFileInOatFileFromDexLocation(const char* dex_location,
942                                                                const uint32_t* const dex_location_checksum,
943                                                                std::string* error_msg) {
944  const OatFile* open_oat_file = FindOpenedOatFileFromDexLocation(dex_location,
945                                                                  dex_location_checksum);
946  if (open_oat_file != nullptr) {
947    const OatFile::OatDexFile* oat_dex_file = open_oat_file->GetOatDexFile(dex_location,
948                                                                           dex_location_checksum);
949    return oat_dex_file->OpenDexFile(error_msg);
950  }
951
952  // Look for an existing file next to dex. for example, for
953  // /foo/bar/baz.jar, look for /foo/bar/baz.odex.
954  std::string odex_filename(OatFile::DexFilenameToOdexFilename(dex_location));
955  bool open_failed;
956  const DexFile* dex_file = VerifyAndOpenDexFileFromOatFile(odex_filename, dex_location,
957                                                            error_msg, &open_failed);
958  if (dex_file != nullptr) {
959    return dex_file;
960  }
961  if (dex_location_checksum == nullptr) {
962    *error_msg = StringPrintf("Failed to open oat file from %s and no classes.dex found in %s: %s",
963                              odex_filename.c_str(), dex_location, error_msg->c_str());
964    return nullptr;
965  }
966
967  std::string cache_error_msg;
968  std::string cache_location(GetDalvikCacheFilenameOrDie(dex_location));
969  dex_file = VerifyAndOpenDexFileFromOatFile(cache_location, dex_location, &cache_error_msg,
970                                             &open_failed);
971  if (dex_file != nullptr) {
972    return dex_file;
973  }
974  if (!open_failed && TEMP_FAILURE_RETRY(unlink(cache_location.c_str())) != 0) {
975    PLOG(FATAL) << "Failed to remove obsolete oat file from " << cache_location;
976  }
977  VLOG(class_linker) << "Failed to open oat file from " << odex_filename
978      << " (error '" << *error_msg << "') or " << cache_location
979      << " (error '" << cache_error_msg << "').";
980
981  // Try to generate oat file if it wasn't found or was obsolete.
982  error_msg->clear();
983  return FindOrCreateOatFileForDexLocation(dex_location, *dex_location_checksum,
984                                           cache_location.c_str(), error_msg);
985}
986
987const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
988  ReaderMutexLock mu(Thread::Current(), dex_lock_);
989  for (size_t i = 0; i < oat_files_.size(); i++) {
990    const OatFile* oat_file = oat_files_[i];
991    DCHECK(oat_file != nullptr);
992    if (oat_file->GetLocation() == oat_location) {
993      return oat_file;
994    }
995  }
996  return nullptr;
997}
998
999const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location,
1000                                                       std::string* error_msg) {
1001  const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
1002  if (oat_file != nullptr) {
1003    return oat_file;
1004  }
1005
1006  oat_file = OatFile::Open(oat_location, oat_location, NULL, !Runtime::Current()->IsCompiler(),
1007                           error_msg);
1008  if (oat_file == NULL) {
1009    return NULL;
1010  }
1011  return oat_file;
1012}
1013
1014static void InitFromImageInterpretOnlyCallback(mirror::Object* obj, void* arg)
1015    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1016  ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
1017
1018  DCHECK(obj != NULL);
1019  DCHECK(class_linker != NULL);
1020
1021  if (obj->IsArtMethod()) {
1022    mirror::ArtMethod* method = obj->AsArtMethod();
1023    if (!method->IsNative()) {
1024      method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1025      if (method != Runtime::Current()->GetResolutionMethod()) {
1026        method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1027        method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
1028      }
1029    }
1030  }
1031}
1032
1033void ClassLinker::InitFromImage() {
1034  VLOG(startup) << "ClassLinker::InitFromImage entering";
1035  CHECK(!init_done_);
1036
1037  Thread* self = Thread::Current();
1038  gc::Heap* heap = Runtime::Current()->GetHeap();
1039  gc::space::ImageSpace* space = heap->GetImageSpace();
1040  dex_cache_image_class_lookup_required_ = true;
1041  CHECK(space != NULL);
1042  OatFile& oat_file = GetImageOatFile(space);
1043  CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatChecksum(), 0U);
1044  CHECK_EQ(oat_file.GetOatHeader().GetImageFileLocationOatDataBegin(), 0U);
1045  CHECK(oat_file.GetOatHeader().GetImageFileLocation().empty());
1046  portable_resolution_trampoline_ = oat_file.GetOatHeader().GetPortableResolutionTrampoline();
1047  quick_resolution_trampoline_ = oat_file.GetOatHeader().GetQuickResolutionTrampoline();
1048  portable_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetPortableImtConflictTrampoline();
1049  quick_imt_conflict_trampoline_ = oat_file.GetOatHeader().GetQuickImtConflictTrampoline();
1050  mirror::Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
1051  mirror::ObjectArray<mirror::DexCache>* dex_caches =
1052      dex_caches_object->AsObjectArray<mirror::DexCache>();
1053
1054  SirtRef<mirror::ObjectArray<mirror::Class> > class_roots(
1055      self,
1056      space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)->AsObjectArray<mirror::Class>());
1057  class_roots_ = class_roots.get();
1058
1059  // Special case of setting up the String class early so that we can test arbitrary objects
1060  // as being Strings or not
1061  mirror::String::SetClass(GetClassRoot(kJavaLangString));
1062
1063  CHECK_EQ(oat_file.GetOatHeader().GetDexFileCount(),
1064           static_cast<uint32_t>(dex_caches->GetLength()));
1065  for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
1066    SirtRef<mirror::DexCache> dex_cache(self, dex_caches->Get(i));
1067    const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
1068    const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(dex_file_location.c_str(),
1069                                                                     nullptr);
1070    CHECK(oat_dex_file != NULL) << oat_file.GetLocation() << " " << dex_file_location;
1071    std::string error_msg;
1072    const DexFile* dex_file = oat_dex_file->OpenDexFile(&error_msg);
1073    if (dex_file == NULL) {
1074      LOG(FATAL) << "Failed to open dex file " << dex_file_location
1075                 << " from within oat file " << oat_file.GetLocation()
1076                 << " error '" << error_msg << "'";
1077    }
1078
1079    CHECK_EQ(dex_file->GetLocationChecksum(), oat_dex_file->GetDexFileLocationChecksum());
1080
1081    AppendToBootClassPath(*dex_file, dex_cache);
1082  }
1083
1084  // Set classes on AbstractMethod early so that IsMethod tests can be performed during the live
1085  // bitmap walk.
1086  mirror::ArtMethod::SetClass(GetClassRoot(kJavaLangReflectArtMethod));
1087
1088  // Set entry point to interpreter if in InterpretOnly mode.
1089  if (Runtime::Current()->GetInstrumentation()->InterpretOnly()) {
1090    ReaderMutexLock mu(self, *Locks::heap_bitmap_lock_);
1091    heap->VisitObjects(InitFromImageInterpretOnlyCallback, this);
1092  }
1093
1094  // reinit class_roots_
1095  mirror::Class::SetClassClass(class_roots->Get(kJavaLangClass));
1096  class_roots_ = class_roots.get();
1097
1098  // reinit array_iftable_ from any array class instance, they should be ==
1099  array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
1100  DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
1101  // String class root was set above
1102  mirror::ArtField::SetClass(GetClassRoot(kJavaLangReflectArtField));
1103  mirror::BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
1104  mirror::ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
1105  mirror::CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
1106  mirror::DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
1107  mirror::FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
1108  mirror::IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
1109  mirror::LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
1110  mirror::ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
1111  mirror::Throwable::SetClass(GetClassRoot(kJavaLangThrowable));
1112  mirror::StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
1113
1114  FinishInit();
1115
1116  VLOG(startup) << "ClassLinker::InitFromImage exiting";
1117}
1118
1119// Keep in sync with InitCallback. Anything we visit, we need to
1120// reinit references to when reinitializing a ClassLinker from a
1121// mapped image.
1122void ClassLinker::VisitRoots(RootVisitor* visitor, void* arg, bool only_dirty, bool clean_dirty) {
1123  class_roots_ = down_cast<mirror::ObjectArray<mirror::Class>*>(visitor(class_roots_, arg));
1124  Thread* self = Thread::Current();
1125  {
1126    ReaderMutexLock mu(self, dex_lock_);
1127    if (!only_dirty || dex_caches_dirty_) {
1128      for (mirror::DexCache*& dex_cache : dex_caches_) {
1129        dex_cache = down_cast<mirror::DexCache*>(visitor(dex_cache, arg));
1130        DCHECK(dex_cache != nullptr);
1131      }
1132      if (clean_dirty) {
1133        dex_caches_dirty_ = false;
1134      }
1135    }
1136  }
1137
1138  {
1139    WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
1140    if (!only_dirty || class_table_dirty_) {
1141      for (std::pair<const size_t, mirror::Class*>& it : class_table_) {
1142        it.second = down_cast<mirror::Class*>(visitor(it.second, arg));
1143        DCHECK(it.second != nullptr);
1144      }
1145      if (clean_dirty) {
1146        class_table_dirty_ = false;
1147      }
1148    }
1149
1150    // We deliberately ignore the class roots in the image since we
1151    // handle image roots by using the MS/CMS rescanning of dirty cards.
1152  }
1153
1154  array_iftable_ = reinterpret_cast<mirror::IfTable*>(visitor(array_iftable_, arg));
1155  DCHECK(array_iftable_ != nullptr);
1156}
1157
1158void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) {
1159  if (dex_cache_image_class_lookup_required_) {
1160    MoveImageClassesToClassTable();
1161  }
1162  WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1163  for (const std::pair<size_t, mirror::Class*>& it : class_table_) {
1164    if (!visitor(it.second, arg)) {
1165      return;
1166    }
1167  }
1168}
1169
1170static bool GetClassesVisitor(mirror::Class* c, void* arg) {
1171  std::set<mirror::Class*>* classes = reinterpret_cast<std::set<mirror::Class*>*>(arg);
1172  classes->insert(c);
1173  return true;
1174}
1175
1176void ClassLinker::VisitClassesWithoutClassesLock(ClassVisitor* visitor, void* arg) {
1177  std::set<mirror::Class*> classes;
1178  VisitClasses(GetClassesVisitor, &classes);
1179  for (mirror::Class* klass : classes) {
1180    if (!visitor(klass, arg)) {
1181      return;
1182    }
1183  }
1184}
1185
1186ClassLinker::~ClassLinker() {
1187  mirror::Class::ResetClass();
1188  mirror::String::ResetClass();
1189  mirror::ArtField::ResetClass();
1190  mirror::ArtMethod::ResetClass();
1191  mirror::BooleanArray::ResetArrayClass();
1192  mirror::ByteArray::ResetArrayClass();
1193  mirror::CharArray::ResetArrayClass();
1194  mirror::DoubleArray::ResetArrayClass();
1195  mirror::FloatArray::ResetArrayClass();
1196  mirror::IntArray::ResetArrayClass();
1197  mirror::LongArray::ResetArrayClass();
1198  mirror::ShortArray::ResetArrayClass();
1199  mirror::Throwable::ResetClass();
1200  mirror::StackTraceElement::ResetClass();
1201  STLDeleteElements(&boot_class_path_);
1202  STLDeleteElements(&oat_files_);
1203}
1204
1205mirror::DexCache* ClassLinker::AllocDexCache(Thread* self, const DexFile& dex_file) {
1206  gc::Heap* heap = Runtime::Current()->GetHeap();
1207  SirtRef<mirror::Class> dex_cache_class(self, GetClassRoot(kJavaLangDexCache));
1208  SirtRef<mirror::DexCache> dex_cache(
1209      self, down_cast<mirror::DexCache*>(
1210          heap->AllocObject<true>(self, dex_cache_class.get(), dex_cache_class->GetObjectSize())));
1211  if (dex_cache.get() == NULL) {
1212    return NULL;
1213  }
1214  SirtRef<mirror::String>
1215      location(self, intern_table_->InternStrong(dex_file.GetLocation().c_str()));
1216  if (location.get() == NULL) {
1217    return NULL;
1218  }
1219  SirtRef<mirror::ObjectArray<mirror::String> >
1220      strings(self, AllocStringArray(self, dex_file.NumStringIds()));
1221  if (strings.get() == NULL) {
1222    return NULL;
1223  }
1224  SirtRef<mirror::ObjectArray<mirror::Class> >
1225      types(self, AllocClassArray(self, dex_file.NumTypeIds()));
1226  if (types.get() == NULL) {
1227    return NULL;
1228  }
1229  SirtRef<mirror::ObjectArray<mirror::ArtMethod> >
1230      methods(self, AllocArtMethodArray(self, dex_file.NumMethodIds()));
1231  if (methods.get() == NULL) {
1232    return NULL;
1233  }
1234  SirtRef<mirror::ObjectArray<mirror::ArtField> >
1235      fields(self, AllocArtFieldArray(self, dex_file.NumFieldIds()));
1236  if (fields.get() == NULL) {
1237    return NULL;
1238  }
1239  dex_cache->Init(&dex_file, location.get(), strings.get(), types.get(), methods.get(),
1240                  fields.get());
1241  return dex_cache.get();
1242}
1243
1244mirror::Class* ClassLinker::AllocClass(Thread* self, mirror::Class* java_lang_Class,
1245                                       size_t class_size) {
1246  DCHECK_GE(class_size, sizeof(mirror::Class));
1247  gc::Heap* heap = Runtime::Current()->GetHeap();
1248  mirror::Object* k =
1249      kMovingClasses ?
1250          heap->AllocObject<true>(self, java_lang_Class, class_size) :
1251          heap->AllocNonMovableObject<true>(self, java_lang_Class, class_size);
1252  if (UNLIKELY(k == NULL)) {
1253    CHECK(self->IsExceptionPending());  // OOME.
1254    return NULL;
1255  }
1256  mirror::Class* klass = k->AsClass();
1257  klass->SetPrimitiveType(Primitive::kPrimNot);  // Default to not being primitive.
1258  klass->SetClassSize(class_size);
1259  klass->SetDexClassDefIndex(DexFile::kDexNoIndex16);  // Default to no valid class def index.
1260  klass->SetDexTypeIndex(DexFile::kDexNoIndex16);  // Default to no valid type index.
1261  return klass;
1262}
1263
1264mirror::Class* ClassLinker::AllocClass(Thread* self, size_t class_size) {
1265  return AllocClass(self, GetClassRoot(kJavaLangClass), class_size);
1266}
1267
1268mirror::ArtField* ClassLinker::AllocArtField(Thread* self) {
1269  return down_cast<mirror::ArtField*>(
1270      GetClassRoot(kJavaLangReflectArtField)->AllocNonMovableObject(self));
1271}
1272
1273mirror::ArtMethod* ClassLinker::AllocArtMethod(Thread* self) {
1274  return down_cast<mirror::ArtMethod*>(
1275      GetClassRoot(kJavaLangReflectArtMethod)->AllocNonMovableObject(self));
1276}
1277
1278mirror::ObjectArray<mirror::StackTraceElement>* ClassLinker::AllocStackTraceElementArray(
1279    Thread* self, size_t length) {
1280  return mirror::ObjectArray<mirror::StackTraceElement>::Alloc(
1281      self, GetClassRoot(kJavaLangStackTraceElementArrayClass), length);
1282}
1283
1284static mirror::Class* EnsureResolved(Thread* self, mirror::Class* klass)
1285    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1286  DCHECK(klass != NULL);
1287  // Wait for the class if it has not already been linked.
1288  if (!klass->IsResolved() && !klass->IsErroneous()) {
1289    SirtRef<mirror::Class> sirt_class(self, klass);
1290    ObjectLock<mirror::Class> lock(self, &sirt_class);
1291    // Check for circular dependencies between classes.
1292    if (!sirt_class->IsResolved() && sirt_class->GetClinitThreadId() == self->GetTid()) {
1293      ThrowClassCircularityError(sirt_class.get());
1294      sirt_class->SetStatus(mirror::Class::kStatusError, self);
1295      return nullptr;
1296    }
1297    // Wait for the pending initialization to complete.
1298    while (!sirt_class->IsResolved() && !sirt_class->IsErroneous()) {
1299      lock.WaitIgnoringInterrupts();
1300    }
1301    klass = sirt_class.get();
1302  }
1303  if (klass->IsErroneous()) {
1304    ThrowEarlierClassFailure(klass);
1305    return nullptr;
1306  }
1307  // Return the loaded class.  No exceptions should be pending.
1308  CHECK(klass->IsResolved()) << PrettyClass(klass);
1309  self->AssertNoPendingException();
1310  return klass;
1311}
1312
1313bool ClassLinker::IsInBootClassPath(const char* descriptor) {
1314  DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1315  return pair.second != NULL;
1316}
1317
1318mirror::Class* ClassLinker::FindSystemClass(const char* descriptor) {
1319  SirtRef<mirror::ClassLoader> class_loader(Thread::Current(), nullptr);
1320  return FindClass(descriptor, class_loader);
1321}
1322
1323mirror::Class* ClassLinker::FindClass(const char* descriptor,
1324                                      const SirtRef<mirror::ClassLoader>& class_loader) {
1325  DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
1326  Thread* self = Thread::Current();
1327  DCHECK(self != NULL);
1328  self->AssertNoPendingException();
1329  if (descriptor[1] == '\0') {
1330    // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1331    // for primitive classes that aren't backed by dex files.
1332    return FindPrimitiveClass(descriptor[0]);
1333  }
1334  // Find the class in the loaded classes table.
1335  mirror::Class* klass = LookupClass(descriptor, class_loader.get());
1336  if (klass != NULL) {
1337    return EnsureResolved(self, klass);
1338  }
1339  // Class is not yet loaded.
1340  if (descriptor[0] == '[') {
1341    return CreateArrayClass(descriptor, class_loader);
1342  } else if (class_loader.get() == nullptr) {
1343    DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1344    if (pair.second != NULL) {
1345      SirtRef<mirror::ClassLoader> class_loader(self, nullptr);
1346      return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
1347    }
1348  } else if (Runtime::Current()->UseCompileTimeClassPath()) {
1349    // First try the boot class path, we check the descriptor first to avoid an unnecessary
1350    // throw of a NoClassDefFoundError.
1351    if (IsInBootClassPath(descriptor)) {
1352      mirror::Class* system_class = FindSystemClass(descriptor);
1353      CHECK(system_class != NULL);
1354      return system_class;
1355    }
1356    // Next try the compile time class path.
1357    const std::vector<const DexFile*>* class_path;
1358    {
1359      ScopedObjectAccessUnchecked soa(self);
1360      ScopedLocalRef<jobject> jclass_loader(soa.Env(),
1361                                            soa.AddLocalReference<jobject>(class_loader.get()));
1362      class_path = &Runtime::Current()->GetCompileTimeClassPath(jclass_loader.get());
1363    }
1364
1365    DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, *class_path);
1366    if (pair.second != NULL) {
1367      return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
1368    }
1369
1370  } else {
1371    ScopedObjectAccessUnchecked soa(self->GetJniEnv());
1372    ScopedLocalRef<jobject> class_loader_object(soa.Env(),
1373                                                soa.AddLocalReference<jobject>(class_loader.get()));
1374    std::string class_name_string(DescriptorToDot(descriptor));
1375    ScopedLocalRef<jobject> result(soa.Env(), NULL);
1376    {
1377      ScopedThreadStateChange tsc(self, kNative);
1378      ScopedLocalRef<jobject> class_name_object(soa.Env(),
1379                                                soa.Env()->NewStringUTF(class_name_string.c_str()));
1380      if (class_name_object.get() == NULL) {
1381        return NULL;
1382      }
1383      CHECK(class_loader_object.get() != NULL);
1384      result.reset(soa.Env()->CallObjectMethod(class_loader_object.get(),
1385                                               WellKnownClasses::java_lang_ClassLoader_loadClass,
1386                                               class_name_object.get()));
1387    }
1388    if (soa.Self()->IsExceptionPending()) {
1389      // If the ClassLoader threw, pass that exception up.
1390      return NULL;
1391    } else if (result.get() == NULL) {
1392      // broken loader - throw NPE to be compatible with Dalvik
1393      ThrowNullPointerException(NULL, StringPrintf("ClassLoader.loadClass returned null for %s",
1394                                                   class_name_string.c_str()).c_str());
1395      return NULL;
1396    } else {
1397      // success, return mirror::Class*
1398      return soa.Decode<mirror::Class*>(result.get());
1399    }
1400  }
1401
1402  ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
1403  return NULL;
1404}
1405
1406mirror::Class* ClassLinker::DefineClass(const char* descriptor,
1407                                        const SirtRef<mirror::ClassLoader>& class_loader,
1408                                        const DexFile& dex_file,
1409                                        const DexFile::ClassDef& dex_class_def) {
1410  Thread* self = Thread::Current();
1411  SirtRef<mirror::Class> klass(self, NULL);
1412  // Load the class from the dex file.
1413  if (UNLIKELY(!init_done_)) {
1414    // finish up init of hand crafted class_roots_
1415    if (strcmp(descriptor, "Ljava/lang/Object;") == 0) {
1416      klass.reset(GetClassRoot(kJavaLangObject));
1417    } else if (strcmp(descriptor, "Ljava/lang/Class;") == 0) {
1418      klass.reset(GetClassRoot(kJavaLangClass));
1419    } else if (strcmp(descriptor, "Ljava/lang/String;") == 0) {
1420      klass.reset(GetClassRoot(kJavaLangString));
1421    } else if (strcmp(descriptor, "Ljava/lang/DexCache;") == 0) {
1422      klass.reset(GetClassRoot(kJavaLangDexCache));
1423    } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtField;") == 0) {
1424      klass.reset(GetClassRoot(kJavaLangReflectArtField));
1425    } else if (strcmp(descriptor, "Ljava/lang/reflect/ArtMethod;") == 0) {
1426      klass.reset(GetClassRoot(kJavaLangReflectArtMethod));
1427    } else {
1428      klass.reset(AllocClass(self, SizeOfClass(dex_file, dex_class_def)));
1429    }
1430  } else {
1431    klass.reset(AllocClass(self, SizeOfClass(dex_file, dex_class_def)));
1432  }
1433  if (UNLIKELY(klass.get() == NULL)) {
1434    CHECK(self->IsExceptionPending());  // Expect an OOME.
1435    return NULL;
1436  }
1437  klass->SetDexCache(FindDexCache(dex_file));
1438  LoadClass(dex_file, dex_class_def, klass, class_loader.get());
1439  // Check for a pending exception during load
1440  if (self->IsExceptionPending()) {
1441    klass->SetStatus(mirror::Class::kStatusError, self);
1442    return NULL;
1443  }
1444  ObjectLock<mirror::Class> lock(self, &klass);
1445  klass->SetClinitThreadId(self->GetTid());
1446  // Add the newly loaded class to the loaded classes table.
1447  mirror::Class* existing = InsertClass(descriptor, klass.get(), Hash(descriptor));
1448  if (existing != NULL) {
1449    // We failed to insert because we raced with another thread. Calling EnsureResolved may cause
1450    // this thread to block.
1451    return EnsureResolved(self, existing);
1452  }
1453  // Finish loading (if necessary) by finding parents
1454  CHECK(!klass->IsLoaded());
1455  if (!LoadSuperAndInterfaces(klass, dex_file)) {
1456    // Loading failed.
1457    klass->SetStatus(mirror::Class::kStatusError, self);
1458    return NULL;
1459  }
1460  CHECK(klass->IsLoaded());
1461  // Link the class (if necessary)
1462  CHECK(!klass->IsResolved());
1463  // TODO: Use fast jobjects?
1464  SirtRef<mirror::ObjectArray<mirror::Class> > interfaces(self, nullptr);
1465  if (!LinkClass(self, klass, interfaces)) {
1466    // Linking failed.
1467    klass->SetStatus(mirror::Class::kStatusError, self);
1468    return NULL;
1469  }
1470  CHECK(klass->IsResolved());
1471
1472  /*
1473   * We send CLASS_PREPARE events to the debugger from here.  The
1474   * definition of "preparation" is creating the static fields for a
1475   * class and initializing them to the standard default values, but not
1476   * executing any code (that comes later, during "initialization").
1477   *
1478   * We did the static preparation in LinkClass.
1479   *
1480   * The class has been prepared and resolved but possibly not yet verified
1481   * at this point.
1482   */
1483  Dbg::PostClassPrepare(klass.get());
1484
1485  return klass.get();
1486}
1487
1488// Precomputes size that will be needed for Class, matching LinkStaticFields
1489size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1490                                const DexFile::ClassDef& dex_class_def) {
1491  const byte* class_data = dex_file.GetClassData(dex_class_def);
1492  size_t num_ref = 0;
1493  size_t num_32 = 0;
1494  size_t num_64 = 0;
1495  if (class_data != NULL) {
1496    for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1497      const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
1498      const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
1499      char c = descriptor[0];
1500      if (c == 'L' || c == '[') {
1501        num_ref++;
1502      } else if (c == 'J' || c == 'D') {
1503        num_64++;
1504      } else {
1505        num_32++;
1506      }
1507    }
1508  }
1509  // start with generic class data
1510  size_t size = sizeof(mirror::Class);
1511  // follow with reference fields which must be contiguous at start
1512  size += (num_ref * sizeof(uint32_t));
1513  // if there are 64-bit fields to add, make sure they are aligned
1514  if (num_64 != 0 && size != RoundUp(size, 8)) {  // for 64-bit alignment
1515    if (num_32 != 0) {
1516      // use an available 32-bit field for padding
1517      num_32--;
1518    }
1519    size += sizeof(uint32_t);  // either way, we are adding a word
1520    DCHECK_EQ(size, RoundUp(size, 8));
1521  }
1522  // tack on any 64-bit fields now that alignment is assured
1523  size += (num_64 * sizeof(uint64_t));
1524  // tack on any remaining 32-bit fields
1525  size += (num_32 * sizeof(uint32_t));
1526  return size;
1527}
1528
1529const OatFile::OatClass* ClassLinker::GetOatClass(const DexFile& dex_file, uint16_t class_def_idx) {
1530  DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1531  const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
1532  CHECK(oat_file != NULL) << dex_file.GetLocation();
1533  uint dex_location_checksum = dex_file.GetLocationChecksum();
1534  const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
1535                                                                    &dex_location_checksum);
1536  CHECK(oat_dex_file != NULL) << dex_file.GetLocation();
1537  const OatFile::OatClass* oat_class = oat_dex_file->GetOatClass(class_def_idx);
1538  CHECK(oat_class != NULL) << dex_file.GetLocation() << " " << class_def_idx;
1539  return oat_class;
1540}
1541
1542static uint32_t GetOatMethodIndexFromMethodIndex(const DexFile& dex_file, uint16_t class_def_idx,
1543                                                 uint32_t method_idx) {
1544  const DexFile::ClassDef& class_def = dex_file.GetClassDef(class_def_idx);
1545  const byte* class_data = dex_file.GetClassData(class_def);
1546  CHECK(class_data != NULL);
1547  ClassDataItemIterator it(dex_file, class_data);
1548  // Skip fields
1549  while (it.HasNextStaticField()) {
1550    it.Next();
1551  }
1552  while (it.HasNextInstanceField()) {
1553    it.Next();
1554  }
1555  // Process methods
1556  size_t class_def_method_index = 0;
1557  while (it.HasNextDirectMethod()) {
1558    if (it.GetMemberIndex() == method_idx) {
1559      return class_def_method_index;
1560    }
1561    class_def_method_index++;
1562    it.Next();
1563  }
1564  while (it.HasNextVirtualMethod()) {
1565    if (it.GetMemberIndex() == method_idx) {
1566      return class_def_method_index;
1567    }
1568    class_def_method_index++;
1569    it.Next();
1570  }
1571  DCHECK(!it.HasNext());
1572  LOG(FATAL) << "Failed to find method index " << method_idx << " in " << dex_file.GetLocation();
1573  return 0;
1574}
1575
1576const OatFile::OatMethod ClassLinker::GetOatMethodFor(mirror::ArtMethod* method) {
1577  // Although we overwrite the trampoline of non-static methods, we may get here via the resolution
1578  // method for direct methods (or virtual methods made direct).
1579  mirror::Class* declaring_class = method->GetDeclaringClass();
1580  size_t oat_method_index;
1581  if (method->IsStatic() || method->IsDirect()) {
1582    // Simple case where the oat method index was stashed at load time.
1583    oat_method_index = method->GetMethodIndex();
1584  } else {
1585    // We're invoking a virtual method directly (thanks to sharpening), compute the oat_method_index
1586    // by search for its position in the declared virtual methods.
1587    oat_method_index = declaring_class->NumDirectMethods();
1588    size_t end = declaring_class->NumVirtualMethods();
1589    bool found = false;
1590    for (size_t i = 0; i < end; i++) {
1591      if (declaring_class->GetVirtualMethod(i) == method) {
1592        found = true;
1593        break;
1594      }
1595      oat_method_index++;
1596    }
1597    CHECK(found) << "Didn't find oat method index for virtual method: " << PrettyMethod(method);
1598  }
1599  UniquePtr<const OatFile::OatClass>
1600      oat_class(GetOatClass(*declaring_class->GetDexCache()->GetDexFile(),
1601                            declaring_class->GetDexClassDefIndex()));
1602  CHECK(oat_class.get() != NULL);
1603  DCHECK_EQ(oat_method_index,
1604            GetOatMethodIndexFromMethodIndex(*declaring_class->GetDexCache()->GetDexFile(),
1605                                             method->GetDeclaringClass()->GetDexClassDefIndex(),
1606                                             method->GetDexMethodIndex()));
1607
1608  return oat_class->GetOatMethod(oat_method_index);
1609}
1610
1611// Special case to get oat code without overwriting a trampoline.
1612const void* ClassLinker::GetQuickOatCodeFor(mirror::ArtMethod* method) {
1613  CHECK(!method->IsAbstract()) << PrettyMethod(method);
1614  if (method->IsProxyMethod()) {
1615    return GetQuickProxyInvokeHandler();
1616  }
1617  const void* result = GetOatMethodFor(method).GetQuickCode();
1618  if (result == nullptr) {
1619    if (method->IsPortableCompiled()) {
1620      // No code? Do we expect portable code?
1621      result = GetQuickToPortableBridge();
1622    } else {
1623      // No code? You must mean to go into the interpreter.
1624      result = GetQuickToInterpreterBridge();
1625    }
1626  }
1627  return result;
1628}
1629
1630const void* ClassLinker::GetPortableOatCodeFor(mirror::ArtMethod* method,
1631                                               bool* have_portable_code) {
1632  CHECK(!method->IsAbstract()) << PrettyMethod(method);
1633  *have_portable_code = false;
1634  if (method->IsProxyMethod()) {
1635    return GetPortableProxyInvokeHandler();
1636  }
1637  const void* result = GetOatMethodFor(method).GetPortableCode();
1638  if (result == nullptr) {
1639    if (GetOatMethodFor(method).GetQuickCode() == nullptr) {
1640      // No code? You must mean to go into the interpreter.
1641      result = GetPortableToInterpreterBridge();
1642    } else {
1643      // No code? But there's quick code, so use a bridge.
1644      result = GetPortableToQuickBridge();
1645    }
1646  } else {
1647    *have_portable_code = true;
1648  }
1649  return result;
1650}
1651
1652const void* ClassLinker::GetQuickOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1653                                            uint32_t method_idx) {
1654  UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(dex_file, class_def_idx));
1655  CHECK(oat_class.get() != nullptr);
1656  uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
1657  return oat_class->GetOatMethod(oat_method_idx).GetQuickCode();
1658}
1659
1660const void* ClassLinker::GetPortableOatCodeFor(const DexFile& dex_file, uint16_t class_def_idx,
1661                                               uint32_t method_idx) {
1662  UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(dex_file, class_def_idx));
1663  CHECK(oat_class.get() != nullptr);
1664  uint32_t oat_method_idx = GetOatMethodIndexFromMethodIndex(dex_file, class_def_idx, method_idx);
1665  return oat_class->GetOatMethod(oat_method_idx).GetPortableCode();
1666}
1667
1668// Returns true if the method must run with interpreter, false otherwise.
1669static bool NeedsInterpreter(mirror::ArtMethod* method, const void* quick_code,
1670                             const void* portable_code) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1671  if ((quick_code == nullptr) && (portable_code == nullptr)) {
1672    // No code: need interpreter.
1673    DCHECK(!method->IsNative());
1674    return true;
1675  }
1676#ifdef ART_SEA_IR_MODE
1677  ScopedObjectAccess soa(Thread::Current());
1678  if (std::string::npos != PrettyMethod(method).find("fibonacci")) {
1679    LOG(INFO) << "Found " << PrettyMethod(method);
1680    return false;
1681  }
1682#endif
1683  // If interpreter mode is enabled, every method (except native and proxy) must
1684  // be run with interpreter.
1685  return Runtime::Current()->GetInstrumentation()->InterpretOnly() &&
1686         !method->IsNative() && !method->IsProxyMethod();
1687}
1688
1689void ClassLinker::FixupStaticTrampolines(mirror::Class* klass) {
1690  if (klass->NumDirectMethods() == 0) {
1691    return;  // No direct methods => no static methods.
1692  }
1693  Runtime* runtime = Runtime::Current();
1694  if (!runtime->IsStarted() || runtime->UseCompileTimeClassPath()) {
1695    return;  // OAT file unavailable.
1696  }
1697  ClassHelper kh(klass);
1698  const DexFile& dex_file = kh.GetDexFile();
1699  const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
1700  CHECK(dex_class_def != nullptr);
1701  const byte* class_data = dex_file.GetClassData(*dex_class_def);
1702  // There should always be class data if there were direct methods.
1703  CHECK(class_data != nullptr) << PrettyDescriptor(klass);
1704  UniquePtr<const OatFile::OatClass> oat_class(GetOatClass(dex_file, klass->GetDexClassDefIndex()));
1705  CHECK(oat_class.get() != nullptr);
1706  ClassDataItemIterator it(dex_file, class_data);
1707  // Skip fields
1708  while (it.HasNextStaticField()) {
1709    it.Next();
1710  }
1711  while (it.HasNextInstanceField()) {
1712    it.Next();
1713  }
1714  // Link the code of methods skipped by LinkCode.
1715  for (size_t method_index = 0; it.HasNextDirectMethod(); ++method_index, it.Next()) {
1716    mirror::ArtMethod* method = klass->GetDirectMethod(method_index);
1717    if (!method->IsStatic()) {
1718      // Only update static methods.
1719      continue;
1720    }
1721    const void* portable_code = oat_class->GetOatMethod(method_index).GetPortableCode();
1722    const void* quick_code = oat_class->GetOatMethod(method_index).GetQuickCode();
1723    const bool enter_interpreter = NeedsInterpreter(method, quick_code, portable_code);
1724    bool have_portable_code = false;
1725    if (enter_interpreter) {
1726      // Use interpreter entry point.
1727      portable_code = GetPortableToInterpreterBridge();
1728      quick_code = GetQuickToInterpreterBridge();
1729    } else {
1730      if (portable_code == nullptr) {
1731        portable_code = GetPortableToQuickBridge();
1732      } else {
1733        have_portable_code = true;
1734      }
1735      if (quick_code == nullptr) {
1736        quick_code = GetQuickToPortableBridge();
1737      }
1738    }
1739    runtime->GetInstrumentation()->UpdateMethodsCode(method, quick_code, portable_code,
1740                                                     have_portable_code);
1741  }
1742  // Ignore virtual methods on the iterator.
1743}
1744
1745static void LinkCode(const SirtRef<mirror::ArtMethod>& method, const OatFile::OatClass* oat_class,
1746                     uint32_t method_index)
1747    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1748  // Method shouldn't have already been linked.
1749  DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
1750  DCHECK(method->GetEntryPointFromPortableCompiledCode() == nullptr);
1751  // Every kind of method should at least get an invoke stub from the oat_method.
1752  // non-abstract methods also get their code pointers.
1753  const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
1754  oat_method.LinkMethod(method.get());
1755
1756  // Install entry point from interpreter.
1757  Runtime* runtime = Runtime::Current();
1758  bool enter_interpreter = NeedsInterpreter(method.get(),
1759                                            method->GetEntryPointFromQuickCompiledCode(),
1760                                            method->GetEntryPointFromPortableCompiledCode());
1761  if (enter_interpreter) {
1762    method->SetEntryPointFromInterpreter(interpreter::artInterpreterToInterpreterBridge);
1763  } else {
1764    method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
1765  }
1766
1767  if (method->IsAbstract()) {
1768    method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1769    method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
1770    return;
1771  }
1772
1773  bool have_portable_code = false;
1774  if (method->IsStatic() && !method->IsConstructor()) {
1775    // For static methods excluding the class initializer, install the trampoline.
1776    // It will be replaced by the proper entry point by ClassLinker::FixupStaticTrampolines
1777    // after initializing class (see ClassLinker::InitializeClass method).
1778    method->SetEntryPointFromQuickCompiledCode(GetQuickResolutionTrampoline(runtime->GetClassLinker()));
1779    method->SetEntryPointFromPortableCompiledCode(GetPortableResolutionTrampoline(runtime->GetClassLinker()));
1780  } else if (enter_interpreter) {
1781    // Set entry point from compiled code if there's no code or in interpreter only mode.
1782    method->SetEntryPointFromQuickCompiledCode(GetQuickToInterpreterBridge());
1783    method->SetEntryPointFromPortableCompiledCode(GetPortableToInterpreterBridge());
1784  } else if (method->GetEntryPointFromPortableCompiledCode() != nullptr) {
1785    DCHECK(method->GetEntryPointFromQuickCompiledCode() == nullptr);
1786    have_portable_code = true;
1787    method->SetEntryPointFromQuickCompiledCode(GetQuickToPortableBridge());
1788  } else {
1789    DCHECK(method->GetEntryPointFromQuickCompiledCode() != nullptr);
1790    method->SetEntryPointFromPortableCompiledCode(GetPortableToQuickBridge());
1791  }
1792
1793  if (method->IsNative()) {
1794    // Unregistering restores the dlsym lookup stub.
1795    method->UnregisterNative(Thread::Current());
1796  }
1797
1798  // Allow instrumentation its chance to hijack code.
1799  runtime->GetInstrumentation()->UpdateMethodsCode(method.get(),
1800                                                   method->GetEntryPointFromQuickCompiledCode(),
1801                                                   method->GetEntryPointFromPortableCompiledCode(),
1802                                                   have_portable_code);
1803}
1804
1805void ClassLinker::LoadClass(const DexFile& dex_file,
1806                            const DexFile::ClassDef& dex_class_def,
1807                            const SirtRef<mirror::Class>& klass,
1808                            mirror::ClassLoader* class_loader) {
1809  CHECK(klass.get() != NULL);
1810  CHECK(klass->GetDexCache() != NULL);
1811  CHECK_EQ(mirror::Class::kStatusNotReady, klass->GetStatus());
1812  const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
1813  CHECK(descriptor != NULL);
1814
1815  klass->SetClass(GetClassRoot(kJavaLangClass));
1816  uint32_t access_flags = dex_class_def.access_flags_;
1817  // Make sure that none of our runtime-only flags are set.
1818  CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
1819  klass->SetAccessFlags(access_flags);
1820  klass->SetClassLoader(class_loader);
1821  DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
1822  klass->SetStatus(mirror::Class::kStatusIdx, NULL);
1823
1824  klass->SetDexClassDefIndex(dex_file.GetIndexForClassDef(dex_class_def));
1825  klass->SetDexTypeIndex(dex_class_def.class_idx_);
1826
1827  // Load fields fields.
1828  const byte* class_data = dex_file.GetClassData(dex_class_def);
1829  if (class_data == NULL) {
1830    return;  // no fields or methods - for example a marker interface
1831  }
1832  ClassDataItemIterator it(dex_file, class_data);
1833  Thread* self = Thread::Current();
1834  if (it.NumStaticFields() != 0) {
1835    mirror::ObjectArray<mirror::ArtField>* statics = AllocArtFieldArray(self, it.NumStaticFields());
1836    if (UNLIKELY(statics == NULL)) {
1837      CHECK(self->IsExceptionPending());  // OOME.
1838      return;
1839    }
1840    klass->SetSFields(statics);
1841  }
1842  if (it.NumInstanceFields() != 0) {
1843    mirror::ObjectArray<mirror::ArtField>* fields =
1844        AllocArtFieldArray(self, it.NumInstanceFields());
1845    if (UNLIKELY(fields == NULL)) {
1846      CHECK(self->IsExceptionPending());  // OOME.
1847      return;
1848    }
1849    klass->SetIFields(fields);
1850  }
1851  for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1852    SirtRef<mirror::ArtField> sfield(self, AllocArtField(self));
1853    if (UNLIKELY(sfield.get() == NULL)) {
1854      CHECK(self->IsExceptionPending());  // OOME.
1855      return;
1856    }
1857    klass->SetStaticField(i, sfield.get());
1858    LoadField(dex_file, it, klass, sfield);
1859  }
1860  for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1861    SirtRef<mirror::ArtField> ifield(self, AllocArtField(self));
1862    if (UNLIKELY(ifield.get() == NULL)) {
1863      CHECK(self->IsExceptionPending());  // OOME.
1864      return;
1865    }
1866    klass->SetInstanceField(i, ifield.get());
1867    LoadField(dex_file, it, klass, ifield);
1868  }
1869
1870  UniquePtr<const OatFile::OatClass> oat_class;
1871  if (Runtime::Current()->IsStarted() && !Runtime::Current()->UseCompileTimeClassPath()) {
1872    oat_class.reset(GetOatClass(dex_file, klass->GetDexClassDefIndex()));
1873  }
1874
1875  // Load methods.
1876  if (it.NumDirectMethods() != 0) {
1877    // TODO: append direct methods to class object
1878    mirror::ObjectArray<mirror::ArtMethod>* directs =
1879         AllocArtMethodArray(self, it.NumDirectMethods());
1880    if (UNLIKELY(directs == NULL)) {
1881      CHECK(self->IsExceptionPending());  // OOME.
1882      return;
1883    }
1884    klass->SetDirectMethods(directs);
1885  }
1886  if (it.NumVirtualMethods() != 0) {
1887    // TODO: append direct methods to class object
1888    mirror::ObjectArray<mirror::ArtMethod>* virtuals =
1889        AllocArtMethodArray(self, it.NumVirtualMethods());
1890    if (UNLIKELY(virtuals == NULL)) {
1891      CHECK(self->IsExceptionPending());  // OOME.
1892      return;
1893    }
1894    klass->SetVirtualMethods(virtuals);
1895  }
1896  size_t class_def_method_index = 0;
1897  for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1898    SirtRef<mirror::ArtMethod> method(self, LoadMethod(self, dex_file, it, klass));
1899    if (UNLIKELY(method.get() == NULL)) {
1900      CHECK(self->IsExceptionPending());  // OOME.
1901      return;
1902    }
1903    klass->SetDirectMethod(i, method.get());
1904    if (oat_class.get() != NULL) {
1905      LinkCode(method, oat_class.get(), class_def_method_index);
1906    }
1907    method->SetMethodIndex(class_def_method_index);
1908    class_def_method_index++;
1909  }
1910  for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1911    SirtRef<mirror::ArtMethod> method(self, LoadMethod(self, dex_file, it, klass));
1912    if (UNLIKELY(method.get() == NULL)) {
1913      CHECK(self->IsExceptionPending());  // OOME.
1914      return;
1915    }
1916    klass->SetVirtualMethod(i, method.get());
1917    DCHECK_EQ(class_def_method_index, it.NumDirectMethods() + i);
1918    if (oat_class.get() != NULL) {
1919      LinkCode(method, oat_class.get(), class_def_method_index);
1920    }
1921    class_def_method_index++;
1922  }
1923  DCHECK(!it.HasNext());
1924}
1925
1926void ClassLinker::LoadField(const DexFile& /*dex_file*/, const ClassDataItemIterator& it,
1927                            const SirtRef<mirror::Class>& klass,
1928                            const SirtRef<mirror::ArtField>& dst) {
1929  uint32_t field_idx = it.GetMemberIndex();
1930  dst->SetDexFieldIndex(field_idx);
1931  dst->SetDeclaringClass(klass.get());
1932  dst->SetAccessFlags(it.GetMemberAccessFlags());
1933}
1934
1935mirror::ArtMethod* ClassLinker::LoadMethod(Thread* self, const DexFile& dex_file,
1936                                           const ClassDataItemIterator& it,
1937                                           const SirtRef<mirror::Class>& klass) {
1938  uint32_t dex_method_idx = it.GetMemberIndex();
1939  const DexFile::MethodId& method_id = dex_file.GetMethodId(dex_method_idx);
1940  const char* method_name = dex_file.StringDataByIdx(method_id.name_idx_);
1941
1942  mirror::ArtMethod* dst = AllocArtMethod(self);
1943  if (UNLIKELY(dst == NULL)) {
1944    CHECK(self->IsExceptionPending());  // OOME.
1945    return NULL;
1946  }
1947  DCHECK(dst->IsArtMethod()) << PrettyDescriptor(dst->GetClass());
1948
1949  const char* old_cause = self->StartAssertNoThreadSuspension("LoadMethod");
1950  dst->SetDexMethodIndex(dex_method_idx);
1951  dst->SetDeclaringClass(klass.get());
1952  dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
1953
1954  dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1955  dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1956  dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1957
1958  uint32_t access_flags = it.GetMemberAccessFlags();
1959
1960  if (UNLIKELY(strcmp("finalize", method_name) == 0)) {
1961    // Set finalizable flag on declaring class.
1962    if (strcmp("V", dex_file.GetShorty(method_id.proto_idx_)) == 0) {
1963      // Void return type.
1964      if (klass->GetClassLoader() != NULL) {  // All non-boot finalizer methods are flagged
1965        klass->SetFinalizable();
1966      } else {
1967        ClassHelper kh(klass.get());
1968        const char* klass_descriptor = kh.GetDescriptor();
1969        // The Enum class declares a "final" finalize() method to prevent subclasses from
1970        // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1971        // subclasses, so we exclude it here.
1972        // We also want to avoid setting the flag on Object, where we know that finalize() is
1973        // empty.
1974        if ((strcmp("Ljava/lang/Object;", klass_descriptor) != 0) &&
1975            (strcmp("Ljava/lang/Enum;", klass_descriptor) != 0)) {
1976          klass->SetFinalizable();
1977        }
1978      }
1979    }
1980  } else if (method_name[0] == '<') {
1981    // Fix broken access flags for initializers. Bug 11157540.
1982    bool is_init = (strcmp("<init>", method_name) == 0);
1983    bool is_clinit = !is_init && (strcmp("<clinit>", method_name) == 0);
1984    if (UNLIKELY(!is_init && !is_clinit)) {
1985      LOG(WARNING) << "Unexpected '<' at start of method name " << method_name;
1986    } else {
1987      if (UNLIKELY((access_flags & kAccConstructor) == 0)) {
1988        LOG(WARNING) << method_name << " didn't have expected constructor access flag in class "
1989            << PrettyDescriptor(klass.get()) << " in dex file " << dex_file.GetLocation();
1990        access_flags |= kAccConstructor;
1991      }
1992    }
1993  }
1994  dst->SetAccessFlags(access_flags);
1995
1996  self->EndAssertNoThreadSuspension(old_cause);
1997  return dst;
1998}
1999
2000void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
2001  Thread* self = Thread::Current();
2002  SirtRef<mirror::DexCache> dex_cache(self, AllocDexCache(self, dex_file));
2003  CHECK(dex_cache.get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
2004  AppendToBootClassPath(dex_file, dex_cache);
2005}
2006
2007void ClassLinker::AppendToBootClassPath(const DexFile& dex_file,
2008                                        const SirtRef<mirror::DexCache>& dex_cache) {
2009  CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
2010  boot_class_path_.push_back(&dex_file);
2011  RegisterDexFile(dex_file, dex_cache);
2012}
2013
2014bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
2015  dex_lock_.AssertSharedHeld(Thread::Current());
2016  for (size_t i = 0; i != dex_caches_.size(); ++i) {
2017    if (dex_caches_[i]->GetDexFile() == &dex_file) {
2018      return true;
2019    }
2020  }
2021  return false;
2022}
2023
2024bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
2025  ReaderMutexLock mu(Thread::Current(), dex_lock_);
2026  return IsDexFileRegisteredLocked(dex_file);
2027}
2028
2029void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file,
2030                                        const SirtRef<mirror::DexCache>& dex_cache) {
2031  dex_lock_.AssertExclusiveHeld(Thread::Current());
2032  CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
2033  CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()))
2034      << dex_cache->GetLocation()->ToModifiedUtf8() << " " << dex_file.GetLocation();
2035  dex_caches_.push_back(dex_cache.get());
2036  dex_cache->SetDexFile(&dex_file);
2037  dex_caches_dirty_ = true;
2038}
2039
2040void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
2041  Thread* self = Thread::Current();
2042  {
2043    ReaderMutexLock mu(self, dex_lock_);
2044    if (IsDexFileRegisteredLocked(dex_file)) {
2045      return;
2046    }
2047  }
2048  // Don't alloc while holding the lock, since allocation may need to
2049  // suspend all threads and another thread may need the dex_lock_ to
2050  // get to a suspend point.
2051  SirtRef<mirror::DexCache> dex_cache(self, AllocDexCache(self, dex_file));
2052  CHECK(dex_cache.get() != NULL) << "Failed to allocate dex cache for " << dex_file.GetLocation();
2053  {
2054    WriterMutexLock mu(self, dex_lock_);
2055    if (IsDexFileRegisteredLocked(dex_file)) {
2056      return;
2057    }
2058    RegisterDexFileLocked(dex_file, dex_cache);
2059  }
2060}
2061
2062void ClassLinker::RegisterDexFile(const DexFile& dex_file,
2063                                  const SirtRef<mirror::DexCache>& dex_cache) {
2064  WriterMutexLock mu(Thread::Current(), dex_lock_);
2065  RegisterDexFileLocked(dex_file, dex_cache);
2066}
2067
2068mirror::DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
2069  ReaderMutexLock mu(Thread::Current(), dex_lock_);
2070  // Search assuming unique-ness of dex file.
2071  for (size_t i = 0; i != dex_caches_.size(); ++i) {
2072    mirror::DexCache* dex_cache = dex_caches_[i];
2073    if (dex_cache->GetDexFile() == &dex_file) {
2074      return dex_cache;
2075    }
2076  }
2077  // Search matching by location name.
2078  std::string location(dex_file.GetLocation());
2079  for (size_t i = 0; i != dex_caches_.size(); ++i) {
2080    mirror::DexCache* dex_cache = dex_caches_[i];
2081    if (dex_cache->GetDexFile()->GetLocation() == location) {
2082      return dex_cache;
2083    }
2084  }
2085  // Failure, dump diagnostic and abort.
2086  for (size_t i = 0; i != dex_caches_.size(); ++i) {
2087    mirror::DexCache* dex_cache = dex_caches_[i];
2088    LOG(ERROR) << "Registered dex file " << i << " = " << dex_cache->GetDexFile()->GetLocation();
2089  }
2090  LOG(FATAL) << "Failed to find DexCache for DexFile " << location;
2091  return NULL;
2092}
2093
2094void ClassLinker::FixupDexCaches(mirror::ArtMethod* resolution_method) const {
2095  ReaderMutexLock mu(Thread::Current(), dex_lock_);
2096  for (size_t i = 0; i != dex_caches_.size(); ++i) {
2097    dex_caches_[i]->Fixup(resolution_method);
2098  }
2099}
2100
2101mirror::Class* ClassLinker::CreatePrimitiveClass(Thread* self, Primitive::Type type) {
2102  mirror::Class* klass = AllocClass(self, sizeof(mirror::Class));
2103  if (UNLIKELY(klass == NULL)) {
2104    return NULL;
2105  }
2106  return InitializePrimitiveClass(klass, type);
2107}
2108
2109mirror::Class* ClassLinker::InitializePrimitiveClass(mirror::Class* primitive_class,
2110                                                     Primitive::Type type) {
2111  CHECK(primitive_class != NULL);
2112  // Must hold lock on object when initializing.
2113  Thread* self = Thread::Current();
2114  SirtRef<mirror::Class> sirt_class(self, primitive_class);
2115  ObjectLock<mirror::Class> lock(self, &sirt_class);
2116  primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
2117  primitive_class->SetPrimitiveType(type);
2118  primitive_class->SetStatus(mirror::Class::kStatusInitialized, self);
2119  const char* descriptor = Primitive::Descriptor(type);
2120  mirror::Class* existing = InsertClass(descriptor, primitive_class, Hash(descriptor));
2121  CHECK(existing == NULL) << "InitPrimitiveClass(" << type << ") failed";
2122  return primitive_class;
2123}
2124
2125// Create an array class (i.e. the class object for the array, not the
2126// array itself).  "descriptor" looks like "[C" or "[[[[B" or
2127// "[Ljava/lang/String;".
2128//
2129// If "descriptor" refers to an array of primitives, look up the
2130// primitive type's internally-generated class object.
2131//
2132// "class_loader" is the class loader of the class that's referring to
2133// us.  It's used to ensure that we're looking for the element type in
2134// the right context.  It does NOT become the class loader for the
2135// array class; that always comes from the base element class.
2136//
2137// Returns NULL with an exception raised on failure.
2138mirror::Class* ClassLinker::CreateArrayClass(const char* descriptor,
2139                                             const SirtRef<mirror::ClassLoader>& class_loader) {
2140  // Identify the underlying component type
2141  CHECK_EQ('[', descriptor[0]);
2142  Thread* self = Thread::Current();
2143  SirtRef<mirror::Class> component_type(self, FindClass(descriptor + 1, class_loader));
2144  if (component_type.get() == nullptr) {
2145    DCHECK(self->IsExceptionPending());
2146    return nullptr;
2147  }
2148
2149  // See if the component type is already loaded.  Array classes are
2150  // always associated with the class loader of their underlying
2151  // element type -- an array of Strings goes with the loader for
2152  // java/lang/String -- so we need to look for it there.  (The
2153  // caller should have checked for the existence of the class
2154  // before calling here, but they did so with *their* class loader,
2155  // not the component type's loader.)
2156  //
2157  // If we find it, the caller adds "loader" to the class' initiating
2158  // loader list, which should prevent us from going through this again.
2159  //
2160  // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
2161  // are the same, because our caller (FindClass) just did the
2162  // lookup.  (Even if we get this wrong we still have correct behavior,
2163  // because we effectively do this lookup again when we add the new
2164  // class to the hash table --- necessary because of possible races with
2165  // other threads.)
2166  if (class_loader.get() != component_type->GetClassLoader()) {
2167    mirror::Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
2168    if (new_class != NULL) {
2169      return new_class;
2170    }
2171  }
2172
2173  // Fill out the fields in the Class.
2174  //
2175  // It is possible to execute some methods against arrays, because
2176  // all arrays are subclasses of java_lang_Object_, so we need to set
2177  // up a vtable.  We can just point at the one in java_lang_Object_.
2178  //
2179  // Array classes are simple enough that we don't need to do a full
2180  // link step.
2181  SirtRef<mirror::Class> new_class(self, NULL);
2182  if (UNLIKELY(!init_done_)) {
2183    // Classes that were hand created, ie not by FindSystemClass
2184    if (strcmp(descriptor, "[Ljava/lang/Class;") == 0) {
2185      new_class.reset(GetClassRoot(kClassArrayClass));
2186    } else if (strcmp(descriptor, "[Ljava/lang/Object;") == 0) {
2187      new_class.reset(GetClassRoot(kObjectArrayClass));
2188    } else if (strcmp(descriptor, class_roots_descriptors_[kJavaLangStringArrayClass]) == 0) {
2189      new_class.reset(GetClassRoot(kJavaLangStringArrayClass));
2190    } else if (strcmp(descriptor,
2191                      class_roots_descriptors_[kJavaLangReflectArtMethodArrayClass]) == 0) {
2192      new_class.reset(GetClassRoot(kJavaLangReflectArtMethodArrayClass));
2193    } else if (strcmp(descriptor,
2194                      class_roots_descriptors_[kJavaLangReflectArtFieldArrayClass]) == 0) {
2195      new_class.reset(GetClassRoot(kJavaLangReflectArtFieldArrayClass));
2196    } else if (strcmp(descriptor, "[C") == 0) {
2197      new_class.reset(GetClassRoot(kCharArrayClass));
2198    } else if (strcmp(descriptor, "[I") == 0) {
2199      new_class.reset(GetClassRoot(kIntArrayClass));
2200    }
2201  }
2202  if (new_class.get() == nullptr) {
2203    new_class.reset(AllocClass(self, sizeof(mirror::Class)));
2204    if (new_class.get() == nullptr) {
2205      return nullptr;
2206    }
2207    new_class->SetComponentType(component_type.get());
2208  }
2209  ObjectLock<mirror::Class> lock(self, &new_class);  // Must hold lock on object when initializing.
2210  DCHECK(new_class->GetComponentType() != NULL);
2211  mirror::Class* java_lang_Object = GetClassRoot(kJavaLangObject);
2212  new_class->SetSuperClass(java_lang_Object);
2213  new_class->SetVTable(java_lang_Object->GetVTable());
2214  new_class->SetPrimitiveType(Primitive::kPrimNot);
2215  new_class->SetClassLoader(component_type->GetClassLoader());
2216  new_class->SetStatus(mirror::Class::kStatusInitialized, self);
2217  // don't need to set new_class->SetObjectSize(..)
2218  // because Object::SizeOf delegates to Array::SizeOf
2219
2220
2221  // All arrays have java/lang/Cloneable and java/io/Serializable as
2222  // interfaces.  We need to set that up here, so that stuff like
2223  // "instanceof" works right.
2224  //
2225  // Note: The GC could run during the call to FindSystemClass,
2226  // so we need to make sure the class object is GC-valid while we're in
2227  // there.  Do this by clearing the interface list so the GC will just
2228  // think that the entries are null.
2229
2230
2231  // Use the single, global copies of "interfaces" and "iftable"
2232  // (remember not to free them for arrays).
2233  CHECK(array_iftable_ != nullptr);
2234  new_class->SetIfTable(array_iftable_);
2235
2236  // Inherit access flags from the component type.
2237  int access_flags = new_class->GetComponentType()->GetAccessFlags();
2238  // Lose any implementation detail flags; in particular, arrays aren't finalizable.
2239  access_flags &= kAccJavaFlagsMask;
2240  // Arrays can't be used as a superclass or interface, so we want to add "abstract final"
2241  // and remove "interface".
2242  access_flags |= kAccAbstract | kAccFinal;
2243  access_flags &= ~kAccInterface;
2244
2245  new_class->SetAccessFlags(access_flags);
2246
2247  mirror::Class* existing = InsertClass(descriptor, new_class.get(), Hash(descriptor));
2248  if (existing == nullptr) {
2249    return new_class.get();
2250  }
2251  // Another thread must have loaded the class after we
2252  // started but before we finished.  Abandon what we've
2253  // done.
2254  //
2255  // (Yes, this happens.)
2256
2257  return existing;
2258}
2259
2260mirror::Class* ClassLinker::FindPrimitiveClass(char type) {
2261  switch (Primitive::GetType(type)) {
2262    case Primitive::kPrimByte:
2263      return GetClassRoot(kPrimitiveByte);
2264    case Primitive::kPrimChar:
2265      return GetClassRoot(kPrimitiveChar);
2266    case Primitive::kPrimDouble:
2267      return GetClassRoot(kPrimitiveDouble);
2268    case Primitive::kPrimFloat:
2269      return GetClassRoot(kPrimitiveFloat);
2270    case Primitive::kPrimInt:
2271      return GetClassRoot(kPrimitiveInt);
2272    case Primitive::kPrimLong:
2273      return GetClassRoot(kPrimitiveLong);
2274    case Primitive::kPrimShort:
2275      return GetClassRoot(kPrimitiveShort);
2276    case Primitive::kPrimBoolean:
2277      return GetClassRoot(kPrimitiveBoolean);
2278    case Primitive::kPrimVoid:
2279      return GetClassRoot(kPrimitiveVoid);
2280    case Primitive::kPrimNot:
2281      break;
2282  }
2283  std::string printable_type(PrintableChar(type));
2284  ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
2285  return NULL;
2286}
2287
2288mirror::Class* ClassLinker::InsertClass(const char* descriptor, mirror::Class* klass,
2289                                        size_t hash) {
2290  if (VLOG_IS_ON(class_linker)) {
2291    mirror::DexCache* dex_cache = klass->GetDexCache();
2292    std::string source;
2293    if (dex_cache != NULL) {
2294      source += " from ";
2295      source += dex_cache->GetLocation()->ToModifiedUtf8();
2296    }
2297    LOG(INFO) << "Loaded class " << descriptor << source;
2298  }
2299  WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2300  mirror::Class* existing =
2301      LookupClassFromTableLocked(descriptor, klass->GetClassLoader(), hash);
2302  if (existing != NULL) {
2303    return existing;
2304  }
2305  if (kIsDebugBuild && klass->GetClassLoader() == NULL && dex_cache_image_class_lookup_required_) {
2306    // Check a class loaded with the system class loader matches one in the image if the class
2307    // is in the image.
2308    existing = LookupClassFromImage(descriptor);
2309    if (existing != NULL) {
2310      CHECK(klass == existing);
2311    }
2312  }
2313  Runtime::Current()->GetHeap()->VerifyObject(klass);
2314  class_table_.insert(std::make_pair(hash, klass));
2315  class_table_dirty_ = true;
2316  return NULL;
2317}
2318
2319bool ClassLinker::RemoveClass(const char* descriptor, const mirror::ClassLoader* class_loader) {
2320  size_t hash = Hash(descriptor);
2321  WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2322  for (auto it = class_table_.lower_bound(hash), end = class_table_.end(); it != end && it->first == hash;
2323       ++it) {
2324    mirror::Class* klass = it->second;
2325    ClassHelper kh(klass);
2326    if ((klass->GetClassLoader() == class_loader) &&
2327        (strcmp(descriptor, kh.GetDescriptor()) == 0)) {
2328      class_table_.erase(it);
2329      return true;
2330    }
2331  }
2332  return false;
2333}
2334
2335mirror::Class* ClassLinker::LookupClass(const char* descriptor,
2336                                        const mirror::ClassLoader* class_loader) {
2337  size_t hash = Hash(descriptor);
2338  {
2339    ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2340    mirror::Class* result = LookupClassFromTableLocked(descriptor, class_loader, hash);
2341    if (result != NULL) {
2342      return result;
2343    }
2344  }
2345  if (class_loader != NULL || !dex_cache_image_class_lookup_required_) {
2346    return NULL;
2347  } else {
2348    // Lookup failed but need to search dex_caches_.
2349    mirror::Class* result = LookupClassFromImage(descriptor);
2350    if (result != NULL) {
2351      InsertClass(descriptor, result, hash);
2352    } else {
2353      // Searching the image dex files/caches failed, we don't want to get into this situation
2354      // often as map searches are faster, so after kMaxFailedDexCacheLookups move all image
2355      // classes into the class table.
2356      const int32_t kMaxFailedDexCacheLookups = 1000;
2357      if (++failed_dex_cache_class_lookups_ > kMaxFailedDexCacheLookups) {
2358        MoveImageClassesToClassTable();
2359      }
2360    }
2361    return result;
2362  }
2363}
2364
2365mirror::Class* ClassLinker::LookupClassFromTableLocked(const char* descriptor,
2366                                                       const mirror::ClassLoader* class_loader,
2367                                                       size_t hash) {
2368  auto end = class_table_.end();
2369  for (auto it = class_table_.lower_bound(hash); it != end && it->first == hash; ++it) {
2370    mirror::Class* klass = it->second;
2371    ClassHelper kh(klass);
2372    if ((klass->GetClassLoader() == class_loader) &&
2373        (strcmp(descriptor, kh.GetDescriptor()) == 0)) {
2374      if (kIsDebugBuild) {
2375        // Check for duplicates in the table.
2376        for (++it; it != end && it->first == hash; ++it) {
2377          mirror::Class* klass2 = it->second;
2378          ClassHelper kh(klass2);
2379          CHECK(!((klass2->GetClassLoader() == class_loader) &&
2380                  (strcmp(descriptor, kh.GetDescriptor()) == 0)))
2381              << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
2382              << PrettyClass(klass2) << " " << klass2 << " " << klass2->GetClassLoader();
2383        }
2384      }
2385      return klass;
2386    }
2387  }
2388  return NULL;
2389}
2390
2391static mirror::ObjectArray<mirror::DexCache>* GetImageDexCaches()
2392    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2393  gc::space::ImageSpace* image = Runtime::Current()->GetHeap()->GetImageSpace();
2394  CHECK(image != NULL);
2395  mirror::Object* root = image->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
2396  return root->AsObjectArray<mirror::DexCache>();
2397}
2398
2399void ClassLinker::MoveImageClassesToClassTable() {
2400  Thread* self = Thread::Current();
2401  WriterMutexLock mu(self, *Locks::classlinker_classes_lock_);
2402  if (!dex_cache_image_class_lookup_required_) {
2403    return;  // All dex cache classes are already in the class table.
2404  }
2405  const char* old_no_suspend_cause =
2406      self->StartAssertNoThreadSuspension("Moving image classes to class table");
2407  mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2408  for (int32_t i = 0; i < dex_caches->GetLength(); i++) {
2409    mirror::DexCache* dex_cache = dex_caches->Get(i);
2410    mirror::ObjectArray<mirror::Class>* types = dex_cache->GetResolvedTypes();
2411    for (int32_t j = 0; j < types->GetLength(); j++) {
2412      mirror::Class* klass = types->Get(j);
2413      if (klass != NULL) {
2414        ClassHelper kh(klass);
2415        DCHECK(klass->GetClassLoader() == NULL);
2416        const char* descriptor = kh.GetDescriptor();
2417        size_t hash = Hash(descriptor);
2418        mirror::Class* existing = LookupClassFromTableLocked(descriptor, NULL, hash);
2419        if (existing != NULL) {
2420          CHECK(existing == klass) << PrettyClassAndClassLoader(existing) << " != "
2421              << PrettyClassAndClassLoader(klass);
2422        } else {
2423          class_table_.insert(std::make_pair(hash, klass));
2424        }
2425      }
2426    }
2427  }
2428  class_table_dirty_ = true;
2429  dex_cache_image_class_lookup_required_ = false;
2430  self->EndAssertNoThreadSuspension(old_no_suspend_cause);
2431}
2432
2433mirror::Class* ClassLinker::LookupClassFromImage(const char* descriptor) {
2434  Thread* self = Thread::Current();
2435  const char* old_no_suspend_cause =
2436      self->StartAssertNoThreadSuspension("Image class lookup");
2437  mirror::ObjectArray<mirror::DexCache>* dex_caches = GetImageDexCaches();
2438  for (int32_t i = 0; i < dex_caches->GetLength(); ++i) {
2439    mirror::DexCache* dex_cache = dex_caches->Get(i);
2440    const DexFile* dex_file = dex_cache->GetDexFile();
2441    // Try binary searching the string/type index.
2442    const DexFile::StringId* string_id = dex_file->FindStringId(descriptor);
2443    if (string_id != NULL) {
2444      const DexFile::TypeId* type_id =
2445          dex_file->FindTypeId(dex_file->GetIndexForStringId(*string_id));
2446      if (type_id != NULL) {
2447        uint16_t type_idx = dex_file->GetIndexForTypeId(*type_id);
2448        mirror::Class* klass = dex_cache->GetResolvedType(type_idx);
2449        if (klass != NULL) {
2450          self->EndAssertNoThreadSuspension(old_no_suspend_cause);
2451          return klass;
2452        }
2453      }
2454    }
2455  }
2456  self->EndAssertNoThreadSuspension(old_no_suspend_cause);
2457  return NULL;
2458}
2459
2460void ClassLinker::LookupClasses(const char* descriptor, std::vector<mirror::Class*>& result) {
2461  result.clear();
2462  if (dex_cache_image_class_lookup_required_) {
2463    MoveImageClassesToClassTable();
2464  }
2465  size_t hash = Hash(descriptor);
2466  ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
2467  for (auto it = class_table_.lower_bound(hash), end = class_table_.end();
2468      it != end && it->first == hash; ++it) {
2469    mirror::Class* klass = it->second;
2470    ClassHelper kh(klass);
2471    if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
2472      result.push_back(klass);
2473    }
2474  }
2475}
2476
2477void ClassLinker::VerifyClass(const SirtRef<mirror::Class>& klass) {
2478  // TODO: assert that the monitor on the Class is held
2479  Thread* self = Thread::Current();
2480  ObjectLock<mirror::Class> lock(self, &klass);
2481
2482  // Don't attempt to re-verify if already sufficiently verified.
2483  if (klass->IsVerified() ||
2484      (klass->IsCompileTimeVerified() && Runtime::Current()->IsCompiler())) {
2485    return;
2486  }
2487
2488  // The class might already be erroneous, for example at compile time if we attempted to verify
2489  // this class as a parent to another.
2490  if (klass->IsErroneous()) {
2491    ThrowEarlierClassFailure(klass.get());
2492    return;
2493  }
2494
2495  if (klass->GetStatus() == mirror::Class::kStatusResolved) {
2496    klass->SetStatus(mirror::Class::kStatusVerifying, self);
2497  } else {
2498    CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime)
2499        << PrettyClass(klass.get());
2500    CHECK(!Runtime::Current()->IsCompiler());
2501    klass->SetStatus(mirror::Class::kStatusVerifyingAtRuntime, self);
2502  }
2503
2504  // Verify super class.
2505  SirtRef<mirror::Class> super(self, klass->GetSuperClass());
2506  if (super.get() != NULL) {
2507    // Acquire lock to prevent races on verifying the super class.
2508    ObjectLock<mirror::Class> lock(self, &super);
2509
2510    if (!super->IsVerified() && !super->IsErroneous()) {
2511      VerifyClass(super);
2512    }
2513    if (!super->IsCompileTimeVerified()) {
2514      std::string error_msg(StringPrintf("Rejecting class %s that attempts to sub-class erroneous class %s",
2515                                         PrettyDescriptor(klass.get()).c_str(),
2516                                         PrettyDescriptor(super.get()).c_str()));
2517      LOG(ERROR) << error_msg  << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
2518      SirtRef<mirror::Throwable> cause(self, self->GetException(NULL));
2519      if (cause.get() != nullptr) {
2520        self->ClearException();
2521      }
2522      ThrowVerifyError(klass.get(), "%s", error_msg.c_str());
2523      if (cause.get() != nullptr) {
2524        self->GetException(nullptr)->SetCause(cause.get());
2525      }
2526      ClassReference ref(klass->GetDexCache()->GetDexFile(), klass->GetDexClassDefIndex());
2527      if (Runtime::Current()->IsCompiler()) {
2528        Runtime::Current()->GetCompilerCallbacks()->ClassRejected(ref);
2529      }
2530      klass->SetStatus(mirror::Class::kStatusError, self);
2531      return;
2532    }
2533  }
2534
2535  // Try to use verification information from the oat file, otherwise do runtime verification.
2536  const DexFile& dex_file = *klass->GetDexCache()->GetDexFile();
2537  mirror::Class::Status oat_file_class_status(mirror::Class::kStatusNotReady);
2538  bool preverified = VerifyClassUsingOatFile(dex_file, klass.get(), oat_file_class_status);
2539  if (oat_file_class_status == mirror::Class::kStatusError) {
2540    VLOG(class_linker) << "Skipping runtime verification of erroneous class "
2541        << PrettyDescriptor(klass.get()) << " in "
2542        << klass->GetDexCache()->GetLocation()->ToModifiedUtf8();
2543    ThrowVerifyError(klass.get(), "Rejecting class %s because it failed compile-time verification",
2544                     PrettyDescriptor(klass.get()).c_str());
2545    klass->SetStatus(mirror::Class::kStatusError, self);
2546    return;
2547  }
2548  verifier::MethodVerifier::FailureKind verifier_failure = verifier::MethodVerifier::kNoFailure;
2549  std::string error_msg;
2550  if (!preverified) {
2551    verifier_failure = verifier::MethodVerifier::VerifyClass(klass.get(),
2552                                                             Runtime::Current()->IsCompiler(),
2553                                                             &error_msg);
2554  }
2555  if (preverified || verifier_failure != verifier::MethodVerifier::kHardFailure) {
2556    if (!preverified && verifier_failure != verifier::MethodVerifier::kNoFailure) {
2557      VLOG(class_linker) << "Soft verification failure in class " << PrettyDescriptor(klass.get())
2558          << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2559          << " because: " << error_msg;
2560    }
2561    self->AssertNoPendingException();
2562    // Make sure all classes referenced by catch blocks are resolved.
2563    ResolveClassExceptionHandlerTypes(dex_file, klass);
2564    if (verifier_failure == verifier::MethodVerifier::kNoFailure) {
2565      // Even though there were no verifier failures we need to respect whether the super-class
2566      // was verified or requiring runtime reverification.
2567      if (super.get() == NULL || super->IsVerified()) {
2568        klass->SetStatus(mirror::Class::kStatusVerified, self);
2569      } else {
2570        CHECK_EQ(super->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
2571        klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
2572        // Pretend a soft failure occured so that we don't consider the class verified below.
2573        verifier_failure = verifier::MethodVerifier::kSoftFailure;
2574      }
2575    } else {
2576      CHECK_EQ(verifier_failure, verifier::MethodVerifier::kSoftFailure);
2577      // Soft failures at compile time should be retried at runtime. Soft
2578      // failures at runtime will be handled by slow paths in the generated
2579      // code. Set status accordingly.
2580      if (Runtime::Current()->IsCompiler()) {
2581        klass->SetStatus(mirror::Class::kStatusRetryVerificationAtRuntime, self);
2582      } else {
2583        klass->SetStatus(mirror::Class::kStatusVerified, self);
2584      }
2585    }
2586  } else {
2587    LOG(ERROR) << "Verification failed on class " << PrettyDescriptor(klass.get())
2588        << " in " << klass->GetDexCache()->GetLocation()->ToModifiedUtf8()
2589        << " because: " << error_msg;
2590    self->AssertNoPendingException();
2591    ThrowVerifyError(klass.get(), "%s", error_msg.c_str());
2592    klass->SetStatus(mirror::Class::kStatusError, self);
2593  }
2594  if (preverified || verifier_failure == verifier::MethodVerifier::kNoFailure) {
2595    // Class is verified so we don't need to do any access check on its methods.
2596    // Let the interpreter know it by setting the kAccPreverified flag onto each
2597    // method.
2598    // Note: we're going here during compilation and at runtime. When we set the
2599    // kAccPreverified flag when compiling image classes, the flag is recorded
2600    // in the image and is set when loading the image.
2601    klass->SetPreverifiedFlagOnAllMethods();
2602  }
2603}
2604
2605bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, mirror::Class* klass,
2606                                          mirror::Class::Status& oat_file_class_status) {
2607  // If we're compiling, we can only verify the class using the oat file if
2608  // we are not compiling the image or if the class we're verifying is not part of
2609  // the app.  In other words, we will only check for preverification of bootclasspath
2610  // classes.
2611  if (Runtime::Current()->IsCompiler()) {
2612    // Are we compiling the bootclasspath?
2613    if (!Runtime::Current()->UseCompileTimeClassPath()) {
2614      return false;
2615    }
2616    // We are compiling an app (not the image).
2617
2618    // Is this an app class? (I.e. not a bootclasspath class)
2619    if (klass->GetClassLoader() != NULL) {
2620      return false;
2621    }
2622  }
2623
2624  const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
2625  // Make this work with gtests, which do not set up the image properly.
2626  // TODO: we should clean up gtests to set up the image path properly.
2627  if (Runtime::Current()->IsCompiler() && (oat_file == NULL)) {
2628    return false;
2629  }
2630
2631  CHECK(oat_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
2632  uint dex_location_checksum = dex_file.GetLocationChecksum();
2633  const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation().c_str(),
2634                                                                    &dex_location_checksum);
2635  CHECK(oat_dex_file != NULL) << dex_file.GetLocation() << " " << PrettyClass(klass);
2636  uint16_t class_def_index = klass->GetDexClassDefIndex();
2637  UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
2638  CHECK(oat_class.get() != NULL)
2639          << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
2640          << ClassHelper(klass).GetDescriptor();
2641  oat_file_class_status = oat_class->GetStatus();
2642  if (oat_file_class_status == mirror::Class::kStatusVerified ||
2643      oat_file_class_status == mirror::Class::kStatusInitialized) {
2644      return true;
2645  }
2646  if (oat_file_class_status == mirror::Class::kStatusRetryVerificationAtRuntime) {
2647    // Compile time verification failed with a soft error. Compile time verification can fail
2648    // because we have incomplete type information. Consider the following:
2649    // class ... {
2650    //   Foo x;
2651    //   .... () {
2652    //     if (...) {
2653    //       v1 gets assigned a type of resolved class Foo
2654    //     } else {
2655    //       v1 gets assigned a type of unresolved class Bar
2656    //     }
2657    //     iput x = v1
2658    // } }
2659    // when we merge v1 following the if-the-else it results in Conflict
2660    // (see verifier::RegType::Merge) as we can't know the type of Bar and we could possibly be
2661    // allowing an unsafe assignment to the field x in the iput (javac may have compiled this as
2662    // it knew Bar was a sub-class of Foo, but for us this may have been moved into a separate apk
2663    // at compile time).
2664    return false;
2665  }
2666  if (oat_file_class_status == mirror::Class::kStatusError) {
2667    // Compile time verification failed with a hard error. This is caused by invalid instructions
2668    // in the class. These errors are unrecoverable.
2669    return false;
2670  }
2671  if (oat_file_class_status == mirror::Class::kStatusNotReady) {
2672    // Status is uninitialized if we couldn't determine the status at compile time, for example,
2673    // not loading the class.
2674    // TODO: when the verifier doesn't rely on Class-es failing to resolve/load the type hierarchy
2675    // isn't a problem and this case shouldn't occur
2676    return false;
2677  }
2678  LOG(FATAL) << "Unexpected class status: " << oat_file_class_status
2679             << " " << dex_file.GetLocation() << " " << PrettyClass(klass) << " "
2680             << ClassHelper(klass).GetDescriptor();
2681
2682  return false;
2683}
2684
2685void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file,
2686                                                    const SirtRef<mirror::Class>& klass) {
2687  for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
2688    ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
2689  }
2690  for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
2691    ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
2692  }
2693}
2694
2695void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file,
2696                                                     mirror::ArtMethod* method) {
2697  // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
2698  const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
2699  if (code_item == NULL) {
2700    return;  // native or abstract method
2701  }
2702  if (code_item->tries_size_ == 0) {
2703    return;  // nothing to process
2704  }
2705  const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
2706  uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
2707  ClassLinker* linker = Runtime::Current()->GetClassLinker();
2708  for (uint32_t idx = 0; idx < handlers_size; idx++) {
2709    CatchHandlerIterator iterator(handlers_ptr);
2710    for (; iterator.HasNext(); iterator.Next()) {
2711      // Ensure exception types are resolved so that they don't need resolution to be delivered,
2712      // unresolved exception types will be ignored by exception delivery
2713      if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
2714        mirror::Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
2715        if (exception_type == NULL) {
2716          DCHECK(Thread::Current()->IsExceptionPending());
2717          Thread::Current()->ClearException();
2718        }
2719      }
2720    }
2721    handlers_ptr = iterator.EndDataPointer();
2722  }
2723}
2724
2725static void CheckProxyConstructor(mirror::ArtMethod* constructor);
2726static void CheckProxyMethod(mirror::ArtMethod* method,
2727                             SirtRef<mirror::ArtMethod>& prototype);
2728
2729mirror::Class* ClassLinker::CreateProxyClass(ScopedObjectAccess& soa, jstring name,
2730                                             jobjectArray interfaces, jobject loader,
2731                                             jobjectArray methods, jobjectArray throws) {
2732  Thread* self = soa.Self();
2733  SirtRef<mirror::Class> klass(self, AllocClass(self, GetClassRoot(kJavaLangClass),
2734                                                sizeof(mirror::SynthesizedProxyClass)));
2735  if (klass.get() == NULL) {
2736    CHECK(self->IsExceptionPending());  // OOME.
2737    return NULL;
2738  }
2739  DCHECK(klass->GetClass() != NULL);
2740  klass->SetObjectSize(sizeof(mirror::Proxy));
2741  klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
2742  klass->SetClassLoader(soa.Decode<mirror::ClassLoader*>(loader));
2743  DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
2744  klass->SetName(soa.Decode<mirror::String*>(name));
2745  mirror::Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
2746  klass->SetDexCache(proxy_class->GetDexCache());
2747  klass->SetStatus(mirror::Class::kStatusIdx, self);
2748
2749  // Instance fields are inherited, but we add a couple of static fields...
2750  {
2751    mirror::ObjectArray<mirror::ArtField>* sfields = AllocArtFieldArray(self, 2);
2752    if (UNLIKELY(sfields == NULL)) {
2753      CHECK(self->IsExceptionPending());  // OOME.
2754      return NULL;
2755    }
2756    klass->SetSFields(sfields);
2757  }
2758  // 1. Create a static field 'interfaces' that holds the _declared_ interfaces implemented by
2759  // our proxy, so Class.getInterfaces doesn't return the flattened set.
2760  SirtRef<mirror::ArtField> interfaces_sfield(self, AllocArtField(self));
2761  if (UNLIKELY(interfaces_sfield.get() == NULL)) {
2762    CHECK(self->IsExceptionPending());  // OOME.
2763    return NULL;
2764  }
2765  klass->SetStaticField(0, interfaces_sfield.get());
2766  interfaces_sfield->SetDexFieldIndex(0);
2767  interfaces_sfield->SetDeclaringClass(klass.get());
2768  interfaces_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2769  // 2. Create a static field 'throws' that holds exceptions thrown by our methods.
2770  SirtRef<mirror::ArtField> throws_sfield(self, AllocArtField(self));
2771  if (UNLIKELY(throws_sfield.get() == NULL)) {
2772    CHECK(self->IsExceptionPending());  // OOME.
2773    return NULL;
2774  }
2775  klass->SetStaticField(1, throws_sfield.get());
2776  throws_sfield->SetDexFieldIndex(1);
2777  throws_sfield->SetDeclaringClass(klass.get());
2778  throws_sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
2779
2780  // Proxies have 1 direct method, the constructor
2781  {
2782    mirror::ObjectArray<mirror::ArtMethod>* directs = AllocArtMethodArray(self, 1);
2783    if (UNLIKELY(directs == NULL)) {
2784      CHECK(self->IsExceptionPending());  // OOME.
2785      return NULL;
2786    }
2787    klass->SetDirectMethods(directs);
2788    mirror::ArtMethod* constructor = CreateProxyConstructor(self, klass, proxy_class);
2789    if (UNLIKELY(constructor == NULL)) {
2790      CHECK(self->IsExceptionPending());  // OOME.
2791      return NULL;
2792    }
2793    klass->SetDirectMethod(0, constructor);
2794  }
2795
2796  // Create virtual method using specified prototypes.
2797  size_t num_virtual_methods =
2798      soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods)->GetLength();
2799  {
2800    mirror::ObjectArray<mirror::ArtMethod>* virtuals = AllocArtMethodArray(self, num_virtual_methods);
2801    if (UNLIKELY(virtuals == NULL)) {
2802      CHECK(self->IsExceptionPending());  // OOME.
2803      return NULL;
2804    }
2805    klass->SetVirtualMethods(virtuals);
2806  }
2807  for (size_t i = 0; i < num_virtual_methods; ++i) {
2808    mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
2809        soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
2810    SirtRef<mirror::ArtMethod> prototype(self, decoded_methods->Get(i));
2811    mirror::ArtMethod* clone = CreateProxyMethod(self, klass, prototype);
2812    if (UNLIKELY(clone == NULL)) {
2813      CHECK(self->IsExceptionPending());  // OOME.
2814      return NULL;
2815    }
2816    klass->SetVirtualMethod(i, clone);
2817  }
2818
2819  klass->SetSuperClass(proxy_class);  // The super class is java.lang.reflect.Proxy
2820  klass->SetStatus(mirror::Class::kStatusLoaded, self);  // Class is now effectively in the loaded state
2821  self->AssertNoPendingException();
2822
2823  {
2824    ObjectLock<mirror::Class> lock(self, &klass);  // Must hold lock on object when resolved.
2825    // Link the fields and virtual methods, creating vtable and iftables
2826    SirtRef<mirror::ObjectArray<mirror::Class> > sirt_interfaces(
2827        self, soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
2828    if (!LinkClass(self, klass, sirt_interfaces)) {
2829      klass->SetStatus(mirror::Class::kStatusError, self);
2830      return nullptr;
2831    }
2832
2833    interfaces_sfield->SetObject(klass.get(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
2834    throws_sfield->SetObject(klass.get(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
2835    klass->SetStatus(mirror::Class::kStatusInitialized, self);
2836  }
2837
2838  // sanity checks
2839  if (kIsDebugBuild) {
2840    CHECK(klass->GetIFields() == NULL);
2841    CheckProxyConstructor(klass->GetDirectMethod(0));
2842    for (size_t i = 0; i < num_virtual_methods; ++i) {
2843      mirror::ObjectArray<mirror::ArtMethod>* decoded_methods =
2844          soa.Decode<mirror::ObjectArray<mirror::ArtMethod>*>(methods);
2845      SirtRef<mirror::ArtMethod> prototype(self, decoded_methods->Get(i));
2846      CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2847    }
2848
2849    mirror::String* decoded_name = soa.Decode<mirror::String*>(name);
2850    std::string interfaces_field_name(StringPrintf("java.lang.Class[] %s.interfaces",
2851                                                   decoded_name->ToModifiedUtf8().c_str()));
2852    CHECK_EQ(PrettyField(klass->GetStaticField(0)), interfaces_field_name);
2853
2854    std::string throws_field_name(StringPrintf("java.lang.Class[][] %s.throws",
2855                                               decoded_name->ToModifiedUtf8().c_str()));
2856    CHECK_EQ(PrettyField(klass->GetStaticField(1)), throws_field_name);
2857
2858    mirror::SynthesizedProxyClass* synth_proxy_class =
2859        down_cast<mirror::SynthesizedProxyClass*>(klass.get());
2860    CHECK_EQ(synth_proxy_class->GetInterfaces(), soa.Decode<mirror::ObjectArray<mirror::Class>*>(interfaces));
2861    CHECK_EQ(synth_proxy_class->GetThrows(), soa.Decode<mirror::ObjectArray<mirror::ObjectArray<mirror::Class> >*>(throws));
2862  }
2863  std::string descriptor(GetDescriptorForProxy(klass.get()));
2864  mirror::Class* existing = InsertClass(descriptor.c_str(), klass.get(), Hash(descriptor.c_str()));
2865  CHECK(existing == nullptr);
2866  return klass.get();
2867}
2868
2869std::string ClassLinker::GetDescriptorForProxy(mirror::Class* proxy_class) {
2870  DCHECK(proxy_class->IsProxyClass());
2871  mirror::String* name = proxy_class->GetName();
2872  DCHECK(name != NULL);
2873  return DotToDescriptor(name->ToModifiedUtf8().c_str());
2874}
2875
2876mirror::ArtMethod* ClassLinker::FindMethodForProxy(mirror::Class* proxy_class,
2877                                                   mirror::ArtMethod* proxy_method) {
2878  DCHECK(proxy_class->IsProxyClass());
2879  DCHECK(proxy_method->IsProxyMethod());
2880  // Locate the dex cache of the original interface/Object
2881  mirror::DexCache* dex_cache = NULL;
2882  {
2883    mirror::ObjectArray<mirror::Class>* resolved_types = proxy_method->GetDexCacheResolvedTypes();
2884    ReaderMutexLock mu(Thread::Current(), dex_lock_);
2885    for (size_t i = 0; i != dex_caches_.size(); ++i) {
2886      if (dex_caches_[i]->GetResolvedTypes() == resolved_types) {
2887        dex_cache = dex_caches_[i];
2888        break;
2889      }
2890    }
2891  }
2892  CHECK(dex_cache != NULL);
2893  uint32_t method_idx = proxy_method->GetDexMethodIndex();
2894  mirror::ArtMethod* resolved_method = dex_cache->GetResolvedMethod(method_idx);
2895  CHECK(resolved_method != NULL);
2896  return resolved_method;
2897}
2898
2899
2900mirror::ArtMethod* ClassLinker::CreateProxyConstructor(Thread* self,
2901                                                       const SirtRef<mirror::Class>& klass,
2902                                                       mirror::Class* proxy_class) {
2903  // Create constructor for Proxy that must initialize h
2904  mirror::ObjectArray<mirror::ArtMethod>* proxy_direct_methods =
2905      proxy_class->GetDirectMethods();
2906  CHECK_EQ(proxy_direct_methods->GetLength(), 16);
2907  mirror::ArtMethod* proxy_constructor = proxy_direct_methods->Get(2);
2908  // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2909  // code_ too)
2910  mirror::ArtMethod* constructor =
2911      down_cast<mirror::ArtMethod*>(proxy_constructor->Clone(self));
2912  if (constructor == NULL) {
2913    CHECK(self->IsExceptionPending());  // OOME.
2914    return NULL;
2915  }
2916  // Make this constructor public and fix the class to be our Proxy version
2917  constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
2918  constructor->SetDeclaringClass(klass.get());
2919  return constructor;
2920}
2921
2922static void CheckProxyConstructor(mirror::ArtMethod* constructor)
2923    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2924  CHECK(constructor->IsConstructor());
2925  MethodHelper mh(constructor);
2926  CHECK_STREQ(mh.GetName(), "<init>");
2927  CHECK_STREQ(mh.GetSignature().ToString().c_str(), "(Ljava/lang/reflect/InvocationHandler;)V");
2928  DCHECK(constructor->IsPublic());
2929}
2930
2931mirror::ArtMethod* ClassLinker::CreateProxyMethod(Thread* self,
2932                                                  const SirtRef<mirror::Class>& klass,
2933                                                  const SirtRef<mirror::ArtMethod>& prototype) {
2934  // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2935  // prototype method
2936  prototype->GetDeclaringClass()->GetDexCache()->SetResolvedMethod(prototype->GetDexMethodIndex(),
2937                                                                   prototype.get());
2938  // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
2939  // as necessary
2940  mirror::ArtMethod* method = down_cast<mirror::ArtMethod*>(prototype->Clone(self));
2941  if (UNLIKELY(method == NULL)) {
2942    CHECK(self->IsExceptionPending());  // OOME.
2943    return NULL;
2944  }
2945
2946  // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2947  // the intersection of throw exceptions as defined in Proxy
2948  method->SetDeclaringClass(klass.get());
2949  method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
2950
2951  // At runtime the method looks like a reference and argument saving method, clone the code
2952  // related parameters from this method.
2953  mirror::ArtMethod* refs_and_args =
2954      Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2955  method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2956  method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2957  method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2958  method->SetEntryPointFromQuickCompiledCode(GetQuickProxyInvokeHandler());
2959  method->SetEntryPointFromPortableCompiledCode(GetPortableProxyInvokeHandler());
2960  method->SetEntryPointFromInterpreter(artInterpreterToCompiledCodeBridge);
2961
2962  return method;
2963}
2964
2965static void CheckProxyMethod(mirror::ArtMethod* method,
2966                             SirtRef<mirror::ArtMethod>& prototype)
2967    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2968  // Basic sanity
2969  CHECK(!prototype->IsFinal());
2970  CHECK(method->IsFinal());
2971  CHECK(!method->IsAbstract());
2972
2973  // The proxy method doesn't have its own dex cache or dex file and so it steals those of its
2974  // interface prototype. The exception to this are Constructors and the Class of the Proxy itself.
2975  CHECK_EQ(prototype->GetDexCacheStrings(), method->GetDexCacheStrings());
2976  CHECK_EQ(prototype->GetDexCacheResolvedMethods(), method->GetDexCacheResolvedMethods());
2977  CHECK_EQ(prototype->GetDexCacheResolvedTypes(), method->GetDexCacheResolvedTypes());
2978  CHECK_EQ(prototype->GetDexMethodIndex(), method->GetDexMethodIndex());
2979
2980  MethodHelper mh(method);
2981  MethodHelper mh2(prototype.get());
2982  CHECK_STREQ(mh.GetName(), mh2.GetName());
2983  CHECK_STREQ(mh.GetShorty(), mh2.GetShorty());
2984  // More complex sanity - via dex cache
2985  CHECK_EQ(mh.GetReturnType(), mh2.GetReturnType());
2986}
2987
2988static bool CanWeInitializeClass(mirror::Class* klass, bool can_init_statics,
2989                                 bool can_init_parents)
2990    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
2991  if (can_init_statics && can_init_parents) {
2992    return true;
2993  }
2994  if (!can_init_statics) {
2995    // Check if there's a class initializer.
2996    mirror::ArtMethod* clinit = klass->FindClassInitializer();
2997    if (clinit != NULL) {
2998      return false;
2999    }
3000    // Check if there are encoded static values needing initialization.
3001    if (klass->NumStaticFields() != 0) {
3002      ClassHelper kh(klass);
3003      const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
3004      DCHECK(dex_class_def != NULL);
3005      if (dex_class_def->static_values_off_ != 0) {
3006        return false;
3007      }
3008    }
3009  }
3010  if (!klass->IsInterface() && klass->HasSuperClass()) {
3011    mirror::Class* super_class = klass->GetSuperClass();
3012    if (!can_init_parents && !super_class->IsInitialized()) {
3013      return false;
3014    } else {
3015      if (!CanWeInitializeClass(super_class, can_init_statics, can_init_parents)) {
3016        return false;
3017      }
3018    }
3019  }
3020  return true;
3021}
3022
3023bool ClassLinker::IsInitialized() const {
3024  return init_done_;
3025}
3026
3027bool ClassLinker::InitializeClass(const SirtRef<mirror::Class>& klass, bool can_init_statics,
3028                                  bool can_init_parents) {
3029  // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
3030
3031  // Are we already initialized and therefore done?
3032  // Note: we differ from the JLS here as we don't do this under the lock, this is benign as
3033  // an initialized class will never change its state.
3034  if (klass->IsInitialized()) {
3035    return true;
3036  }
3037
3038  // Fast fail if initialization requires a full runtime. Not part of the JLS.
3039  if (!CanWeInitializeClass(klass.get(), can_init_statics, can_init_parents)) {
3040    return false;
3041  }
3042
3043  Thread* self = Thread::Current();
3044  uint64_t t0;
3045  {
3046    ObjectLock<mirror::Class> lock(self, &klass);
3047
3048    // Re-check under the lock in case another thread initialized ahead of us.
3049    if (klass->IsInitialized()) {
3050      return true;
3051    }
3052
3053    // Was the class already found to be erroneous? Done under the lock to match the JLS.
3054    if (klass->IsErroneous()) {
3055      ThrowEarlierClassFailure(klass.get());
3056      return false;
3057    }
3058
3059    CHECK(klass->IsResolved()) << PrettyClass(klass.get()) << ": state=" << klass->GetStatus();
3060
3061    if (!klass->IsVerified()) {
3062      VerifyClass(klass);
3063      if (!klass->IsVerified()) {
3064        // We failed to verify, expect either the klass to be erroneous or verification failed at
3065        // compile time.
3066        if (klass->IsErroneous()) {
3067          CHECK(self->IsExceptionPending());
3068        } else {
3069          CHECK(Runtime::Current()->IsCompiler());
3070          CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusRetryVerificationAtRuntime);
3071        }
3072        return false;
3073      }
3074    }
3075
3076    // If the class is kStatusInitializing, either this thread is
3077    // initializing higher up the stack or another thread has beat us
3078    // to initializing and we need to wait. Either way, this
3079    // invocation of InitializeClass will not be responsible for
3080    // running <clinit> and will return.
3081    if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
3082      // We caught somebody else in the act; was it us?
3083      if (klass->GetClinitThreadId() == self->GetTid()) {
3084        // Yes. That's fine. Return so we can continue initializing.
3085        return true;
3086      }
3087      // No. That's fine. Wait for another thread to finish initializing.
3088      return WaitForInitializeClass(klass, self, lock);
3089    }
3090
3091    if (!ValidateSuperClassDescriptors(klass)) {
3092      klass->SetStatus(mirror::Class::kStatusError, self);
3093      return false;
3094    }
3095
3096    CHECK_EQ(klass->GetStatus(), mirror::Class::kStatusVerified) << PrettyClass(klass.get());
3097
3098    // From here out other threads may observe that we're initializing and so changes of state
3099    // require the a notification.
3100    klass->SetClinitThreadId(self->GetTid());
3101    klass->SetStatus(mirror::Class::kStatusInitializing, self);
3102
3103    t0 = NanoTime();
3104  }
3105
3106  // Initialize super classes, must be done while initializing for the JLS.
3107  if (!klass->IsInterface() && klass->HasSuperClass()) {
3108    mirror::Class* super_class = klass->GetSuperClass();
3109    if (!super_class->IsInitialized()) {
3110      CHECK(!super_class->IsInterface());
3111      CHECK(can_init_parents);
3112      SirtRef<mirror::Class> sirt_super(self, super_class);
3113      bool super_initialized = InitializeClass(sirt_super, can_init_statics, true);
3114      if (!super_initialized) {
3115        // The super class was verified ahead of entering initializing, we should only be here if
3116        // the super class became erroneous due to initialization.
3117        CHECK(sirt_super->IsErroneous() && self->IsExceptionPending())
3118            << "Super class initialization failed for " << PrettyDescriptor(sirt_super.get())
3119            << " that has unexpected status " << sirt_super->GetStatus()
3120            << "\nPending exception:\n"
3121            << (self->GetException(NULL) != NULL ? self->GetException(NULL)->Dump() : "");
3122        ObjectLock<mirror::Class> lock(self, &klass);
3123        // Initialization failed because the super-class is erroneous.
3124        klass->SetStatus(mirror::Class::kStatusError, self);
3125        return false;
3126      }
3127    }
3128  }
3129
3130  if (klass->NumStaticFields() > 0) {
3131    ClassHelper kh(klass.get());
3132    const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
3133    CHECK(dex_class_def != NULL);
3134    const DexFile& dex_file = kh.GetDexFile();
3135    SirtRef<mirror::ClassLoader> class_loader(self, klass->GetClassLoader());
3136    SirtRef<mirror::DexCache> dex_cache(self, kh.GetDexCache());
3137    EncodedStaticFieldValueIterator it(dex_file, &dex_cache, &class_loader,
3138                                       this, *dex_class_def);
3139    if (it.HasNext()) {
3140      CHECK(can_init_statics);
3141      // We reordered the fields, so we need to be able to map the field indexes to the right fields.
3142      SafeMap<uint32_t, mirror::ArtField*> field_map;
3143      ConstructFieldMap(dex_file, *dex_class_def, klass.get(), field_map);
3144      for (size_t i = 0; it.HasNext(); i++, it.Next()) {
3145        it.ReadValueToField(field_map.Get(i));
3146      }
3147    }
3148  }
3149
3150  mirror::ArtMethod* clinit = klass->FindClassInitializer();
3151  if (clinit != NULL) {
3152    CHECK(can_init_statics);
3153    if (LIKELY(Runtime::Current()->IsStarted())) {
3154      JValue result;
3155      clinit->Invoke(self, NULL, 0, &result, "V");
3156    } else {
3157      art::interpreter::EnterInterpreterFromInvoke(self, clinit, NULL, NULL, NULL);
3158    }
3159  }
3160
3161  // Opportunistically set static method trampolines to their destination.
3162  FixupStaticTrampolines(klass.get());
3163
3164  uint64_t t1 = NanoTime();
3165
3166  bool success = true;
3167  {
3168    ObjectLock<mirror::Class> lock(self, &klass);
3169
3170    if (self->IsExceptionPending()) {
3171      WrapExceptionInInitializer();
3172      klass->SetStatus(mirror::Class::kStatusError, self);
3173      success = false;
3174    } else {
3175      RuntimeStats* global_stats = Runtime::Current()->GetStats();
3176      RuntimeStats* thread_stats = self->GetStats();
3177      ++global_stats->class_init_count;
3178      ++thread_stats->class_init_count;
3179      global_stats->class_init_time_ns += (t1 - t0);
3180      thread_stats->class_init_time_ns += (t1 - t0);
3181      // Set the class as initialized except if failed to initialize static fields.
3182      klass->SetStatus(mirror::Class::kStatusInitialized, self);
3183      if (VLOG_IS_ON(class_linker)) {
3184        ClassHelper kh(klass.get());
3185        LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
3186      }
3187    }
3188  }
3189  return success;
3190}
3191
3192bool ClassLinker::WaitForInitializeClass(const SirtRef<mirror::Class>& klass, Thread* self,
3193                                         ObjectLock<mirror::Class>& lock)
3194    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3195  while (true) {
3196    self->AssertNoPendingException();
3197    CHECK(!klass->IsInitialized());
3198    lock.WaitIgnoringInterrupts();
3199
3200    // When we wake up, repeat the test for init-in-progress.  If
3201    // there's an exception pending (only possible if
3202    // "interruptShouldThrow" was set), bail out.
3203    if (self->IsExceptionPending()) {
3204      WrapExceptionInInitializer();
3205      klass->SetStatus(mirror::Class::kStatusError, self);
3206      return false;
3207    }
3208    // Spurious wakeup? Go back to waiting.
3209    if (klass->GetStatus() == mirror::Class::kStatusInitializing) {
3210      continue;
3211    }
3212    if (klass->GetStatus() == mirror::Class::kStatusVerified && Runtime::Current()->IsCompiler()) {
3213      // Compile time initialization failed.
3214      return false;
3215    }
3216    if (klass->IsErroneous()) {
3217      // The caller wants an exception, but it was thrown in a
3218      // different thread.  Synthesize one here.
3219      ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
3220                                PrettyDescriptor(klass.get()).c_str());
3221      return false;
3222    }
3223    if (klass->IsInitialized()) {
3224      return true;
3225    }
3226    LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass.get()) << " is "
3227        << klass->GetStatus();
3228  }
3229  LOG(FATAL) << "Not Reached" << PrettyClass(klass.get());
3230}
3231
3232bool ClassLinker::ValidateSuperClassDescriptors(const SirtRef<mirror::Class>& klass) {
3233  if (klass->IsInterface()) {
3234    return true;
3235  }
3236  Thread* self = Thread::Current();
3237  // begin with the methods local to the superclass
3238  if (klass->HasSuperClass() &&
3239      klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
3240    SirtRef<mirror::Class> super(self, klass->GetSuperClass());
3241    for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
3242      mirror::ArtMethod* method = klass->GetVTable()->Get(i);
3243      if (method != super->GetVTable()->Get(i) &&
3244          !IsSameMethodSignatureInDifferentClassContexts(method, super.get(), klass.get())) {
3245        ThrowLinkageError(klass.get(), "Class %s method %s resolves differently in superclass %s",
3246                          PrettyDescriptor(klass.get()).c_str(), PrettyMethod(method).c_str(),
3247                          PrettyDescriptor(super.get()).c_str());
3248        return false;
3249      }
3250    }
3251  }
3252  for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
3253    SirtRef<mirror::Class> interface(self, klass->GetIfTable()->GetInterface(i));
3254    if (klass->GetClassLoader() != interface->GetClassLoader()) {
3255      for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
3256        mirror::ArtMethod* method = klass->GetIfTable()->GetMethodArray(i)->Get(j);
3257        if (!IsSameMethodSignatureInDifferentClassContexts(method, interface.get(),
3258                                                           method->GetDeclaringClass())) {
3259          ThrowLinkageError(klass.get(), "Class %s method %s resolves differently in interface %s",
3260                            PrettyDescriptor(method->GetDeclaringClass()).c_str(),
3261                            PrettyMethod(method).c_str(),
3262                            PrettyDescriptor(interface.get()).c_str());
3263          return false;
3264        }
3265      }
3266    }
3267  }
3268  return true;
3269}
3270
3271// Returns true if classes referenced by the signature of the method are the
3272// same classes in klass1 as they are in klass2.
3273bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(mirror::ArtMethod* method,
3274                                                                mirror::Class* klass1,
3275                                                                mirror::Class* klass2) {
3276  if (klass1 == klass2) {
3277    return true;
3278  }
3279  Thread* self = Thread::Current();
3280  CHECK(klass1 != nullptr);
3281  CHECK(klass2 != nullptr);
3282  SirtRef<mirror::ClassLoader> loader1(self, klass1->GetClassLoader());
3283  SirtRef<mirror::ClassLoader> loader2(self, klass2->GetClassLoader());
3284  const DexFile& dex_file = *method->GetDeclaringClass()->GetDexCache()->GetDexFile();
3285  const DexFile::ProtoId& proto_id =
3286      dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
3287  for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
3288    const char* descriptor = it.GetDescriptor();
3289    if (descriptor == nullptr) {
3290      break;
3291    }
3292    if (descriptor[0] == 'L' || descriptor[0] == '[') {
3293      // Found a non-primitive type.
3294      if (!IsSameDescriptorInDifferentClassContexts(descriptor, loader1, loader2)) {
3295        return false;
3296      }
3297    }
3298  }
3299  // Check the return type
3300  const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
3301  if (descriptor[0] == 'L' || descriptor[0] == '[') {
3302    if (!IsSameDescriptorInDifferentClassContexts(descriptor, loader1, loader2)) {
3303      return false;
3304    }
3305  }
3306  return true;
3307}
3308
3309// Returns true if the descriptor resolves to the same class in the context of loader1 and loader2.
3310bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
3311                                                           SirtRef<mirror::ClassLoader>& loader1,
3312                                                           SirtRef<mirror::ClassLoader>& loader2) {
3313  CHECK(descriptor != nullptr);
3314  Thread* self = Thread::Current();
3315  SirtRef<mirror::Class> found1(self, FindClass(descriptor, loader1));
3316  if (found1.get() == nullptr) {
3317    self->ClearException();
3318  }
3319  mirror::Class* found2 = FindClass(descriptor, loader2);
3320  if (found2 == nullptr) {
3321    self->ClearException();
3322  }
3323  return found1.get() == found2;
3324}
3325
3326bool ClassLinker::EnsureInitialized(const SirtRef<mirror::Class>& c, bool can_init_fields,
3327                                    bool can_init_parents) {
3328  DCHECK(c.get() != NULL);
3329  if (c->IsInitialized()) {
3330    return true;
3331  }
3332
3333  bool success = InitializeClass(c, can_init_fields, can_init_parents);
3334  if (!success) {
3335    if (can_init_fields && can_init_parents) {
3336      CHECK(Thread::Current()->IsExceptionPending()) << PrettyClass(c.get());
3337    }
3338  }
3339  return success;
3340}
3341
3342void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
3343                                    mirror::Class* c,
3344                                    SafeMap<uint32_t, mirror::ArtField*>& field_map) {
3345  const byte* class_data = dex_file.GetClassData(dex_class_def);
3346  ClassDataItemIterator it(dex_file, class_data);
3347  Thread* self = Thread::Current();
3348  SirtRef<mirror::DexCache> dex_cache(self, c->GetDexCache());
3349  SirtRef<mirror::ClassLoader> class_loader(self, c->GetClassLoader());
3350  CHECK(!kMovingFields);
3351  for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
3352    field_map.Put(i, ResolveField(dex_file, it.GetMemberIndex(), dex_cache, class_loader, true));
3353  }
3354}
3355
3356bool ClassLinker::LinkClass(Thread* self, const SirtRef<mirror::Class>& klass,
3357                            const SirtRef<mirror::ObjectArray<mirror::Class> >& interfaces) {
3358  CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
3359  if (!LinkSuperClass(klass)) {
3360    return false;
3361  }
3362  if (!LinkMethods(klass, interfaces)) {
3363    return false;
3364  }
3365  if (!LinkInstanceFields(klass)) {
3366    return false;
3367  }
3368  if (!LinkStaticFields(klass)) {
3369    return false;
3370  }
3371  CreateReferenceInstanceOffsets(klass);
3372  CreateReferenceStaticOffsets(klass);
3373  CHECK_EQ(mirror::Class::kStatusLoaded, klass->GetStatus());
3374  klass->SetStatus(mirror::Class::kStatusResolved, self);
3375  return true;
3376}
3377
3378bool ClassLinker::LoadSuperAndInterfaces(const SirtRef<mirror::Class>& klass,
3379                                         const DexFile& dex_file) {
3380  CHECK_EQ(mirror::Class::kStatusIdx, klass->GetStatus());
3381  const DexFile::ClassDef& class_def = dex_file.GetClassDef(klass->GetDexClassDefIndex());
3382  uint16_t super_class_idx = class_def.superclass_idx_;
3383  if (super_class_idx != DexFile::kDexNoIndex16) {
3384    mirror::Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
3385    if (super_class == NULL) {
3386      DCHECK(Thread::Current()->IsExceptionPending());
3387      return false;
3388    }
3389    // Verify
3390    if (!klass->CanAccess(super_class)) {
3391      ThrowIllegalAccessError(klass.get(), "Class %s extended by class %s is inaccessible",
3392                              PrettyDescriptor(super_class).c_str(),
3393                              PrettyDescriptor(klass.get()).c_str());
3394      return false;
3395    }
3396    klass->SetSuperClass(super_class);
3397  }
3398  const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(class_def);
3399  if (interfaces != NULL) {
3400    for (size_t i = 0; i < interfaces->Size(); i++) {
3401      uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
3402      mirror::Class* interface = ResolveType(dex_file, idx, klass.get());
3403      if (interface == NULL) {
3404        DCHECK(Thread::Current()->IsExceptionPending());
3405        return false;
3406      }
3407      // Verify
3408      if (!klass->CanAccess(interface)) {
3409        // TODO: the RI seemed to ignore this in my testing.
3410        ThrowIllegalAccessError(klass.get(), "Interface %s implemented by class %s is inaccessible",
3411                                PrettyDescriptor(interface).c_str(),
3412                                PrettyDescriptor(klass.get()).c_str());
3413        return false;
3414      }
3415    }
3416  }
3417  // Mark the class as loaded.
3418  klass->SetStatus(mirror::Class::kStatusLoaded, NULL);
3419  return true;
3420}
3421
3422bool ClassLinker::LinkSuperClass(const SirtRef<mirror::Class>& klass) {
3423  CHECK(!klass->IsPrimitive());
3424  mirror::Class* super = klass->GetSuperClass();
3425  if (klass.get() == GetClassRoot(kJavaLangObject)) {
3426    if (super != NULL) {
3427      ThrowClassFormatError(klass.get(), "java.lang.Object must not have a superclass");
3428      return false;
3429    }
3430    return true;
3431  }
3432  if (super == NULL) {
3433    ThrowLinkageError(klass.get(), "No superclass defined for class %s",
3434                      PrettyDescriptor(klass.get()).c_str());
3435    return false;
3436  }
3437  // Verify
3438  if (super->IsFinal() || super->IsInterface()) {
3439    ThrowIncompatibleClassChangeError(klass.get(), "Superclass %s of %s is %s",
3440                                      PrettyDescriptor(super).c_str(),
3441                                      PrettyDescriptor(klass.get()).c_str(),
3442                                      super->IsFinal() ? "declared final" : "an interface");
3443    return false;
3444  }
3445  if (!klass->CanAccess(super)) {
3446    ThrowIllegalAccessError(klass.get(), "Superclass %s is inaccessible to class %s",
3447                            PrettyDescriptor(super).c_str(),
3448                            PrettyDescriptor(klass.get()).c_str());
3449    return false;
3450  }
3451
3452  // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
3453  if (super->IsFinalizable()) {
3454    klass->SetFinalizable();
3455  }
3456
3457  // Inherit reference flags (if any) from the superclass.
3458  int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
3459  if (reference_flags != 0) {
3460    klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
3461  }
3462  // Disallow custom direct subclasses of java.lang.ref.Reference.
3463  if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
3464    ThrowLinkageError(klass.get(),
3465                      "Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
3466                      PrettyDescriptor(klass.get()).c_str());
3467    return false;
3468  }
3469
3470  if (kIsDebugBuild) {
3471    // Ensure super classes are fully resolved prior to resolving fields..
3472    while (super != NULL) {
3473      CHECK(super->IsResolved());
3474      super = super->GetSuperClass();
3475    }
3476  }
3477  return true;
3478}
3479
3480// Populate the class vtable and itable. Compute return type indices.
3481bool ClassLinker::LinkMethods(const SirtRef<mirror::Class>& klass,
3482                              const SirtRef<mirror::ObjectArray<mirror::Class> >& interfaces) {
3483  if (klass->IsInterface()) {
3484    // No vtable.
3485    size_t count = klass->NumVirtualMethods();
3486    if (!IsUint(16, count)) {
3487      ThrowClassFormatError(klass.get(), "Too many methods on interface: %zd", count);
3488      return false;
3489    }
3490    for (size_t i = 0; i < count; ++i) {
3491      klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
3492    }
3493    // Link interface method tables
3494    return LinkInterfaceMethods(klass, interfaces);
3495  } else {
3496    // Link virtual and interface method tables
3497    return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
3498  }
3499  return true;
3500}
3501
3502bool ClassLinker::LinkVirtualMethods(const SirtRef<mirror::Class>& klass) {
3503  Thread* self = Thread::Current();
3504  if (klass->HasSuperClass()) {
3505    uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
3506    size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
3507    CHECK_LE(actual_count, max_count);
3508    // TODO: do not assign to the vtable field until it is fully constructed.
3509    SirtRef<mirror::ObjectArray<mirror::ArtMethod> >
3510      vtable(self, klass->GetSuperClass()->GetVTable()->CopyOf(self, max_count));
3511    if (UNLIKELY(vtable.get() == NULL)) {
3512      CHECK(self->IsExceptionPending());  // OOME.
3513      return false;
3514    }
3515    // See if any of our virtual methods override the superclass.
3516    for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
3517      mirror::ArtMethod* local_method = klass->GetVirtualMethodDuringLinking(i);
3518      MethodHelper local_mh(local_method);
3519      size_t j = 0;
3520      for (; j < actual_count; ++j) {
3521        mirror::ArtMethod* super_method = vtable->Get(j);
3522        MethodHelper super_mh(super_method);
3523        if (local_mh.HasSameNameAndSignature(&super_mh)) {
3524          if (klass->CanAccessMember(super_method->GetDeclaringClass(), super_method->GetAccessFlags())) {
3525            if (super_method->IsFinal()) {
3526              ThrowLinkageError(klass.get(), "Method %s overrides final method in class %s",
3527                                PrettyMethod(local_method).c_str(),
3528                                super_mh.GetDeclaringClassDescriptor());
3529              return false;
3530            }
3531            vtable->Set(j, local_method);
3532            local_method->SetMethodIndex(j);
3533            break;
3534          } else {
3535            LOG(WARNING) << "Before Android 4.1, method " << PrettyMethod(local_method)
3536                         << " would have incorrectly overridden the package-private method in "
3537                         << PrettyDescriptor(super_mh.GetDeclaringClassDescriptor());
3538          }
3539        }
3540      }
3541      if (j == actual_count) {
3542        // Not overriding, append.
3543        vtable->Set(actual_count, local_method);
3544        local_method->SetMethodIndex(actual_count);
3545        actual_count += 1;
3546      }
3547    }
3548    if (!IsUint(16, actual_count)) {
3549      ThrowClassFormatError(klass.get(), "Too many methods defined on class: %zd", actual_count);
3550      return false;
3551    }
3552    // Shrink vtable if possible
3553    CHECK_LE(actual_count, max_count);
3554    if (actual_count < max_count) {
3555      vtable.reset(vtable->CopyOf(self, actual_count));
3556      if (UNLIKELY(vtable.get() == NULL)) {
3557        CHECK(self->IsExceptionPending());  // OOME.
3558        return false;
3559      }
3560    }
3561    klass->SetVTable(vtable.get());
3562  } else {
3563    CHECK(klass.get() == GetClassRoot(kJavaLangObject));
3564    uint32_t num_virtual_methods = klass->NumVirtualMethods();
3565    if (!IsUint(16, num_virtual_methods)) {
3566      ThrowClassFormatError(klass.get(), "Too many methods: %d", num_virtual_methods);
3567      return false;
3568    }
3569    SirtRef<mirror::ObjectArray<mirror::ArtMethod> >
3570        vtable(self, AllocArtMethodArray(self, num_virtual_methods));
3571    if (UNLIKELY(vtable.get() == NULL)) {
3572      CHECK(self->IsExceptionPending());  // OOME.
3573      return false;
3574    }
3575    for (size_t i = 0; i < num_virtual_methods; ++i) {
3576      mirror::ArtMethod* virtual_method = klass->GetVirtualMethodDuringLinking(i);
3577      vtable->Set(i, virtual_method);
3578      virtual_method->SetMethodIndex(i & 0xFFFF);
3579    }
3580    klass->SetVTable(vtable.get());
3581  }
3582  return true;
3583}
3584
3585bool ClassLinker::LinkInterfaceMethods(const SirtRef<mirror::Class>& klass,
3586                                       const SirtRef<mirror::ObjectArray<mirror::Class> >& interfaces) {
3587  // Set the imt table to be all conflicts by default.
3588  klass->SetImTable(Runtime::Current()->GetDefaultImt());
3589  size_t super_ifcount;
3590  if (klass->HasSuperClass()) {
3591    super_ifcount = klass->GetSuperClass()->GetIfTableCount();
3592  } else {
3593    super_ifcount = 0;
3594  }
3595  size_t ifcount = super_ifcount;
3596  uint32_t num_interfaces;
3597  {
3598    ClassHelper kh(klass.get());
3599    num_interfaces =
3600        interfaces.get() == nullptr ? kh.NumDirectInterfaces() : interfaces->GetLength();
3601    ifcount += num_interfaces;
3602    for (size_t i = 0; i < num_interfaces; i++) {
3603      mirror::Class* interface =
3604          interfaces.get() == nullptr ? kh.GetDirectInterface(i) : interfaces->Get(i);
3605      ifcount += interface->GetIfTableCount();
3606    }
3607  }
3608  if (ifcount == 0) {
3609    // Class implements no interfaces.
3610    DCHECK_EQ(klass->GetIfTableCount(), 0);
3611    DCHECK(klass->GetIfTable() == NULL);
3612    return true;
3613  }
3614  if (ifcount == super_ifcount) {
3615    // Class implements same interfaces as parent, are any of these not marker interfaces?
3616    bool has_non_marker_interface = false;
3617    mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
3618    for (size_t i = 0; i < ifcount; ++i) {
3619      if (super_iftable->GetMethodArrayCount(i) > 0) {
3620        has_non_marker_interface = true;
3621        break;
3622      }
3623    }
3624    if (!has_non_marker_interface) {
3625      // Class just inherits marker interfaces from parent so recycle parent's iftable.
3626      klass->SetIfTable(super_iftable);
3627      return true;
3628    }
3629  }
3630  Thread* self = Thread::Current();
3631  SirtRef<mirror::IfTable> iftable(self, AllocIfTable(self, ifcount));
3632  if (UNLIKELY(iftable.get() == NULL)) {
3633    CHECK(self->IsExceptionPending());  // OOME.
3634    return false;
3635  }
3636  if (super_ifcount != 0) {
3637    mirror::IfTable* super_iftable = klass->GetSuperClass()->GetIfTable();
3638    for (size_t i = 0; i < super_ifcount; i++) {
3639      mirror::Class* super_interface = super_iftable->GetInterface(i);
3640      iftable->SetInterface(i, super_interface);
3641    }
3642  }
3643  // Flatten the interface inheritance hierarchy.
3644  size_t idx = super_ifcount;
3645  for (size_t i = 0; i < num_interfaces; i++) {
3646    ClassHelper kh(klass.get());
3647    mirror::Class* interface =
3648        interfaces.get() == nullptr ? kh.GetDirectInterface(i) : interfaces->Get(i);
3649    DCHECK(interface != NULL);
3650    if (!interface->IsInterface()) {
3651      ClassHelper ih(interface);
3652      ThrowIncompatibleClassChangeError(klass.get(), "Class %s implements non-interface class %s",
3653                                        PrettyDescriptor(klass.get()).c_str(),
3654                                        PrettyDescriptor(ih.GetDescriptor()).c_str());
3655      return false;
3656    }
3657    // Check if interface is already in iftable
3658    bool duplicate = false;
3659    for (size_t j = 0; j < idx; j++) {
3660      mirror::Class* existing_interface = iftable->GetInterface(j);
3661      if (existing_interface == interface) {
3662        duplicate = true;
3663        break;
3664      }
3665    }
3666    if (!duplicate) {
3667      // Add this non-duplicate interface.
3668      iftable->SetInterface(idx++, interface);
3669      // Add this interface's non-duplicate super-interfaces.
3670      for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
3671        mirror::Class* super_interface = interface->GetIfTable()->GetInterface(j);
3672        bool super_duplicate = false;
3673        for (size_t k = 0; k < idx; k++) {
3674          mirror::Class* existing_interface = iftable->GetInterface(k);
3675          if (existing_interface == super_interface) {
3676            super_duplicate = true;
3677            break;
3678          }
3679        }
3680        if (!super_duplicate) {
3681          iftable->SetInterface(idx++, super_interface);
3682        }
3683      }
3684    }
3685  }
3686  // Shrink iftable in case duplicates were found
3687  if (idx < ifcount) {
3688    iftable.reset(down_cast<mirror::IfTable*>(iftable->CopyOf(self, idx * mirror::IfTable::kMax)));
3689    if (UNLIKELY(iftable.get() == NULL)) {
3690      CHECK(self->IsExceptionPending());  // OOME.
3691      return false;
3692    }
3693    ifcount = idx;
3694  } else {
3695    CHECK_EQ(idx, ifcount);
3696  }
3697  klass->SetIfTable(iftable.get());
3698
3699  // If we're an interface, we don't need the vtable pointers, so we're done.
3700  if (klass->IsInterface()) {
3701    return true;
3702  }
3703  // Allocate imtable
3704  bool imtable_changed = false;
3705  SirtRef<mirror::ObjectArray<mirror::ArtMethod> > imtable(self, AllocArtMethodArray(self, kImtSize));
3706  if (UNLIKELY(imtable.get() == NULL)) {
3707    CHECK(self->IsExceptionPending());  // OOME.
3708    return false;
3709  }
3710  std::vector<mirror::ArtMethod*> miranda_list;
3711  for (size_t i = 0; i < ifcount; ++i) {
3712    size_t num_methods = iftable->GetInterface(i)->NumVirtualMethods();
3713    if (num_methods > 0) {
3714      SirtRef<mirror::ObjectArray<mirror::ArtMethod> >
3715          method_array(self, AllocArtMethodArray(self, num_methods));
3716      if (UNLIKELY(method_array.get() == nullptr)) {
3717        CHECK(self->IsExceptionPending());  // OOME.
3718        return false;
3719      }
3720      iftable->SetMethodArray(i, method_array.get());
3721      SirtRef<mirror::ObjectArray<mirror::ArtMethod> > vtable(self,
3722                                                              klass->GetVTableDuringLinking());
3723      for (size_t j = 0; j < num_methods; ++j) {
3724        mirror::ArtMethod* interface_method = iftable->GetInterface(i)->GetVirtualMethod(j);
3725        MethodHelper interface_mh(interface_method);
3726        int32_t k;
3727        // For each method listed in the interface's method list, find the
3728        // matching method in our class's method list.  We want to favor the
3729        // subclass over the superclass, which just requires walking
3730        // back from the end of the vtable.  (This only matters if the
3731        // superclass defines a private method and this class redefines
3732        // it -- otherwise it would use the same vtable slot.  In .dex files
3733        // those don't end up in the virtual method table, so it shouldn't
3734        // matter which direction we go.  We walk it backward anyway.)
3735        for (k = vtable->GetLength() - 1; k >= 0; --k) {
3736          mirror::ArtMethod* vtable_method = vtable->Get(k);
3737          MethodHelper vtable_mh(vtable_method);
3738          if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
3739            if (!vtable_method->IsAbstract() && !vtable_method->IsPublic()) {
3740              ThrowIllegalAccessError(klass.get(),
3741                                      "Method '%s' implementing interface method '%s' is not public",
3742                                      PrettyMethod(vtable_method).c_str(),
3743                                      PrettyMethod(interface_method).c_str());
3744              return false;
3745            }
3746            method_array->Set(j, vtable_method);
3747            // Place method in imt if entry is empty, place conflict otherwise.
3748            uint32_t imt_index = interface_method->GetDexMethodIndex() % kImtSize;
3749            if (imtable->Get(imt_index) == NULL) {
3750              imtable->Set(imt_index, vtable_method);
3751              imtable_changed = true;
3752            } else {
3753              imtable->Set(imt_index, Runtime::Current()->GetImtConflictMethod());
3754            }
3755            break;
3756          }
3757        }
3758        if (k < 0) {
3759          SirtRef<mirror::ArtMethod> miranda_method(self, NULL);
3760          for (size_t mir = 0; mir < miranda_list.size(); mir++) {
3761            mirror::ArtMethod* mir_method = miranda_list[mir];
3762            MethodHelper vtable_mh(mir_method);
3763            if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
3764              miranda_method.reset(miranda_list[mir]);
3765              break;
3766            }
3767          }
3768          if (miranda_method.get() == NULL) {
3769            // Point the interface table at a phantom slot.
3770            miranda_method.reset(down_cast<mirror::ArtMethod*>(interface_method->Clone(self)));
3771            if (UNLIKELY(miranda_method.get() == NULL)) {
3772              CHECK(self->IsExceptionPending());  // OOME.
3773              return false;
3774            }
3775            // TODO: If a methods move then the miranda_list may hold stale references.
3776            miranda_list.push_back(miranda_method.get());
3777          }
3778          method_array->Set(j, miranda_method.get());
3779        }
3780      }
3781    }
3782  }
3783  if (imtable_changed) {
3784    // Fill in empty entries in interface method table with conflict.
3785    mirror::ArtMethod* imt_conflict_method = Runtime::Current()->GetImtConflictMethod();
3786    for (size_t i = 0; i < kImtSize; i++) {
3787      if (imtable->Get(i) == NULL) {
3788        imtable->Set(i, imt_conflict_method);
3789      }
3790    }
3791    klass->SetImTable(imtable.get());
3792  }
3793  if (!miranda_list.empty()) {
3794    int old_method_count = klass->NumVirtualMethods();
3795    int new_method_count = old_method_count + miranda_list.size();
3796    mirror::ObjectArray<mirror::ArtMethod>* virtuals;
3797    if (old_method_count == 0) {
3798      virtuals = AllocArtMethodArray(self, new_method_count);
3799    } else {
3800      virtuals = klass->GetVirtualMethods()->CopyOf(self, new_method_count);
3801    }
3802    if (UNLIKELY(virtuals == NULL)) {
3803      CHECK(self->IsExceptionPending());  // OOME.
3804      return false;
3805    }
3806    klass->SetVirtualMethods(virtuals);
3807
3808    SirtRef<mirror::ObjectArray<mirror::ArtMethod> >
3809        vtable(self, klass->GetVTableDuringLinking());
3810    CHECK(vtable.get() != NULL);
3811    int old_vtable_count = vtable->GetLength();
3812    int new_vtable_count = old_vtable_count + miranda_list.size();
3813    vtable.reset(vtable->CopyOf(self, new_vtable_count));
3814    if (UNLIKELY(vtable.get() == NULL)) {
3815      CHECK(self->IsExceptionPending());  // OOME.
3816      return false;
3817    }
3818    for (size_t i = 0; i < miranda_list.size(); ++i) {
3819      mirror::ArtMethod* method = miranda_list[i];
3820      // Leave the declaring class alone as type indices are relative to it
3821      method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
3822      method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
3823      klass->SetVirtualMethod(old_method_count + i, method);
3824      vtable->Set(old_vtable_count + i, method);
3825    }
3826    // TODO: do not assign to the vtable field until it is fully constructed.
3827    klass->SetVTable(vtable.get());
3828  }
3829
3830  mirror::ObjectArray<mirror::ArtMethod>* vtable = klass->GetVTableDuringLinking();
3831  for (int i = 0; i < vtable->GetLength(); ++i) {
3832    CHECK(vtable->Get(i) != NULL);
3833  }
3834
3835//  klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
3836
3837  return true;
3838}
3839
3840bool ClassLinker::LinkInstanceFields(const SirtRef<mirror::Class>& klass) {
3841  CHECK(klass.get() != NULL);
3842  return LinkFields(klass, false);
3843}
3844
3845bool ClassLinker::LinkStaticFields(const SirtRef<mirror::Class>& klass) {
3846  CHECK(klass.get() != NULL);
3847  size_t allocated_class_size = klass->GetClassSize();
3848  bool success = LinkFields(klass, true);
3849  CHECK_EQ(allocated_class_size, klass->GetClassSize());
3850  return success;
3851}
3852
3853struct LinkFieldsComparator {
3854  explicit LinkFieldsComparator() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
3855  }
3856  // No thread safety analysis as will be called from STL. Checked lock held in constructor.
3857  bool operator()(mirror::ArtField* field1, mirror::ArtField* field2)
3858      NO_THREAD_SAFETY_ANALYSIS {
3859    // First come reference fields, then 64-bit, and finally 32-bit
3860    FieldHelper fh1(field1);
3861    Primitive::Type type1 = fh1.GetTypeAsPrimitiveType();
3862    FieldHelper fh2(field2);
3863    Primitive::Type type2 = fh2.GetTypeAsPrimitiveType();
3864    if (type1 != type2) {
3865      bool is_primitive1 = type1 != Primitive::kPrimNot;
3866      bool is_primitive2 = type2 != Primitive::kPrimNot;
3867      bool is64bit1 = is_primitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
3868      bool is64bit2 = is_primitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
3869      int order1 = !is_primitive1 ? 0 : (is64bit1 ? 1 : 2);
3870      int order2 = !is_primitive2 ? 0 : (is64bit2 ? 1 : 2);
3871      if (order1 != order2) {
3872        return order1 < order2;
3873      }
3874    }
3875    // same basic group? then sort by string.
3876    const char* name1 = fh1.GetName();
3877    const char* name2 = fh2.GetName();
3878    return strcmp(name1, name2) < 0;
3879  }
3880};
3881
3882bool ClassLinker::LinkFields(const SirtRef<mirror::Class>& klass, bool is_static) {
3883  size_t num_fields =
3884      is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
3885
3886  mirror::ObjectArray<mirror::ArtField>* fields =
3887      is_static ? klass->GetSFields() : klass->GetIFields();
3888
3889  // Initialize size and field_offset
3890  size_t size;
3891  MemberOffset field_offset(0);
3892  if (is_static) {
3893    size = klass->GetClassSize();
3894    field_offset = mirror::Class::FieldsOffset();
3895  } else {
3896    mirror::Class* super_class = klass->GetSuperClass();
3897    if (super_class != NULL) {
3898      CHECK(super_class->IsResolved());
3899      field_offset = MemberOffset(super_class->GetObjectSize());
3900    }
3901    size = field_offset.Uint32Value();
3902  }
3903
3904  CHECK_EQ(num_fields == 0, fields == NULL);
3905
3906  // we want a relatively stable order so that adding new fields
3907  // minimizes disruption of C++ version such as Class and Method.
3908  std::deque<mirror::ArtField*> grouped_and_sorted_fields;
3909  for (size_t i = 0; i < num_fields; i++) {
3910    mirror::ArtField* f = fields->Get(i);
3911    CHECK(f != NULL);
3912    grouped_and_sorted_fields.push_back(f);
3913  }
3914  std::sort(grouped_and_sorted_fields.begin(), grouped_and_sorted_fields.end(),
3915            LinkFieldsComparator());
3916
3917  // References should be at the front.
3918  size_t current_field = 0;
3919  size_t num_reference_fields = 0;
3920  for (; current_field < num_fields; current_field++) {
3921    mirror::ArtField* field = grouped_and_sorted_fields.front();
3922    FieldHelper fh(field);
3923    Primitive::Type type = fh.GetTypeAsPrimitiveType();
3924    bool isPrimitive = type != Primitive::kPrimNot;
3925    if (isPrimitive) {
3926      break;  // past last reference, move on to the next phase
3927    }
3928    grouped_and_sorted_fields.pop_front();
3929    num_reference_fields++;
3930    fields->Set(current_field, field);
3931    field->SetOffset(field_offset);
3932    field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
3933  }
3934
3935  // Now we want to pack all of the double-wide fields together.  If
3936  // we're not aligned, though, we want to shuffle one 32-bit field
3937  // into place.  If we can't find one, we'll have to pad it.
3938  if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
3939    for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
3940      mirror::ArtField* field = grouped_and_sorted_fields[i];
3941      FieldHelper fh(field);
3942      Primitive::Type type = fh.GetTypeAsPrimitiveType();
3943      CHECK(type != Primitive::kPrimNot);  // should only be working on primitive types
3944      if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
3945        continue;
3946      }
3947      fields->Set(current_field++, field);
3948      field->SetOffset(field_offset);
3949      // drop the consumed field
3950      grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
3951      break;
3952    }
3953    // whether we found a 32-bit field for padding or not, we advance
3954    field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
3955  }
3956
3957  // Alignment is good, shuffle any double-wide fields forward, and
3958  // finish assigning field offsets to all fields.
3959  DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
3960  while (!grouped_and_sorted_fields.empty()) {
3961    mirror::ArtField* field = grouped_and_sorted_fields.front();
3962    grouped_and_sorted_fields.pop_front();
3963    FieldHelper fh(field);
3964    Primitive::Type type = fh.GetTypeAsPrimitiveType();
3965    CHECK(type != Primitive::kPrimNot);  // should only be working on primitive types
3966    fields->Set(current_field, field);
3967    field->SetOffset(field_offset);
3968    field_offset = MemberOffset(field_offset.Uint32Value() +
3969                                ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
3970                                 ? sizeof(uint64_t)
3971                                 : sizeof(uint32_t)));
3972    current_field++;
3973  }
3974
3975  // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
3976  if (!is_static &&
3977      (strcmp("Ljava/lang/ref/Reference;", ClassHelper(klass.get()).GetDescriptor()) == 0)) {
3978    // We know there are no non-reference fields in the Reference classes, and we know
3979    // that 'referent' is alphabetically last, so this is easy...
3980    CHECK_EQ(num_reference_fields, num_fields);
3981    FieldHelper fh(fields->Get(num_fields - 1));
3982    CHECK_STREQ(fh.GetName(), "referent");
3983    --num_reference_fields;
3984  }
3985
3986  if (kIsDebugBuild) {
3987    // Make sure that all reference fields appear before
3988    // non-reference fields, and all double-wide fields are aligned.
3989    bool seen_non_ref = false;
3990    for (size_t i = 0; i < num_fields; i++) {
3991      mirror::ArtField* field = fields->Get(i);
3992      if (false) {  // enable to debug field layout
3993        LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
3994                    << " class=" << PrettyClass(klass.get())
3995                    << " field=" << PrettyField(field)
3996                    << " offset=" << field->GetField32(MemberOffset(mirror::ArtField::OffsetOffset()),
3997                                                       false);
3998      }
3999      FieldHelper fh(field);
4000      Primitive::Type type = fh.GetTypeAsPrimitiveType();
4001      bool is_primitive = type != Primitive::kPrimNot;
4002      if ((strcmp("Ljava/lang/ref/Reference;", ClassHelper(klass.get()).GetDescriptor()) == 0)
4003          && (strcmp("referent", fh.GetName()) == 0)) {
4004        is_primitive = true;  // We lied above, so we have to expect a lie here.
4005      }
4006      if (is_primitive) {
4007        if (!seen_non_ref) {
4008          seen_non_ref = true;
4009          DCHECK_EQ(num_reference_fields, i);
4010        }
4011      } else {
4012        DCHECK(!seen_non_ref);
4013      }
4014    }
4015    if (!seen_non_ref) {
4016      DCHECK_EQ(num_fields, num_reference_fields);
4017    }
4018  }
4019  size = field_offset.Uint32Value();
4020  // Update klass
4021  if (is_static) {
4022    klass->SetNumReferenceStaticFields(num_reference_fields);
4023    klass->SetClassSize(size);
4024  } else {
4025    klass->SetNumReferenceInstanceFields(num_reference_fields);
4026    if (!klass->IsVariableSize()) {
4027      DCHECK_GE(size, sizeof(mirror::Object)) << ClassHelper(klass.get()).GetDescriptor();
4028      size_t previous_size = klass->GetObjectSize();
4029      if (previous_size != 0) {
4030        // Make sure that we didn't originally have an incorrect size.
4031        CHECK_EQ(previous_size, size);
4032      }
4033      klass->SetObjectSize(size);
4034    }
4035  }
4036  return true;
4037}
4038
4039//  Set the bitmap of reference offsets, refOffsets, from the ifields
4040//  list.
4041void ClassLinker::CreateReferenceInstanceOffsets(const SirtRef<mirror::Class>& klass) {
4042  uint32_t reference_offsets = 0;
4043  mirror::Class* super_class = klass->GetSuperClass();
4044  if (super_class != NULL) {
4045    reference_offsets = super_class->GetReferenceInstanceOffsets();
4046    // If our superclass overflowed, we don't stand a chance.
4047    if (reference_offsets == CLASS_WALK_SUPER) {
4048      klass->SetReferenceInstanceOffsets(reference_offsets);
4049      return;
4050    }
4051  }
4052  CreateReferenceOffsets(klass, false, reference_offsets);
4053}
4054
4055void ClassLinker::CreateReferenceStaticOffsets(const SirtRef<mirror::Class>& klass) {
4056  CreateReferenceOffsets(klass, true, 0);
4057}
4058
4059void ClassLinker::CreateReferenceOffsets(const SirtRef<mirror::Class>& klass, bool is_static,
4060                                         uint32_t reference_offsets) {
4061  size_t num_reference_fields =
4062      is_static ? klass->NumReferenceStaticFieldsDuringLinking()
4063                : klass->NumReferenceInstanceFieldsDuringLinking();
4064  mirror::ObjectArray<mirror::ArtField>* fields =
4065      is_static ? klass->GetSFields() : klass->GetIFields();
4066  // All of the fields that contain object references are guaranteed
4067  // to be at the beginning of the fields list.
4068  for (size_t i = 0; i < num_reference_fields; ++i) {
4069    // Note that byte_offset is the offset from the beginning of
4070    // object, not the offset into instance data
4071    mirror::ArtField* field = fields->Get(i);
4072    MemberOffset byte_offset = field->GetOffsetDuringLinking();
4073    CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
4074    if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
4075      uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
4076      CHECK_NE(new_bit, 0U);
4077      reference_offsets |= new_bit;
4078    } else {
4079      reference_offsets = CLASS_WALK_SUPER;
4080      break;
4081    }
4082  }
4083  // Update fields in klass
4084  if (is_static) {
4085    klass->SetReferenceStaticOffsets(reference_offsets);
4086  } else {
4087    klass->SetReferenceInstanceOffsets(reference_offsets);
4088  }
4089}
4090
4091mirror::String* ClassLinker::ResolveString(const DexFile& dex_file, uint32_t string_idx,
4092                                           const SirtRef<mirror::DexCache>& dex_cache) {
4093  DCHECK(dex_cache.get() != nullptr);
4094  mirror::String* resolved = dex_cache->GetResolvedString(string_idx);
4095  if (resolved != NULL) {
4096    return resolved;
4097  }
4098  uint32_t utf16_length;
4099  const char* utf8_data = dex_file.StringDataAndUtf16LengthByIdx(string_idx, &utf16_length);
4100  mirror::String* string = intern_table_->InternStrong(utf16_length, utf8_data);
4101  dex_cache->SetResolvedString(string_idx, string);
4102  return string;
4103}
4104
4105mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
4106                                        mirror::Class* referrer) {
4107  Thread* self = Thread::Current();
4108  SirtRef<mirror::DexCache> dex_cache(self, referrer->GetDexCache());
4109  SirtRef<mirror::ClassLoader> class_loader(self, referrer->GetClassLoader());
4110  return ResolveType(dex_file, type_idx, dex_cache, class_loader);
4111}
4112
4113mirror::Class* ClassLinker::ResolveType(const DexFile& dex_file, uint16_t type_idx,
4114                                        const SirtRef<mirror::DexCache>& dex_cache,
4115                                        const SirtRef<mirror::ClassLoader>& class_loader) {
4116  DCHECK(dex_cache.get() != NULL);
4117  mirror::Class* resolved = dex_cache->GetResolvedType(type_idx);
4118  if (resolved == NULL) {
4119    const char* descriptor = dex_file.StringByTypeIdx(type_idx);
4120    resolved = FindClass(descriptor, class_loader);
4121    if (resolved != NULL) {
4122      // TODO: we used to throw here if resolved's class loader was not the
4123      //       boot class loader. This was to permit different classes with the
4124      //       same name to be loaded simultaneously by different loaders
4125      dex_cache->SetResolvedType(type_idx, resolved);
4126    } else {
4127      Thread* self = Thread::Current();
4128      CHECK(self->IsExceptionPending())
4129          << "Expected pending exception for failed resolution of: " << descriptor;
4130      // Convert a ClassNotFoundException to a NoClassDefFoundError.
4131      SirtRef<mirror::Throwable> cause(self, self->GetException(NULL));
4132      if (cause->InstanceOf(GetClassRoot(kJavaLangClassNotFoundException))) {
4133        DCHECK(resolved == NULL);  // No SirtRef needed to preserve resolved.
4134        Thread::Current()->ClearException();
4135        ThrowNoClassDefFoundError("Failed resolution of: %s", descriptor);
4136        self->GetException(NULL)->SetCause(cause.get());
4137      }
4138    }
4139  }
4140  DCHECK((resolved == NULL) || resolved->IsResolved() || resolved->IsErroneous())
4141          << PrettyDescriptor(resolved) << " " << resolved->GetStatus();
4142  return resolved;
4143}
4144
4145mirror::ArtMethod* ClassLinker::ResolveMethod(const DexFile& dex_file,
4146                                              uint32_t method_idx,
4147                                              const SirtRef<mirror::DexCache>& dex_cache,
4148                                              const SirtRef<mirror::ClassLoader>& class_loader,
4149                                              mirror::ArtMethod* referrer,
4150                                              InvokeType type) {
4151  DCHECK(dex_cache.get() != NULL);
4152  // Check for hit in the dex cache.
4153  mirror::ArtMethod* resolved = dex_cache->GetResolvedMethod(method_idx);
4154  if (resolved != NULL && !resolved->IsRuntimeMethod()) {
4155    return resolved;
4156  }
4157  // Fail, get the declaring class.
4158  const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
4159  mirror::Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
4160  if (klass == NULL) {
4161    DCHECK(Thread::Current()->IsExceptionPending());
4162    return NULL;
4163  }
4164  // Scan using method_idx, this saves string compares but will only hit for matching dex
4165  // caches/files.
4166  switch (type) {
4167    case kDirect:  // Fall-through.
4168    case kStatic:
4169      resolved = klass->FindDirectMethod(dex_cache.get(), method_idx);
4170      break;
4171    case kInterface:
4172      resolved = klass->FindInterfaceMethod(dex_cache.get(), method_idx);
4173      DCHECK(resolved == NULL || resolved->GetDeclaringClass()->IsInterface());
4174      break;
4175    case kSuper:  // Fall-through.
4176    case kVirtual:
4177      resolved = klass->FindVirtualMethod(dex_cache.get(), method_idx);
4178      break;
4179    default:
4180      LOG(FATAL) << "Unreachable - invocation type: " << type;
4181  }
4182  if (resolved == NULL) {
4183    // Search by name, which works across dex files.
4184    const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4185    const Signature signature = dex_file.GetMethodSignature(method_id);
4186    switch (type) {
4187      case kDirect:  // Fall-through.
4188      case kStatic:
4189        resolved = klass->FindDirectMethod(name, signature);
4190        break;
4191      case kInterface:
4192        resolved = klass->FindInterfaceMethod(name, signature);
4193        DCHECK(resolved == NULL || resolved->GetDeclaringClass()->IsInterface());
4194        break;
4195      case kSuper:  // Fall-through.
4196      case kVirtual:
4197        resolved = klass->FindVirtualMethod(name, signature);
4198        break;
4199    }
4200  }
4201  if (resolved != NULL) {
4202    // We found a method, check for incompatible class changes.
4203    if (resolved->CheckIncompatibleClassChange(type)) {
4204      resolved = NULL;
4205    }
4206  }
4207  if (resolved != NULL) {
4208    // Be a good citizen and update the dex cache to speed subsequent calls.
4209    dex_cache->SetResolvedMethod(method_idx, resolved);
4210    return resolved;
4211  } else {
4212    // We failed to find the method which means either an access error, an incompatible class
4213    // change, or no such method. First try to find the method among direct and virtual methods.
4214    const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
4215    const Signature signature = dex_file.GetMethodSignature(method_id);
4216    switch (type) {
4217      case kDirect:
4218      case kStatic:
4219        resolved = klass->FindVirtualMethod(name, signature);
4220        break;
4221      case kInterface:
4222      case kVirtual:
4223      case kSuper:
4224        resolved = klass->FindDirectMethod(name, signature);
4225        break;
4226    }
4227
4228    // If we found something, check that it can be accessed by the referrer.
4229    if (resolved != NULL && referrer != NULL) {
4230      mirror::Class* methods_class = resolved->GetDeclaringClass();
4231      mirror::Class* referring_class = referrer->GetDeclaringClass();
4232      if (!referring_class->CanAccess(methods_class)) {
4233        ThrowIllegalAccessErrorClassForMethodDispatch(referring_class, methods_class,
4234                                                      resolved, type);
4235        return NULL;
4236      } else if (!referring_class->CanAccessMember(methods_class,
4237                                                   resolved->GetAccessFlags())) {
4238        ThrowIllegalAccessErrorMethod(referring_class, resolved);
4239        return NULL;
4240      }
4241    }
4242
4243    // Otherwise, throw an IncompatibleClassChangeError if we found something, and check interface
4244    // methods and throw if we find the method there. If we find nothing, throw a NoSuchMethodError.
4245    switch (type) {
4246      case kDirect:
4247      case kStatic:
4248        if (resolved != NULL) {
4249          ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
4250        } else {
4251          resolved = klass->FindInterfaceMethod(name, signature);
4252          if (resolved != NULL) {
4253            ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
4254          } else {
4255            ThrowNoSuchMethodError(type, klass, name, signature);
4256          }
4257        }
4258        break;
4259      case kInterface:
4260        if (resolved != NULL) {
4261          ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
4262        } else {
4263          resolved = klass->FindVirtualMethod(name, signature);
4264          if (resolved != NULL) {
4265            ThrowIncompatibleClassChangeError(type, kVirtual, resolved, referrer);
4266          } else {
4267            ThrowNoSuchMethodError(type, klass, name, signature);
4268          }
4269        }
4270        break;
4271      case kSuper:
4272        ThrowNoSuchMethodError(type, klass, name, signature);
4273        break;
4274      case kVirtual:
4275        if (resolved != NULL) {
4276          ThrowIncompatibleClassChangeError(type, kDirect, resolved, referrer);
4277        } else {
4278          resolved = klass->FindInterfaceMethod(name, signature);
4279          if (resolved != NULL) {
4280            ThrowIncompatibleClassChangeError(type, kInterface, resolved, referrer);
4281          } else {
4282            ThrowNoSuchMethodError(type, klass, name, signature);
4283          }
4284        }
4285        break;
4286    }
4287    DCHECK(Thread::Current()->IsExceptionPending());
4288    return NULL;
4289  }
4290}
4291
4292mirror::ArtField* ClassLinker::ResolveField(const DexFile& dex_file, uint32_t field_idx,
4293                                            const SirtRef<mirror::DexCache>& dex_cache,
4294                                            const SirtRef<mirror::ClassLoader>& class_loader,
4295                                            bool is_static) {
4296  DCHECK(dex_cache.get() != nullptr);
4297  mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
4298  if (resolved != NULL) {
4299    return resolved;
4300  }
4301  const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
4302  mirror::Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
4303  if (klass == NULL) {
4304    DCHECK(Thread::Current()->IsExceptionPending());
4305    return NULL;
4306  }
4307
4308  if (is_static) {
4309    resolved = klass->FindStaticField(dex_cache.get(), field_idx);
4310  } else {
4311    resolved = klass->FindInstanceField(dex_cache.get(), field_idx);
4312  }
4313
4314  if (resolved == NULL) {
4315    const char* name = dex_file.GetFieldName(field_id);
4316    const char* type = dex_file.GetFieldTypeDescriptor(field_id);
4317    if (is_static) {
4318      resolved = klass->FindStaticField(name, type);
4319    } else {
4320      resolved = klass->FindInstanceField(name, type);
4321    }
4322    if (resolved == NULL) {
4323      ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
4324      return NULL;
4325    }
4326  }
4327  dex_cache->SetResolvedField(field_idx, resolved);
4328  return resolved;
4329}
4330
4331mirror::ArtField* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
4332                                               uint32_t field_idx,
4333                                               const SirtRef<mirror::DexCache>& dex_cache,
4334                                               const SirtRef<mirror::ClassLoader>& class_loader) {
4335  DCHECK(dex_cache.get() != nullptr);
4336  mirror::ArtField* resolved = dex_cache->GetResolvedField(field_idx);
4337  if (resolved != NULL) {
4338    return resolved;
4339  }
4340  const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
4341  mirror::Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
4342  if (klass == NULL) {
4343    DCHECK(Thread::Current()->IsExceptionPending());
4344    return NULL;
4345  }
4346
4347  StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_));
4348  StringPiece type(dex_file.StringDataByIdx(
4349      dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_));
4350  resolved = klass->FindField(name, type);
4351  if (resolved != NULL) {
4352    dex_cache->SetResolvedField(field_idx, resolved);
4353  } else {
4354    ThrowNoSuchFieldError("", klass, type, name);
4355  }
4356  return resolved;
4357}
4358
4359const char* ClassLinker::MethodShorty(uint32_t method_idx, mirror::ArtMethod* referrer,
4360                                      uint32_t* length) {
4361  mirror::Class* declaring_class = referrer->GetDeclaringClass();
4362  mirror::DexCache* dex_cache = declaring_class->GetDexCache();
4363  const DexFile& dex_file = *dex_cache->GetDexFile();
4364  const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
4365  return dex_file.GetMethodShorty(method_id, length);
4366}
4367
4368void ClassLinker::DumpAllClasses(int flags) {
4369  if (dex_cache_image_class_lookup_required_) {
4370    MoveImageClassesToClassTable();
4371  }
4372  // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
4373  // lock held, because it might need to resolve a field's type, which would try to take the lock.
4374  std::vector<mirror::Class*> all_classes;
4375  {
4376    ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4377    for (const std::pair<size_t, mirror::Class*>& it : class_table_) {
4378      all_classes.push_back(it.second);
4379    }
4380  }
4381
4382  for (size_t i = 0; i < all_classes.size(); ++i) {
4383    all_classes[i]->DumpClass(std::cerr, flags);
4384  }
4385}
4386
4387void ClassLinker::DumpForSigQuit(std::ostream& os) {
4388  if (dex_cache_image_class_lookup_required_) {
4389    MoveImageClassesToClassTable();
4390  }
4391  ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4392  os << "Loaded classes: " << class_table_.size() << " allocated classes\n";
4393}
4394
4395size_t ClassLinker::NumLoadedClasses() {
4396  if (dex_cache_image_class_lookup_required_) {
4397    MoveImageClassesToClassTable();
4398  }
4399  ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
4400  return class_table_.size();
4401}
4402
4403pid_t ClassLinker::GetClassesLockOwner() {
4404  return Locks::classlinker_classes_lock_->GetExclusiveOwnerTid();
4405}
4406
4407pid_t ClassLinker::GetDexLockOwner() {
4408  return dex_lock_.GetExclusiveOwnerTid();
4409}
4410
4411void ClassLinker::SetClassRoot(ClassRoot class_root, mirror::Class* klass) {
4412  DCHECK(!init_done_);
4413
4414  DCHECK(klass != NULL);
4415  DCHECK(klass->GetClassLoader() == NULL);
4416
4417  DCHECK(class_roots_ != NULL);
4418  DCHECK(class_roots_->Get(class_root) == NULL);
4419  class_roots_->Set(class_root, klass);
4420}
4421
4422}  // namespace art
4423