blob: 5e054392dced4a413aaa2b23b6a3a4759b3f90d8 [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004
Brian Carlstromdbc05252011-09-09 01:59:59 -07005#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070011#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070012#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070013#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "dex_verifier.h"
15#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070016#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070018#include "monitor.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070019#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include "runtime.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070021#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070022#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070023#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070024#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025
26namespace art {
27
Brian Carlstroma663ea52011-08-19 23:33:41 -070028const char* ClassLinker::class_roots_descriptors_[kClassRootsMax] = {
29 "Ljava/lang/Class;",
30 "Ljava/lang/Object;",
31 "[Ljava/lang/Object;",
32 "Ljava/lang/String;",
33 "Ljava/lang/reflect/Field;",
34 "Ljava/lang/reflect/Method;",
35 "Ljava/lang/ClassLoader;",
36 "Ldalvik/system/BaseDexClassLoader;",
37 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070038 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070039 "Z",
40 "B",
41 "C",
42 "D",
43 "F",
44 "I",
45 "J",
46 "S",
47 "V",
48 "[Z",
49 "[B",
50 "[C",
51 "[D",
52 "[F",
53 "[I",
54 "[J",
55 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070056 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070057};
58
Elliott Hughes5f791332011-09-15 17:45:30 -070059class ObjectLock {
60 public:
61 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
62 CHECK(object != NULL);
63 obj_->MonitorEnter(self_);
64 }
65
66 ~ObjectLock() {
67 obj_->MonitorExit(self_);
68 }
69
70 void Wait() {
71 return Monitor::Wait(self_, obj_, 0, 0, false);
72 }
73
74 void Notify() {
75 obj_->Notify();
76 }
77
78 void NotifyAll() {
79 obj_->NotifyAll();
80 }
81
82 private:
83 Thread* self_;
84 Object* obj_;
85 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
86};
87
Elliott Hughescf4c6c42011-09-01 15:16:42 -070088ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path,
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070089 const std::vector<const DexFile*>& class_path,
Brian Carlstromc74255f2011-09-11 22:47:39 -070090 InternTable* intern_table, bool image) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070091 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -070092 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstromc74255f2011-09-11 22:47:39 -070093 if (image) {
94 class_linker->InitFromImage(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -070095 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -070096 class_linker->Init(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -070097 }
Carl Shapiro61e019d2011-07-14 16:53:09 -070098 // TODO: check for failure during initialization
99 return class_linker.release();
100}
101
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700102ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700103 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700104 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700105 array_interfaces_(NULL),
106 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700107 init_done_(false),
108 intern_table_(intern_table) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700109}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700110
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700111void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
112 const std::vector<const DexFile*>& class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700113 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700114
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700115 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700116 Class* java_lang_Class = down_cast<Class*>(
117 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700118 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700119 java_lang_Class->SetClass(java_lang_Class);
120 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700121 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700122
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700123 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700124 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700125 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700126 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700127 java_lang_Class->SetSuperClass(java_lang_Object);
128 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700129
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700130 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700131 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700132 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700133
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700134 // Setup the char class to be used for char[]
135 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
136
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700137 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700138 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700139 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700140 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700141
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700142 // Setup String
143 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
144 String::SetClass(java_lang_String);
145 java_lang_String->SetObjectSize(sizeof(String));
146 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400147
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700148 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700149 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
150 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
151 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
152 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
153 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700154
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700155 // Create storage for root classes, save away our work so far (requires
156 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700157 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700158 SetClassRoot(kJavaLangClass, java_lang_Class);
159 SetClassRoot(kJavaLangObject, java_lang_Object);
160 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700161 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700162 SetClassRoot(kJavaLangString, java_lang_String);
163
164 // Setup the primitive type classes.
165 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
166 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700167 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
168 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
169 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
170 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
171 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
172 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
173
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700174 // Create array interface entries to populate once we can load system classes
175 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700176 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700177
178 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
179 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700180 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700181 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
182 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700183 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700184
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700185 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700186
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700187 // setup boot_class_path_ and register class_path now that we can
188 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700189 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700190 const DexFile* dex_file = boot_class_path[i];
191 CHECK(dex_file != NULL);
192 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700193 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700194 for (size_t i = 0; i != class_path.size(); ++i) {
195 const DexFile* dex_file = class_path[i];
196 CHECK(dex_file != NULL);
197 RegisterDexFile(*dex_file);
198 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199
200 // Field and Method are necessary so that FindClass can link members
201 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
202 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700203 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700204 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
205 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
206 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
207 Field::SetClass(java_lang_reflect_Field);
208
209 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700210 java_lang_reflect_Method->SetDescriptor(
211 intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700212 CHECK(java_lang_reflect_Method != NULL);
213 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
214 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
215 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
216 Method::SetClass(java_lang_reflect_Method);
217
218 // now we can use FindSystemClass
219
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700220 // run char class through InitializePrimitiveClass to finish init
221 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
222 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
223
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700224 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700225 java_lang_Object->SetStatus(Class::kStatusNotReady);
226 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
227 CHECK_EQ(java_lang_Object, Object_class);
228 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
229 java_lang_String->SetStatus(Class::kStatusNotReady);
230 Class* String_class = FindSystemClass("Ljava/lang/String;");
231 CHECK_EQ(java_lang_String, String_class);
232 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
233
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700234 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700235 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
236 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
237
238 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
239 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
240
241 Class* found_char_array_class = FindSystemClass("[C");
242 CHECK_EQ(char_array_class, found_char_array_class);
243
244 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
245 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
246
247 Class* found_int_array_class = FindSystemClass("[I");
248 CHECK_EQ(int_array_class, found_int_array_class);
249
250 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
251 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
252
253 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
254 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
255
256 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
257 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
258
259 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
260 CHECK_EQ(object_array_class, found_object_array_class);
261
262 // Setup the single, global copies of "interfaces" and "iftable"
263 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
264 CHECK(java_lang_Cloneable != NULL);
265 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
266 CHECK(java_io_Serializable != NULL);
267 CHECK(array_interfaces_ != NULL);
268 array_interfaces_->Set(0, java_lang_Cloneable);
269 array_interfaces_->Set(1, java_io_Serializable);
270 // We assume that Cloneable/Serializable don't have superinterfaces --
271 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700272 // supers as well.
273 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
274 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275
276 // Sanity check Object[]'s interfaces
277 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
278 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700279
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700280 // run Class, Field, and Method through FindSystemClass.
281 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700282 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700283 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284
285 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700286 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700287 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288
289 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700290 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700291 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700292
293 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
294 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295 java_lang_ref_FinalizerReference->SetAccessFlags(
296 java_lang_ref_FinalizerReference->GetAccessFlags() |
297 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700298 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299 java_lang_ref_PhantomReference->SetAccessFlags(
300 java_lang_ref_PhantomReference->GetAccessFlags() |
301 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700302 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303 java_lang_ref_SoftReference->SetAccessFlags(
304 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700305 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306 java_lang_ref_WeakReference->SetAccessFlags(
307 java_lang_ref_WeakReference->GetAccessFlags() |
308 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700309
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700310 // Setup the ClassLoaders, adjusting the object_size_ as necessary
311 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
312 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
313 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
314 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
315
316 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
317 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
318 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
319
320 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
321 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
322 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
323 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
324
325 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700326 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
327 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700328 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700329
Brian Carlstroma663ea52011-08-19 23:33:41 -0700330 FinishInit();
331}
332
333void ClassLinker::FinishInit() {
Brian Carlstrom16192862011-09-12 17:50:06 -0700334
335 // Let the heap know some key offsets into java.lang.ref instances
336 // NB we hard code the field indexes here rather than using FindInstanceField
337 // as the types of the field can't be resolved prior to the runtime being
338 // fully initialized
339 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
340 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
341
342 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
343 CHECK(pendingNext->GetName()->Equals("pendingNext"));
344 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
345
346 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
347 CHECK(queue->GetName()->Equals("queue"));
348 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
349 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
350
351 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
352 CHECK(queueNext->GetName()->Equals("queueNext"));
353 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
354
355 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
356 CHECK(referent->GetName()->Equals("referent"));
357 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
358
359 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
360 CHECK(zombie->GetName()->Equals("zombie"));
361 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
362
363 Heap::SetReferenceOffsets(referent->GetOffset(),
364 queue->GetOffset(),
365 queueNext->GetOffset(),
366 pendingNext->GetOffset(),
367 zombie->GetOffset());
368
Brian Carlstroma663ea52011-08-19 23:33:41 -0700369 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700370 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700371 ClassRoot class_root = static_cast<ClassRoot>(i);
372 Class* klass = GetClassRoot(class_root);
373 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700375 // note SetClassRoot does additional validation.
376 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700377 }
378
379 // disable the slow paths in FindClass and CreatePrimitiveClass now
380 // that Object, Class, and Object[] are setup
381 init_done_ = true;
382}
383
Brian Carlstromc74255f2011-09-11 22:47:39 -0700384struct ClassLinker::InitFromImageCallbackState {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700385 ClassLinker* class_linker;
386
387 Class* class_roots[kClassRootsMax];
388
389 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
390 Table descriptor_to_class_root;
391
Brian Carlstroma663ea52011-08-19 23:33:41 -0700392 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
393 Set dex_caches;
394};
395
Brian Carlstromc74255f2011-09-11 22:47:39 -0700396void ClassLinker::InitFromImage(const std::vector<const DexFile*>& boot_class_path,
397 const std::vector<const DexFile*>& class_path) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700398 CHECK(!init_done_);
399
400 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
401 DCHECK(heap_bitmap != NULL);
402
Brian Carlstromc74255f2011-09-11 22:47:39 -0700403 InitFromImageCallbackState state;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700404 state.class_linker = this;
405 for (size_t i = 0; i < kClassRootsMax; i++) {
406 ClassRoot class_root = static_cast<ClassRoot>(i);
407 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
408 }
409
410 // reinit clases_ table
Brian Carlstromc74255f2011-09-11 22:47:39 -0700411 heap_bitmap->Walk(InitFromImageCallback, &state);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700412
413 // reinit class_roots_
414 Class* object_array_class = state.class_roots[kObjectArrayClass];
415 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
416 for (size_t i = 0; i < kClassRootsMax; i++) {
417 ClassRoot class_root = static_cast<ClassRoot>(i);
418 SetClassRoot(class_root, state.class_roots[class_root]);
419 }
420
Brian Carlstroma663ea52011-08-19 23:33:41 -0700421 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
423 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700424
425 // build a map from location to DexCache to match up with DexFile::GetLocation
426 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Brian Carlstromc74255f2011-09-11 22:47:39 -0700427 typedef InitFromImageCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700428 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
429 DexCache* dex_cache = *it;
430 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
431 location_to_dex_cache[location] = dex_cache;
432 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700433 CHECK_EQ(boot_class_path.size() + class_path.size(),
434 location_to_dex_cache.size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700435
436 // reinit boot_class_path with DexFile arguments and found DexCaches
437 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700438 const DexFile* dex_file = boot_class_path[i];
439 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700440 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700441 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700442 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700443 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700444
445 // register class_path with DexFile arguments and found DexCaches
446 for (size_t i = 0; i != class_path.size(); ++i) {
447 const DexFile* dex_file = class_path[i];
448 CHECK(dex_file != NULL);
449 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
450 CHECK(dex_cache != NULL) << dex_file->GetLocation();
451 RegisterDexFile(*dex_file, dex_cache);
452 }
453
Brian Carlstroma663ea52011-08-19 23:33:41 -0700454 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455 Field::SetClass(GetClassRoot(kJavaLangReflectField));
456 Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700457 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
458 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
459 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
460 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
461 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
462 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
463 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
464 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700465 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700466 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700467
468 FinishInit();
469}
470
Brian Carlstrom78128a62011-09-15 17:21:19 -0700471void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700472 DCHECK(obj != NULL);
473 DCHECK(arg != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700474 InitFromImageCallbackState* state = reinterpret_cast<InitFromImageCallbackState*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700475
Brian Carlstromc74255f2011-09-11 22:47:39 -0700476 if (obj->IsString()) {
477 state->class_linker->intern_table_->RegisterStrong(obj->AsString());
478 return;
479 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700480 if (!obj->IsClass()) {
481 return;
482 }
483 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700484 // TODO: restore ClassLoader's list of DexFiles after image load
485 // CHECK(klass->GetClassLoader() == NULL);
486 const ClassLoader* class_loader = klass->GetClassLoader();
487 if (class_loader != NULL) {
488 // TODO: replace this hack with something based on command line arguments
489 Thread::Current()->SetClassLoaderOverride(class_loader);
490 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700491
492 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700493 // restore class to ClassLinker::classes_ table
494 state->class_linker->InsertClass(descriptor, klass);
495
496 // note DexCache to match with DexFile later
497 DexCache* dex_cache = klass->GetDexCache();
498 if (dex_cache != NULL) {
499 state->dex_caches.insert(dex_cache);
500 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700501 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700502 }
503
504 // check if this is a root, if so, register it
Brian Carlstromc74255f2011-09-11 22:47:39 -0700505 typedef InitFromImageCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700506 It it = state->descriptor_to_class_root.find(descriptor);
507 if (it != state->descriptor_to_class_root.end()) {
508 ClassRoot class_root = it->second;
509 state->class_roots[class_root] = klass;
510 }
511}
512
513// Keep in sync with InitCallback. Anything we visit, we need to
514// reinit references to when reinitializing a ClassLinker from a
515// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700516void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
517 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700518
519 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700520 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700521 }
522
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700523 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700524 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700526 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700527 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700528 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700529 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700530
Elliott Hughes410c0c82011-09-01 17:58:25 -0700531 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700532}
533
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700534ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700535 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700536 Field::ResetClass();
537 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700538 BooleanArray::ResetArrayClass();
539 ByteArray::ResetArrayClass();
540 CharArray::ResetArrayClass();
541 DoubleArray::ResetArrayClass();
542 FloatArray::ResetArrayClass();
543 IntArray::ResetArrayClass();
544 LongArray::ResetArrayClass();
545 ShortArray::ResetArrayClass();
546 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700547 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700548}
549
550DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700551 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700552 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700553 AllocObjectArray<String>(dex_file.NumStringIds()),
554 AllocObjectArray<Class>(dex_file.NumTypeIds()),
555 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700556 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700557 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
558 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700559 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700560}
561
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700562CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
563 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700564}
565
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700566InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
567 DCHECK(interface->IsInterface());
568 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
569 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
570 interface_entry->SetInterface(interface);
571 return interface_entry;
572}
573
Brian Carlstrom4873d462011-08-21 15:23:39 -0700574Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
575 DCHECK_GE(class_size, sizeof(Class));
576 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700577 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
578 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700579 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700580}
581
Brian Carlstrom4873d462011-08-21 15:23:39 -0700582Class* ClassLinker::AllocClass(size_t class_size) {
583 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700584}
585
Jesse Wilson35baaab2011-08-10 16:18:03 -0400586Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700587 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700588}
589
590Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700591 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700592}
593
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700594ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
595 return ObjectArray<StackTraceElement>::Alloc(
596 GetClassRoot(kJavaLangStackTraceElementArrayClass),
597 length);
598}
599
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700600Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700601 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700602 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700603 if (class_loader != NULL) {
604 Class* klass = FindClass(descriptor, NULL);
605 if (klass != NULL) {
606 return klass;
607 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700608 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700609 }
610
Carl Shapirob5573532011-07-12 18:22:59 -0700611 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700612 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700613 CHECK(!self->IsExceptionPending());
614 // Find the class in the loaded classes table.
615 Class* klass = LookupClass(descriptor, class_loader);
616 if (klass == NULL) {
617 // Class is not yet loaded.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700618 if (descriptor[0] == '[' && descriptor[1] != '\0') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700619 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700620 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700621 const DexFile::ClassPath& class_path = ((class_loader != NULL)
622 ? ClassLoader::GetClassPath(class_loader)
623 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700624 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700625 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700626 std::string name(PrintableString(descriptor));
627 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
628 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700629 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700630 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700631 const DexFile& dex_file = *pair.first;
632 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700633 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700634 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700635 if (!init_done_) {
636 // finish up init of hand crafted class_roots_
637 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700638 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700639 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700640 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400641 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700642 klass = GetClassRoot(kJavaLangString);
643 } else if (descriptor == "Ljava/lang/reflect/Field;") {
644 klass = GetClassRoot(kJavaLangReflectField);
645 } else if (descriptor == "Ljava/lang/reflect/Method;") {
646 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700647 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700648 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700649 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700650 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700651 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700652 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700653 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700654 klass->SetDexCache(dex_cache);
655 LoadClass(dex_file, dex_class_def, klass, class_loader);
656 // Check for a pending exception during load
657 if (self->IsExceptionPending()) {
658 // TODO: free native allocations in klass
659 return NULL;
660 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700661 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700662 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700663 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700664 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700665 if (!success) {
666 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700667 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700668 // TODO: free native allocations in klass
669 klass = LookupClass(descriptor, class_loader);
670 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700671 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700672 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700673 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700674 CHECK(!klass->IsLoaded());
675 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700676 // Loading failed.
677 // TODO: CHECK(self->IsExceptionPending());
678 lock.NotifyAll();
679 return NULL;
680 }
681 CHECK(klass->IsLoaded());
682 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700683 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700684 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700685 // Linking failed.
686 // TODO: CHECK(self->IsExceptionPending());
687 lock.NotifyAll();
688 return NULL;
689 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700690 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700691 }
692 }
693 }
694 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700695 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700696 ObjectLock lock(klass);
697 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700698 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700699 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700700 return NULL;
701 }
702 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700703 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700704 lock.Wait();
705 }
706 }
707 if (klass->IsErroneous()) {
708 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
709 return NULL;
710 }
711 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700712 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700713 CHECK(!self->IsExceptionPending());
714 return klass;
715}
716
Brian Carlstrom4873d462011-08-21 15:23:39 -0700717// Precomputes size that will be needed for Class, matching LinkStaticFields
718size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
719 const DexFile::ClassDef& dex_class_def) {
720 const byte* class_data = dex_file.GetClassData(dex_class_def);
721 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
722 size_t num_static_fields = header.static_fields_size_;
723 size_t num_ref = 0;
724 size_t num_32 = 0;
725 size_t num_64 = 0;
726 if (num_static_fields != 0) {
727 uint32_t last_idx = 0;
728 for (size_t i = 0; i < num_static_fields; ++i) {
729 DexFile::Field dex_field;
730 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
731 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
732 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
733 char c = descriptor[0];
734 if (c == 'L' || c == '[') {
735 num_ref++;
736 } else if (c == 'J' || c == 'D') {
737 num_64++;
738 } else {
739 num_32++;
740 }
741 }
742 }
743
744 // start with generic class data
745 size_t size = sizeof(Class);
746 // follow with reference fields which must be contiguous at start
747 size += (num_ref * sizeof(uint32_t));
748 // if there are 64-bit fields to add, make sure they are aligned
749 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
750 if (num_32 != 0) {
751 // use an available 32-bit field for padding
752 num_32--;
753 }
754 size += sizeof(uint32_t); // either way, we are adding a word
755 DCHECK_EQ(size, RoundUp(size, 8));
756 }
757 // tack on any 64-bit fields now that alignment is assured
758 size += (num_64 * sizeof(uint64_t));
759 // tack on any remaining 32-bit fields
760 size += (num_32 * sizeof(uint32_t));
761 return size;
762}
763
Brian Carlstromf615a612011-07-23 12:50:34 -0700764void ClassLinker::LoadClass(const DexFile& dex_file,
765 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700766 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700767 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700768 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700769 CHECK(klass->GetDexCache() != NULL);
770 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700771 const byte* class_data = dex_file.GetClassData(dex_class_def);
772 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700773
Brian Carlstromf615a612011-07-23 12:50:34 -0700774 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700775 CHECK(descriptor != NULL);
776
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700777 klass->SetClass(GetClassRoot(kJavaLangClass));
778 if (klass->GetDescriptor() != NULL) {
779 DCHECK(klass->GetDescriptor()->Equals(descriptor));
780 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700781 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700782 }
783 uint32_t access_flags = dex_class_def.access_flags_;
784 // Make sure there aren't any "bonus" flags set, since we use them for runtime
785 // state.
786 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
787 klass->SetAccessFlags(access_flags);
788 klass->SetClassLoader(class_loader);
789 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
790 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700791
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700792 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700793
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700794 size_t num_static_fields = header.static_fields_size_;
795 size_t num_instance_fields = header.instance_fields_size_;
796 size_t num_direct_methods = header.direct_methods_size_;
797 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700798
Brian Carlstromc74255f2011-09-11 22:47:39 -0700799 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700800
801 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700802 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700803
804 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700805 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700806 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700807 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700808 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700809 DexFile::Field dex_field;
810 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400811 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700812 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700813 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700814 }
815 }
816
817 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700818 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700819 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700820 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700821 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700822 DexFile::Field dex_field;
823 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400824 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700825 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700826 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700827 }
828 }
829
830 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700831 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700832 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700833 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700834 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700835 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700836 DexFile::Method dex_method;
837 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700838 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700839 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700840 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700841 // TODO: register maps
842 }
843 }
844
845 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700846 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700847 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700848 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700849 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700850 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700851 DexFile::Method dex_method;
852 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700853 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700854 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700855 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700856 // TODO: register maps
857 }
858 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700859}
860
Brian Carlstromf615a612011-07-23 12:50:34 -0700861void ClassLinker::LoadInterfaces(const DexFile& dex_file,
862 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700863 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700864 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700865 if (list != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700866 klass->SetInterfaces(AllocObjectArray<Class>(list->Size()));
867 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
868 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700869 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700870 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700871 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700872 }
873 }
874}
875
Brian Carlstromf615a612011-07-23 12:50:34 -0700876void ClassLinker::LoadField(const DexFile& dex_file,
877 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700878 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700879 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700880 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700881 dst->SetDeclaringClass(klass);
882 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
883 dst->SetTypeIdx(field_id.type_idx_);
884 dst->SetAccessFlags(src.access_flags_);
885
886 // In order to access primitive types using GetTypeDuringLinking we need to
887 // ensure they are resolved into the dex cache
888 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
889 if (descriptor[1] == '\0') {
890 // only the descriptors of primitive types should be 1 character long
891 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
892 DCHECK(resolved->IsPrimitive());
893 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700894}
895
Brian Carlstromf615a612011-07-23 12:50:34 -0700896void ClassLinker::LoadMethod(const DexFile& dex_file,
897 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700898 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700899 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700900 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700901 dst->SetDeclaringClass(klass);
902 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700903 {
904 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700905 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700906 dst->SetSignature(intern_table_->InternStrong(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700907 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700908 dst->SetProtoIdx(method_id.proto_idx_);
909 dst->SetCodeItemOffset(src.code_off_);
910 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700911 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700912 dst->SetAccessFlags(src.access_flags_);
913 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700914
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700915 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
916 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
917 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
918 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
919 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
920 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700921
Brian Carlstrom934486c2011-07-12 23:42:50 -0700922 // TODO: check for finalize method
923
Brian Carlstromf615a612011-07-23 12:50:34 -0700924 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700925 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700926 dst->SetNumRegisters(code_item->registers_size_);
927 dst->SetNumIns(code_item->ins_size_);
928 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700929 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700930 uint16_t num_args = Method::NumArgRegisters(shorty);
931 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700932 ++num_args;
933 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700934 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700935 // TODO: native methods
936 }
937}
938
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700939void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700940 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
941}
942
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700943void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700944 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700945 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700946 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700947}
948
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700949void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700950 RegisterDexFile(dex_file, AllocDexCache(dex_file));
951}
952
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700953void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700954 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700955 CHECK(dex_cache != NULL) << dex_file.GetLocation();
956 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700957 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700958 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700959}
960
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700961const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700962 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700963 for (size_t i = 0; i != dex_caches_.size(); ++i) {
964 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700965 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700966 }
967 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700968 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700969 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700970}
971
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700972DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700973 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -0700974 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700975 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700976 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700977 }
978 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700979 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700980 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700981}
982
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700983Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
984 const char* descriptor,
985 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700986 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700987 CHECK(primitive_class != NULL);
988 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
989 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
990 primitive_class->SetPrimitiveType(type);
991 primitive_class->SetStatus(Class::kStatusInitialized);
992 bool success = InsertClass(descriptor, primitive_class);
993 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
994 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -0700995}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700996
Brian Carlstrombe977852011-07-19 14:54:54 -0700997// Create an array class (i.e. the class object for the array, not the
998// array itself). "descriptor" looks like "[C" or "[[[[B" or
999// "[Ljava/lang/String;".
1000//
1001// If "descriptor" refers to an array of primitives, look up the
1002// primitive type's internally-generated class object.
1003//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001004// "class_loader" is the class loader of the class that's referring to
1005// us. It's used to ensure that we're looking for the element type in
1006// the right context. It does NOT become the class loader for the
1007// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001008//
1009// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001010Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001011 const ClassLoader* class_loader) {
1012 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001013
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001014 // Identify the underlying component type
1015 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001016 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001017 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001018 return NULL;
1019 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001020
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001021 // See if the component type is already loaded. Array classes are
1022 // always associated with the class loader of their underlying
1023 // element type -- an array of Strings goes with the loader for
1024 // java/lang/String -- so we need to look for it there. (The
1025 // caller should have checked for the existence of the class
1026 // before calling here, but they did so with *their* class loader,
1027 // not the component type's loader.)
1028 //
1029 // If we find it, the caller adds "loader" to the class' initiating
1030 // loader list, which should prevent us from going through this again.
1031 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001032 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001033 // are the same, because our caller (FindClass) just did the
1034 // lookup. (Even if we get this wrong we still have correct behavior,
1035 // because we effectively do this lookup again when we add the new
1036 // class to the hash table --- necessary because of possible races with
1037 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001038 if (class_loader != component_type->GetClassLoader()) {
1039 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001040 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001041 return new_class;
1042 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001043 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001044
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001045 // Fill out the fields in the Class.
1046 //
1047 // It is possible to execute some methods against arrays, because
1048 // all arrays are subclasses of java_lang_Object_, so we need to set
1049 // up a vtable. We can just point at the one in java_lang_Object_.
1050 //
1051 // Array classes are simple enough that we don't need to do a full
1052 // link step.
1053
1054 Class* new_class = NULL;
1055 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001056 // Classes that were hand created, ie not by FindSystemClass
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001057 if (descriptor == "[Ljava/lang/Object;") {
1058 new_class = GetClassRoot(kObjectArrayClass);
1059 } else if (descriptor == "[C") {
1060 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001061 } else if (descriptor == "[I") {
1062 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001063 }
1064 }
1065 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001066 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001067 if (new_class == NULL) {
1068 return NULL;
1069 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001070 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001071 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001072 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001073 if (new_class->GetDescriptor() != NULL) {
1074 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1075 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001076 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001077 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001078 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001079 new_class->SetSuperClass(java_lang_Object);
1080 new_class->SetVTable(java_lang_Object->GetVTable());
1081 new_class->SetPrimitiveType(Class::kPrimNot);
1082 new_class->SetClassLoader(component_type->GetClassLoader());
1083 new_class->SetStatus(Class::kStatusInitialized);
1084 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001085 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001086
1087
1088 // All arrays have java/lang/Cloneable and java/io/Serializable as
1089 // interfaces. We need to set that up here, so that stuff like
1090 // "instanceof" works right.
1091 //
1092 // Note: The GC could run during the call to FindSystemClass,
1093 // so we need to make sure the class object is GC-valid while we're in
1094 // there. Do this by clearing the interface list so the GC will just
1095 // think that the entries are null.
1096
1097
1098 // Use the single, global copies of "interfaces" and "iftable"
1099 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001100 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001101 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001102
1103 // Inherit access flags from the component type. Arrays can't be
1104 // used as a superclass or interface, so we want to add "final"
1105 // and remove "interface".
1106 //
1107 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001108 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001109 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001110 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1111 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001112
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001113 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001114 return new_class;
1115 }
1116 // Another thread must have loaded the class after we
1117 // started but before we finished. Abandon what we've
1118 // done.
1119 //
1120 // (Yes, this happens.)
1121
1122 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001123 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001124 DCHECK(other_class != NULL);
1125 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001126}
1127
1128Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001129 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001130 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001131 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001132 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001133 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001134 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001135 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001136 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001137 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001138 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001139 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001140 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001141 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001142 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001143 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001144 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001145 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001146 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001147 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001148 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001149 std::string printable_type(PrintableChar(type));
1150 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1151 "Not a primitive type: %s", printable_type.c_str());
1152 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001153}
1154
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001155bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1156 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001157 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001158 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001159 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001160}
1161
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001162Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001163 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001164 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001165 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001166 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001167 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001168 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001169 return klass;
1170 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001171 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001172 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001173}
1174
jeffhao98eacac2011-09-14 16:11:53 -07001175void ClassLinker::VerifyClass(Class* klass) {
1176 if (klass->IsVerified()) {
1177 return;
1178 }
1179
1180 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
1181
1182 klass->SetStatus(Class::kStatusVerifying);
1183 if (!DexVerifier::VerifyClass(klass)) {
1184 LOG(ERROR) << "Verification failed on class "
1185 << klass->GetDescriptor()->ToModifiedUtf8();
1186 Object* exception = Thread::Current()->GetException();
1187 klass->SetVerifyErrorClass(exception->GetClass());
1188 klass->SetStatus(Class::kStatusError);
1189 return;
1190 }
1191
1192 klass->SetStatus(Class::kStatusVerified);
1193}
1194
Brian Carlstrom25c33252011-09-18 15:58:35 -07001195bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001196 CHECK(klass->GetStatus() == Class::kStatusResolved ||
jeffhao98eacac2011-09-14 16:11:53 -07001197 klass->GetStatus() == Class::kStatusVerified ||
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001198 klass->GetStatus() == Class::kStatusInitializing ||
1199 klass->GetStatus() == Class::kStatusError)
Elliott Hughes54e7df12011-09-16 11:47:04 -07001200 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001201
Carl Shapirob5573532011-07-12 18:22:59 -07001202 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001203
Brian Carlstrom25c33252011-09-18 15:58:35 -07001204 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001205 {
1206 ObjectLock lock(klass);
1207
1208 if (klass->GetStatus() < Class::kStatusVerified) {
1209 if (klass->IsErroneous()) {
1210 LG << "re-initializing failed class"; // TODO: throw
1211 return false;
1212 }
1213
jeffhao98eacac2011-09-14 16:11:53 -07001214 VerifyClass(klass);
1215 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001216 return false;
1217 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001218 }
1219
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001220 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001221 return true;
1222 }
1223
Brian Carlstrom25c33252011-09-18 15:58:35 -07001224 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1225 if (clinit != NULL && !can_run_clinit) {
1226 // if the class has a <clinit>, don't bother going to initializing
1227 return false;
1228 }
1229
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001230 while (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001231 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001232 if (klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001233 // Yes. That's fine.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001234 return true;
1235 }
1236
1237 CHECK(!self->IsExceptionPending());
1238
1239 lock.Wait(); // TODO: check for interruption
1240
1241 // When we wake up, repeat the test for init-in-progress. If
1242 // there's an exception pending (only possible if
1243 // "interruptShouldThrow" was set), bail out.
1244 if (self->IsExceptionPending()) {
1245 CHECK(false);
1246 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1247 klass->SetStatus(Class::kStatusError);
1248 return false;
1249 }
1250 if (klass->GetStatus() == Class::kStatusInitializing) {
1251 continue;
1252 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001253 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001254 klass->GetStatus() == Class::kStatusError);
1255 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001256 // The caller wants an exception, but it was thrown in a
1257 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001258 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1259 return false;
1260 }
1261 return true; // otherwise, initialized
1262 }
1263
1264 // see if we failed previously
1265 if (klass->IsErroneous()) {
1266 // might be wise to unlock before throwing; depends on which class
1267 // it is that we have locked
1268
1269 // TODO: throwEarlierClassFailure(klass);
1270 return false;
1271 }
1272
1273 if (!ValidateSuperClassDescriptors(klass)) {
1274 klass->SetStatus(Class::kStatusError);
1275 return false;
1276 }
1277
Brian Carlstrom25c33252011-09-18 15:58:35 -07001278 DCHECK_LT(klass->GetStatus(), Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001279
Elliott Hughesdcc24742011-09-07 14:02:44 -07001280 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001281 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001282 }
1283
Brian Carlstrom25c33252011-09-18 15:58:35 -07001284 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001285 return false;
1286 }
1287
1288 InitializeStaticFields(klass);
1289
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001290 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001291 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001292 }
1293
1294 {
1295 ObjectLock lock(klass);
1296
1297 if (self->IsExceptionPending()) {
1298 klass->SetStatus(Class::kStatusError);
1299 } else {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001300 ++Runtime::Current()->GetStats()->class_init_count;
1301 ++self->GetStats()->class_init_count;
1302 // TODO: class_init_time_ns
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001303 klass->SetStatus(Class::kStatusInitialized);
1304 }
1305 lock.NotifyAll();
1306 }
1307
1308 return true;
1309}
1310
1311bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1312 if (klass->IsInterface()) {
1313 return true;
1314 }
1315 // begin with the methods local to the superclass
1316 if (klass->HasSuperClass() &&
1317 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1318 const Class* super = klass->GetSuperClass();
1319 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001320 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001321 if (method != super->GetVirtualMethod(i) &&
1322 !HasSameMethodDescriptorClasses(method, super, klass)) {
1323 LG << "Classes resolve differently in superclass";
1324 return false;
1325 }
1326 }
1327 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001328 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1329 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1330 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001331 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1332 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001333 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001334 if (!HasSameMethodDescriptorClasses(method, interface,
1335 method->GetClass())) {
1336 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1337 return false;
1338 }
1339 }
1340 }
1341 }
1342 return true;
1343}
1344
1345bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001346 const Class* klass1,
1347 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001348 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001349 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001350 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001351 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001352 const char* descriptor = it->GetDescriptor();
1353 if (descriptor == NULL) {
1354 break;
1355 }
1356 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1357 // Found a non-primitive type.
1358 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1359 return false;
1360 }
1361 }
1362 }
1363 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001364 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001365 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1366 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1367 return false;
1368 }
1369 }
1370 return true;
1371}
1372
1373// Returns true if classes referenced by the descriptor are the
1374// same classes in klass1 as they are in klass2.
1375bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001376 const Class* klass1,
1377 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001378 CHECK(descriptor != NULL);
1379 CHECK(klass1 != NULL);
1380 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001381 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001382 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001383 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001384 // TODO: found2 == NULL
1385 // TODO: lookup found1 in initiating loader list
1386 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001387 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001388 if (found1 == found2) {
1389 return true;
1390 } else {
1391 return false;
1392 }
1393 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001394 return true;
1395}
1396
Brian Carlstrom25c33252011-09-18 15:58:35 -07001397bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001398 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001399 if (!klass->IsInterface() && klass->HasSuperClass()) {
1400 Class* super_class = klass->GetSuperClass();
1401 if (super_class->GetStatus() != Class::kStatusInitialized) {
1402 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001403 Thread* self = Thread::Current();
1404 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001405 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001406 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001407 // TODO: check for a pending exception
1408 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001409 if (!can_run_clinit) {
1410 // Don't set status to error when we can't run <clinit>.
1411 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1412 klass->SetStatus(Class::kStatusVerified);
1413 return false;
1414 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001415 klass->SetStatus(Class::kStatusError);
1416 klass->NotifyAll();
1417 return false;
1418 }
1419 }
1420 }
1421 return true;
1422}
1423
Brian Carlstrom25c33252011-09-18 15:58:35 -07001424bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001425 CHECK(c != NULL);
1426 if (c->IsInitialized()) {
1427 return true;
1428 }
1429
Elliott Hughes5f791332011-09-15 17:45:30 -07001430 Thread* self = Thread::Current();
1431 c->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001432 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001433 c->MonitorExit(self);
1434 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001435}
1436
Brian Carlstromb9edb842011-08-28 16:31:06 -07001437StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1438 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001439 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1440 Class* klass = class_linker->ResolveType(type_idx, referrer);
1441 if (klass == NULL) {
1442 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1443 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001444 // If we are the <clinit> of this class, just return our storage.
1445 //
1446 // Do not set the DexCache InitializedStaticStorage, since that
1447 // implies <clinit> has finished running.
1448 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1449 return klass;
1450 }
Brian Carlstrom25c33252011-09-18 15:58:35 -07001451 if (!class_linker->EnsureInitialized(klass, true)) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001452 CHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001453 UNIMPLEMENTED(FATAL) << "throw exception due to class initialization problem";
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001454 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001455 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001456 return klass;
1457}
1458
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001459void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1460 Class* c, std::map<int, Field*>& field_map) {
1461 const ClassLoader* cl = c->GetClassLoader();
1462 const byte* class_data = dex_file.GetClassData(dex_class_def);
1463 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1464 uint32_t last_idx = 0;
1465 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1466 DexFile::Field dex_field;
1467 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1468 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1469 }
1470}
1471
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001472void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001473 size_t num_static_fields = klass->NumStaticFields();
1474 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001475 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001476 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001477 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001478 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001479 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001480 return;
1481 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001482 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001483 const DexFile& dex_file = FindDexFile(dex_cache);
1484 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001485 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001486
1487 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1488 std::map<int, Field*> field_map;
1489 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1490
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001491 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001492 if (addr == NULL) {
1493 // All this class' static fields have default values.
1494 return;
1495 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001496 size_t array_size = DecodeUnsignedLeb128(&addr);
1497 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001498 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001499 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001500 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001501 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001502 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001503 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001504 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001505 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001506 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001507 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001508 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001509 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001510 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001511 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001512 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001513 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001514 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001515 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001516 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001517 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001518 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001519 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001520 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001521 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001522 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001523 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001524 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001525 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001526 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001527 break;
1528 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001529 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001530 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001531 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001532 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001533 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001534 break;
1535 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001536 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001537 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001538 }
1539}
1540
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001541bool ClassLinker::LinkClass(Class* klass) {
1542 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001543 if (!LinkSuperClass(klass)) {
1544 return false;
1545 }
1546 if (!LinkMethods(klass)) {
1547 return false;
1548 }
1549 if (!LinkInstanceFields(klass)) {
1550 return false;
1551 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001552 if (!LinkStaticFields(klass)) {
1553 return false;
1554 }
1555 CreateReferenceInstanceOffsets(klass);
1556 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001557 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1558 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001559 return true;
1560}
1561
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001562bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001563 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1564 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1565 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001566 if (super_class == NULL) {
1567 LG << "Failed to resolve superclass";
1568 return false;
1569 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001570 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001571 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001572 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1573 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1574 Class *interface = ResolveType(dex_file, idx, klass);
1575 klass->SetInterface(i, interface);
1576 if (interface == NULL) {
1577 LG << "Failed to resolve interface";
1578 return false;
1579 }
1580 // Verify
1581 if (!klass->CanAccess(interface)) {
1582 LG << "Inaccessible interface";
1583 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001584 }
1585 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001586 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001587 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001588 return true;
1589}
1590
1591bool ClassLinker::LinkSuperClass(Class* klass) {
1592 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001593 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001594 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001595 if (super != NULL) {
1596 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1597 return false;
1598 }
1599 // TODO: clear finalize attribute
1600 return true;
1601 }
1602 if (super == NULL) {
1603 LG << "No superclass defined"; // TODO: LinkageError
1604 return false;
1605 }
1606 // Verify
1607 if (super->IsFinal()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001608 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001609 return false;
1610 }
1611 if (super->IsInterface()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001612 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001613 return false;
1614 }
1615 if (!klass->CanAccess(super)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001616 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001617 return false;
1618 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001619#ifndef NDEBUG
1620 // Ensure super classes are fully resolved prior to resolving fields..
1621 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001622 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001623 super = super->GetSuperClass();
1624 }
1625#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001626 return true;
1627}
1628
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001629// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001630bool ClassLinker::LinkMethods(Class* klass) {
1631 if (klass->IsInterface()) {
1632 // No vtable.
1633 size_t count = klass->NumVirtualMethods();
1634 if (!IsUint(16, count)) {
1635 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1636 return false;
1637 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001638 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001639 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640 }
jeffhaobdb76512011-09-07 11:43:16 -07001641 // Link interface method tables
1642 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001643 } else {
1644 // Link virtual method tables
1645 LinkVirtualMethods(klass);
1646
1647 // Link interface method tables
1648 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001649 }
1650 return true;
1651}
1652
1653bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001654 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001655 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1656 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001657 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001658 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001659 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001660 // See if any of our virtual methods override the superclass.
1661 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001662 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001663 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001664 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001665 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001666 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001667 // Verify
1668 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001669 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001670 return false;
1671 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001672 vtable->Set(j, local_method);
1673 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001674 break;
1675 }
1676 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001677 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001678 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001679 vtable->Set(actual_count, local_method);
1680 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001681 actual_count += 1;
1682 }
1683 }
1684 if (!IsUint(16, actual_count)) {
1685 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1686 return false;
1687 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001688 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001689 CHECK_LE(actual_count, max_count);
1690 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001691 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001692 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001693 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001694 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001695 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001696 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001697 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001698 LG << "Too many methods"; // TODO: VirtualMachineError
1699 return false;
1700 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001701 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001702 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001703 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1704 vtable->Set(i, virtual_method);
1705 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001706 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001707 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001708 }
1709 return true;
1710}
1711
1712bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001713 int miranda_count = 0;
1714 int miranda_alloc = 0;
1715 size_t super_ifcount;
1716 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001717 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001718 } else {
1719 super_ifcount = 0;
1720 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001721 size_t ifcount = super_ifcount;
1722 ifcount += klass->NumInterfaces();
1723 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001724 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001725 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001726 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001727 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001728 // DCHECK(klass->GetIfTableCount() == 0);
1729 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001730 return true;
1731 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001732 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001733 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001734 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1735 for (size_t i = 0; i < super_ifcount; i++) {
1736 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1737 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001738 }
1739 // Flatten the interface inheritance hierarchy.
1740 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001741 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001742 Class* interface = klass->GetInterface(i);
1743 DCHECK(interface != NULL);
1744 if (!interface->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001745 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1746 return false;
1747 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001748 iftable->Set(idx++, AllocInterfaceEntry(interface));
1749 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1750 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001751 }
1752 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001753 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001754 CHECK_EQ(idx, ifcount);
Brian Carlstrom86927212011-09-15 11:31:11 -07001755 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001756 return true;
1757 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001758 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001759 for (size_t i = 0; i < ifcount; ++i) {
1760 InterfaceEntry* interface_entry = iftable->Get(i);
1761 Class* interface = interface_entry->GetInterface();
1762 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1763 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001764 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001765 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1766 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001767 int32_t k;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001768 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1769 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001770 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1771 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001772 LG << "Implementation not public";
1773 return false;
1774 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001775 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001776 break;
1777 }
1778 }
1779 if (k < 0) {
1780 if (miranda_count == miranda_alloc) {
1781 miranda_alloc += 8;
1782 if (miranda_list.empty()) {
1783 miranda_list.resize(miranda_alloc);
1784 } else {
1785 miranda_list.resize(miranda_alloc);
1786 }
1787 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001788 Method* miranda_method = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001789 int mir;
1790 for (mir = 0; mir < miranda_count; mir++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001791 miranda_method = miranda_list[mir];
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001792 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001793 break;
1794 }
1795 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001796 // point the interface table at a phantom slot
1797 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001798 if (mir == miranda_count) {
1799 miranda_list[miranda_count++] = interface_method;
1800 }
1801 }
1802 }
1803 }
1804 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001805 int old_method_count = klass->NumVirtualMethods();
1806 int new_method_count = old_method_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001807 klass->SetVirtualMethods(
1808 klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001809
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001810 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1811 CHECK(vtable != NULL);
1812 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001813 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001814 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001815 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001816 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001817 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001818 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001819 meth->SetDeclaringClass(klass);
1820 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1821 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001822 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001823 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001824 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001825 // TODO: do not assign to the vtable field until it is fully constructed.
1826 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001827 }
1828 return true;
1829}
1830
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001831bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001832 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001833 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001834}
1835
1836bool ClassLinker::LinkStaticFields(Class* klass) {
1837 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001838 size_t allocated_class_size = klass->GetClassSize();
1839 bool success = LinkFields(klass, false);
1840 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001841 return success;
1842}
1843
Brian Carlstromdbc05252011-09-09 01:59:59 -07001844struct LinkFieldsComparator {
1845 bool operator()(const Field* field1, const Field* field2){
1846
1847 // First come reference fields, then 64-bit, and finally 32-bit
1848 const Class* type1 = field1->GetTypeDuringLinking();
1849 const Class* type2 = field2->GetTypeDuringLinking();
1850 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
1851 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
1852 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
1853 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
1854 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
1855 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
1856 if (order1 != order2) {
1857 return order1 < order2;
1858 }
1859
1860 // same basic group? then sort by string.
1861 std::string name1 = field1->GetName()->ToModifiedUtf8();
1862 std::string name2 = field2->GetName()->ToModifiedUtf8();
1863 return name1 < name2;
1864 }
1865};
1866
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001867bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001868 size_t num_fields =
1869 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1870
1871 ObjectArray<Field>* fields =
1872 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001873
1874 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07001875 size_t size;
1876 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001877 if (instance) {
1878 Class* super_class = klass->GetSuperClass();
1879 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001880 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001881 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001882 }
1883 size = field_offset.Uint32Value();
1884 } else {
1885 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07001886 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001887 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001888
Brian Carlstromdbc05252011-09-09 01:59:59 -07001889 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001890
Brian Carlstromdbc05252011-09-09 01:59:59 -07001891 // we want a relatively stable order so that adding new fields
1892 // minimizes distruption of C++ version such as Class and Method.
1893 std::deque<Field*> grouped_and_sorted_fields;
1894 for (size_t i = 0; i < num_fields; i++) {
1895 grouped_and_sorted_fields.push_back(fields->Get(i));
1896 }
1897 std::sort(grouped_and_sorted_fields.begin(),
1898 grouped_and_sorted_fields.end(),
1899 LinkFieldsComparator());
1900
1901 // References should be at the front.
1902 size_t current_field = 0;
1903 size_t num_reference_fields = 0;
1904 for (; current_field < num_fields; current_field++) {
1905 Field* field = grouped_and_sorted_fields.front();
1906 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001907 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07001908 bool isPrimitive = type != NULL && type->IsPrimitive();
1909 if (isPrimitive) {
1910 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001911 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001912 grouped_and_sorted_fields.pop_front();
1913 num_reference_fields++;
1914 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001915 field->SetOffset(field_offset);
1916 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001917 }
1918
1919 // Now we want to pack all of the double-wide fields together. If
1920 // we're not aligned, though, we want to shuffle one 32-bit field
1921 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001922 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
1923 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
1924 Field* field = grouped_and_sorted_fields[i];
1925 const Class* type = field->GetTypeDuringLinking();
1926 CHECK(type != NULL); // should only be working on primitive types
1927 DCHECK(type->IsPrimitive());
1928 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
1929 continue;
1930 }
1931 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001932 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001933 // drop the consumed field
1934 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
1935 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001936 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001937 // whether we found a 32-bit field for padding or not, we advance
1938 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001939 }
1940
1941 // Alignment is good, shuffle any double-wide fields forward, and
1942 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001943 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
1944 while (!grouped_and_sorted_fields.empty()) {
1945 Field* field = grouped_and_sorted_fields.front();
1946 grouped_and_sorted_fields.pop_front();
1947 const Class* type = field->GetTypeDuringLinking();
1948 CHECK(type != NULL); // should only be working on primitive types
1949 DCHECK(type->IsPrimitive());
1950 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001951 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001952 field_offset = MemberOffset(field_offset.Uint32Value() +
1953 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
1954 ? sizeof(uint64_t)
1955 : sizeof(uint32_t)));
1956 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001957 }
1958
1959#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001960 // Make sure that all reference fields appear before
1961 // non-reference fields, and all double-wide fields are aligned.
1962 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07001963 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001964 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001965 if (false) { // enable to debug field layout
1966 LOG(INFO) << "LinkFields:"
1967 << " class=" << klass->GetDescriptor()->ToModifiedUtf8()
1968 << " field=" << field->GetName()->ToModifiedUtf8()
1969 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
1970 }
1971 const Class* type = field->GetTypeDuringLinking();
1972 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001973 if (!seen_non_ref) {
1974 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001975 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001976 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001977 } else {
1978 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001979 }
1980 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001981 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001982 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001983 }
1984#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001985 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001986 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07001987 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001988 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001989 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001990 klass->SetObjectSize(size);
1991 }
1992 } else {
1993 klass->SetNumReferenceStaticFields(num_reference_fields);
1994 klass->SetClassSize(size);
1995 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001996 return true;
1997}
1998
1999// Set the bitmap of reference offsets, refOffsets, from the ifields
2000// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002001void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002002 uint32_t reference_offsets = 0;
2003 Class* super_class = klass->GetSuperClass();
2004 if (super_class != NULL) {
2005 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002006 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002007 if (reference_offsets == CLASS_WALK_SUPER) {
2008 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002009 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002010 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002011 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002012 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002013}
2014
2015void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002016 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002017}
2018
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002019void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2020 uint32_t reference_offsets) {
2021 size_t num_reference_fields =
2022 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2023 : klass->NumReferenceStaticFieldsDuringLinking();
2024 const ObjectArray<Field>* fields =
2025 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002026 // All of the fields that contain object references are guaranteed
2027 // to be at the beginning of the fields list.
2028 for (size_t i = 0; i < num_reference_fields; ++i) {
2029 // Note that byte_offset is the offset from the beginning of
2030 // object, not the offset into instance data
2031 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002032 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002033 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2034 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2035 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002036 CHECK_NE(new_bit, 0U);
2037 reference_offsets |= new_bit;
2038 } else {
2039 reference_offsets = CLASS_WALK_SUPER;
2040 break;
2041 }
2042 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002043 // Update fields in klass
2044 if (instance) {
2045 klass->SetReferenceInstanceOffsets(reference_offsets);
2046 } else {
2047 klass->SetReferenceStaticOffsets(reference_offsets);
2048 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002049}
2050
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002051String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002052 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002053 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002054 if (resolved != NULL) {
2055 return resolved;
2056 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002057 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2058 int32_t utf16_length = dex_file.GetStringLength(string_id);
2059 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002060 // TODO: remote the const_cast below
2061 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002062 dex_cache->SetResolvedString(string_idx, string);
2063 return string;
2064}
2065
2066Class* ClassLinker::ResolveType(const DexFile& dex_file,
2067 uint32_t type_idx,
2068 DexCache* dex_cache,
2069 const ClassLoader* class_loader) {
2070 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002071 if (resolved == NULL) {
2072 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2073 if (descriptor[1] == '\0') {
2074 // only the descriptors of primitive types should be 1 character long
2075 resolved = FindPrimitiveClass(descriptor[0]);
2076 } else {
2077 resolved = FindClass(descriptor, class_loader);
2078 }
2079 if (resolved != NULL) {
2080 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2081 if (dex_cache != check->GetDexCache()) {
2082 if (check->GetClassLoader() != NULL) {
2083 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
2084 resolved = NULL;
2085 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002086 }
2087 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002088 if (resolved != NULL) {
2089 dex_cache->SetResolvedType(type_idx, resolved);
2090 } else {
2091 DCHECK(Thread::Current()->IsExceptionPending());
2092 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002093 }
2094 return resolved;
2095}
2096
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002097Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2098 uint32_t method_idx,
2099 DexCache* dex_cache,
2100 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002101 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002102 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2103 if (resolved != NULL) {
2104 return resolved;
2105 }
2106 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2107 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2108 if (klass == NULL) {
2109 return NULL;
2110 }
2111
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002112 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002113 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002114 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002115 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002116 } else if (klass->IsInterface()) {
2117 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002118 } else {
2119 resolved = klass->FindVirtualMethod(name, signature);
2120 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002121 if (resolved != NULL) {
2122 dex_cache->SetResolvedMethod(method_idx, resolved);
2123 } else {
2124 // DCHECK(Thread::Current()->IsExceptionPending());
2125 }
2126 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002127}
2128
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002129Field* ClassLinker::ResolveField(const DexFile& dex_file,
2130 uint32_t field_idx,
2131 DexCache* dex_cache,
2132 const ClassLoader* class_loader,
2133 bool is_static) {
2134 Field* resolved = dex_cache->GetResolvedField(field_idx);
2135 if (resolved != NULL) {
2136 return resolved;
2137 }
2138 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2139 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2140 if (klass == NULL) {
2141 return NULL;
2142 }
2143
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002144 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002145 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2146 // TODO: LinkageError?
2147 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002148 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002149 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002150 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002151 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002152 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002153 if (resolved != NULL) {
2154 dex_cache->SetResolvedfield(field_idx, resolved);
2155 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002156 // TODO: DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002157 }
2158 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002159}
2160
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002161void ClassLinker::DumpAllClasses(int flags) const {
2162 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2163 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2164 std::vector<Class*> all_classes;
2165 {
2166 MutexLock mu(lock_);
2167 typedef Table::const_iterator It; // TODO: C++0x auto
2168 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2169 all_classes.push_back(it->second);
2170 }
2171 }
2172
2173 for (size_t i = 0; i < all_classes.size(); ++i) {
2174 all_classes[i]->DumpClass(std::cerr, flags);
2175 }
2176}
2177
Elliott Hughese27955c2011-08-26 15:21:24 -07002178size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002179 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002180 return classes_.size();
2181}
2182
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002183} // namespace art