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