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