blob: 570d7970d2b9d1260b34815f341334b2aee2ef44 [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
Elliott Hughes90a33692011-08-30 13:27:07 -070010#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070011#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070012#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070013#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070014#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070015#include "dex_verifier.h"
16#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070017#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "logging.h"
19#include "monitor.h"
20#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070021#include "runtime.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070022#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070023#include "thread.h"
24#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 Hughescf4c6c42011-09-01 15:16:42 -070059ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path,
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070060 const std::vector<const DexFile*>& class_path,
61 InternTable* intern_table, Space* space) {
62 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -070063 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstroma663ea52011-08-19 23:33:41 -070064 if (space == NULL) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070065 class_linker->Init(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -070066 } else {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070067 class_linker->Init(boot_class_path, class_path, space);
Brian Carlstroma663ea52011-08-19 23:33:41 -070068 }
Carl Shapiro61e019d2011-07-14 16:53:09 -070069 // TODO: check for failure during initialization
70 return class_linker.release();
71}
72
Elliott Hughescf4c6c42011-09-01 15:16:42 -070073ClassLinker::ClassLinker(InternTable* intern_table)
Elliott Hughes8daa0922011-09-11 13:46:25 -070074 : classes_lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070075 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070076 array_interfaces_(NULL),
77 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -070078 init_done_(false),
79 intern_table_(intern_table) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070080}
Brian Carlstroma663ea52011-08-19 23:33:41 -070081
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070082void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
83 const std::vector<const DexFile*>& class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070084 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070085
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070086 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070087 Class* java_lang_Class = down_cast<Class*>(
88 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070089 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070090 java_lang_Class->SetClass(java_lang_Class);
91 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070092 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -070093
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070094 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -070095 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070096 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070097 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070098 java_lang_Class->SetSuperClass(java_lang_Object);
99 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700100
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700101 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700102 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700103 object_array_class->SetArrayRank(1);
104 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700105
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700106 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700107 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700108 char_array_class->SetArrayRank(1);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700109 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700110
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700111 // Setup String
112 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
113 String::SetClass(java_lang_String);
114 java_lang_String->SetObjectSize(sizeof(String));
115 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400116
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700117 // Backfill Class descriptors missing until this point
118 // TODO: intern these strings
119 java_lang_Class->SetDescriptor(
120 String::AllocFromModifiedUtf8("Ljava/lang/Class;"));
121 java_lang_Object->SetDescriptor(
122 String::AllocFromModifiedUtf8("Ljava/lang/Object;"));
123 object_array_class->SetDescriptor(
124 String::AllocFromModifiedUtf8("[Ljava/lang/Object;"));
125 java_lang_String->SetDescriptor(
126 String::AllocFromModifiedUtf8("Ljava/lang/String;"));
127 char_array_class->SetDescriptor(String::AllocFromModifiedUtf8("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700128
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700129 // Create storage for root classes, save away our work so far (requires
130 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700131 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700132 SetClassRoot(kJavaLangClass, java_lang_Class);
133 SetClassRoot(kJavaLangObject, java_lang_Object);
134 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700135 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700136 SetClassRoot(kJavaLangString, java_lang_String);
137
138 // Setup the primitive type classes.
139 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
140 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
141 SetClassRoot(kPrimitiveChar, CreatePrimitiveClass("C", Class::kPrimChar));
142 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
143 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
144 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
145 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
146 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
147 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
148
149 // Backfill component type of char[]
150 char_array_class->SetComponentType(GetClassRoot(kPrimitiveChar));
151
152 // Create array interface entries to populate once we can load system classes
153 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700154 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700155
156 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
157 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
158 int_array_class->SetArrayRank(1);
159 int_array_class->SetDescriptor(String::AllocFromModifiedUtf8("[I"));
160 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
161 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700162 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700163
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700164 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700165
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700166 // setup boot_class_path_ and register class_path now that we can
167 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700168 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700169 const DexFile* dex_file = boot_class_path[i];
170 CHECK(dex_file != NULL);
171 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700172 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700173 for (size_t i = 0; i != class_path.size(); ++i) {
174 const DexFile* dex_file = class_path[i];
175 CHECK(dex_file != NULL);
176 RegisterDexFile(*dex_file);
177 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700178
179 // Field and Method are necessary so that FindClass can link members
180 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
181 CHECK(java_lang_reflect_Field != NULL);
182 java_lang_reflect_Field->SetDescriptor(String::AllocFromModifiedUtf8("Ljava/lang/reflect/Field;"));
183 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
184 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
185 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
186 Field::SetClass(java_lang_reflect_Field);
187
188 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
189 java_lang_reflect_Method->SetDescriptor(String::AllocFromModifiedUtf8("Ljava/lang/reflect/Method;"));
190 CHECK(java_lang_reflect_Method != NULL);
191 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
192 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
193 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
194 Method::SetClass(java_lang_reflect_Method);
195
196 // now we can use FindSystemClass
197
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700198 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199 java_lang_Object->SetStatus(Class::kStatusNotReady);
200 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
201 CHECK_EQ(java_lang_Object, Object_class);
202 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
203 java_lang_String->SetStatus(Class::kStatusNotReady);
204 Class* String_class = FindSystemClass("Ljava/lang/String;");
205 CHECK_EQ(java_lang_String, String_class);
206 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
207
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700208 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700209 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
210 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
211
212 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
213 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
214
215 Class* found_char_array_class = FindSystemClass("[C");
216 CHECK_EQ(char_array_class, found_char_array_class);
217
218 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
219 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
220
221 Class* found_int_array_class = FindSystemClass("[I");
222 CHECK_EQ(int_array_class, found_int_array_class);
223
224 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
225 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
226
227 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
228 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
229
230 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
231 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
232
233 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
234 CHECK_EQ(object_array_class, found_object_array_class);
235
236 // Setup the single, global copies of "interfaces" and "iftable"
237 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
238 CHECK(java_lang_Cloneable != NULL);
239 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
240 CHECK(java_io_Serializable != NULL);
241 CHECK(array_interfaces_ != NULL);
242 array_interfaces_->Set(0, java_lang_Cloneable);
243 array_interfaces_->Set(1, java_io_Serializable);
244 // We assume that Cloneable/Serializable don't have superinterfaces --
245 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700246 // supers as well.
247 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
248 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700249
250 // Sanity check Object[]'s interfaces
251 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
252 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700253
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700254 // run Class, Field, and Method through FindSystemClass.
255 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700256 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700257 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258 // No sanity check on size as Class is variably sized
259
260 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700261 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700262 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263
264 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700265 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700266 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700267
268 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
269 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 java_lang_ref_FinalizerReference->SetAccessFlags(
271 java_lang_ref_FinalizerReference->GetAccessFlags() |
272 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700273 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700274 java_lang_ref_PhantomReference->SetAccessFlags(
275 java_lang_ref_PhantomReference->GetAccessFlags() |
276 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700277 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700278 java_lang_ref_SoftReference->SetAccessFlags(
279 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700280 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700281 java_lang_ref_WeakReference->SetAccessFlags(
282 java_lang_ref_WeakReference->GetAccessFlags() |
283 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700284
285 // Let the heap know some key offsets into java.lang.ref instances
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700286 // NB we hard code the field indexes here rather than using FindInstanceField
287 // as the types of the field can't be resolved prior to the runtime being
288 // fully initialized
Brian Carlstrom1f870082011-08-23 16:02:11 -0700289 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700290
291 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
292 CHECK(pendingNext->GetName()->Equals("pendingNext"));
293 CHECK(ResolveType(pendingNext->GetTypeIdx(), pendingNext) ==
294 java_lang_ref_Reference);
295
296 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
297 CHECK(queue->GetName()->Equals("queue"));
298 CHECK(ResolveType(queue->GetTypeIdx(), queue) ==
299 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
300
301 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
302 CHECK(queueNext->GetName()->Equals("queueNext"));
303 CHECK(ResolveType(queueNext->GetTypeIdx(), queueNext) ==
304 java_lang_ref_Reference);
305
306 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
307 CHECK(referent->GetName()->Equals("referent"));
308 CHECK(ResolveType(referent->GetTypeIdx(), referent) ==
309 java_lang_Object);
310
311 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
312 CHECK(zombie->GetName()->Equals("zombie"));
313 CHECK(ResolveType(zombie->GetTypeIdx(), zombie) ==
314 java_lang_Object);
315
Brian Carlstrom1f870082011-08-23 16:02:11 -0700316 Heap::SetReferenceOffsets(referent->GetOffset(),
317 queue->GetOffset(),
318 queueNext->GetOffset(),
319 pendingNext->GetOffset(),
320 zombie->GetOffset());
321
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322 // Setup the ClassLoaders, adjusting the object_size_ as necessary
323 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
324 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
325 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
326 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
327
328 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
329 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
330 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
331
332 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
333 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
334 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
335 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
336
337 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700338 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
339 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700340 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700341
Brian Carlstroma663ea52011-08-19 23:33:41 -0700342 FinishInit();
343}
344
345void ClassLinker::FinishInit() {
346 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700347 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700348 ClassRoot class_root = static_cast<ClassRoot>(i);
349 Class* klass = GetClassRoot(class_root);
350 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700352 // note SetClassRoot does additional validation.
353 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700354 }
355
356 // disable the slow paths in FindClass and CreatePrimitiveClass now
357 // that Object, Class, and Object[] are setup
358 init_done_ = true;
359}
360
Brian Carlstroma663ea52011-08-19 23:33:41 -0700361struct ClassLinker::InitCallbackState {
362 ClassLinker* class_linker;
363
364 Class* class_roots[kClassRootsMax];
365
366 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
367 Table descriptor_to_class_root;
368
Brian Carlstroma663ea52011-08-19 23:33:41 -0700369 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
370 Set dex_caches;
371};
372
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700373void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
374 const std::vector<const DexFile*>& class_path,
375 Space* space) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700376 CHECK(!init_done_);
377
378 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
379 DCHECK(heap_bitmap != NULL);
380
381 InitCallbackState state;
382 state.class_linker = this;
383 for (size_t i = 0; i < kClassRootsMax; i++) {
384 ClassRoot class_root = static_cast<ClassRoot>(i);
385 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
386 }
387
388 // reinit clases_ table
389 heap_bitmap->Walk(InitCallback, &state);
390
391 // reinit class_roots_
392 Class* object_array_class = state.class_roots[kObjectArrayClass];
393 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
394 for (size_t i = 0; i < kClassRootsMax; i++) {
395 ClassRoot class_root = static_cast<ClassRoot>(i);
396 SetClassRoot(class_root, state.class_roots[class_root]);
397 }
398
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700399 // reinit intern table
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700400 // TODO: remove interned_array, make all strings in image interned (and remove space argument)
Brian Carlstroma663ea52011-08-19 23:33:41 -0700401 ObjectArray<Object>* interned_array = space->GetImageHeader().GetInternedArray();
402 for (int32_t i = 0; i < interned_array->GetLength(); i++) {
403 String* string = interned_array->Get(i)->AsString();
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700404 intern_table_->RegisterStrong(string);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700405 }
406
407 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700408 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
409 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700410
411 // build a map from location to DexCache to match up with DexFile::GetLocation
412 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413 typedef InitCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700414 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
415 DexCache* dex_cache = *it;
416 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
417 location_to_dex_cache[location] = dex_cache;
418 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700419 CHECK_EQ(boot_class_path.size() + class_path.size(),
420 location_to_dex_cache.size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700421
422 // reinit boot_class_path with DexFile arguments and found DexCaches
423 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700424 const DexFile* dex_file = boot_class_path[i];
425 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700426 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700427 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700428 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700429 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700430
431 // register class_path with DexFile arguments and found DexCaches
432 for (size_t i = 0; i != class_path.size(); ++i) {
433 const DexFile* dex_file = class_path[i];
434 CHECK(dex_file != NULL);
435 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
436 CHECK(dex_cache != NULL) << dex_file->GetLocation();
437 RegisterDexFile(*dex_file, dex_cache);
438 }
439
Brian Carlstroma663ea52011-08-19 23:33:41 -0700440 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441 Field::SetClass(GetClassRoot(kJavaLangReflectField));
442 Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700443 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
444 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
445 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
446 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
447 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
448 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
449 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
450 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700451 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700452 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700453
454 FinishInit();
455}
456
Brian Carlstrom4873d462011-08-21 15:23:39 -0700457void ClassLinker::InitCallback(Object* obj, void *arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700458 DCHECK(obj != NULL);
459 DCHECK(arg != NULL);
460 InitCallbackState* state = reinterpret_cast<InitCallbackState*>(arg);
461
462 if (!obj->IsClass()) {
463 return;
464 }
465 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700466 // TODO: restore ClassLoader's list of DexFiles after image load
467 // CHECK(klass->GetClassLoader() == NULL);
468 const ClassLoader* class_loader = klass->GetClassLoader();
469 if (class_loader != NULL) {
470 // TODO: replace this hack with something based on command line arguments
471 Thread::Current()->SetClassLoaderOverride(class_loader);
472 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700473
474 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700475 // restore class to ClassLinker::classes_ table
476 state->class_linker->InsertClass(descriptor, klass);
477
478 // note DexCache to match with DexFile later
479 DexCache* dex_cache = klass->GetDexCache();
480 if (dex_cache != NULL) {
481 state->dex_caches.insert(dex_cache);
482 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700483 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700484 }
485
486 // check if this is a root, if so, register it
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700487 typedef InitCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700488 It it = state->descriptor_to_class_root.find(descriptor);
489 if (it != state->descriptor_to_class_root.end()) {
490 ClassRoot class_root = it->second;
491 state->class_roots[class_root] = klass;
492 }
493}
494
495// Keep in sync with InitCallback. Anything we visit, we need to
496// reinit references to when reinitializing a ClassLinker from a
497// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700498void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
499 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700500
501 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700502 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700503 }
504
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700505 {
506 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700508 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700509 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700510 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700511 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700512
Elliott Hughes410c0c82011-09-01 17:58:25 -0700513 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700514}
515
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700516ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700517 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700518 Field::ResetClass();
519 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700520 BooleanArray::ResetArrayClass();
521 ByteArray::ResetArrayClass();
522 CharArray::ResetArrayClass();
523 DoubleArray::ResetArrayClass();
524 FloatArray::ResetArrayClass();
525 IntArray::ResetArrayClass();
526 LongArray::ResetArrayClass();
527 ShortArray::ResetArrayClass();
528 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700529 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700530}
531
532DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700533 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700534 dex_cache->Init(String::AllocFromModifiedUtf8(dex_file.GetLocation().c_str()),
535 AllocObjectArray<String>(dex_file.NumStringIds()),
536 AllocObjectArray<Class>(dex_file.NumTypeIds()),
537 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700538 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700539 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
540 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700541 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700542}
543
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700544CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
545 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700546}
547
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700548InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
549 DCHECK(interface->IsInterface());
550 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
551 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
552 interface_entry->SetInterface(interface);
553 return interface_entry;
554}
555
Brian Carlstrom4873d462011-08-21 15:23:39 -0700556Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
557 DCHECK_GE(class_size, sizeof(Class));
558 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700559 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
560 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700561 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700562}
563
Brian Carlstrom4873d462011-08-21 15:23:39 -0700564Class* ClassLinker::AllocClass(size_t class_size) {
565 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700566}
567
Jesse Wilson35baaab2011-08-10 16:18:03 -0400568Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700569 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700570}
571
572Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700573 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700574}
575
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700576ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
577 return ObjectArray<StackTraceElement>::Alloc(
578 GetClassRoot(kJavaLangStackTraceElementArrayClass),
579 length);
580}
581
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700582Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700583 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700584 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700585 if (class_loader != NULL) {
586 Class* klass = FindClass(descriptor, NULL);
587 if (klass != NULL) {
588 return klass;
589 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700590 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700591 }
592
Carl Shapirob5573532011-07-12 18:22:59 -0700593 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700594 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700595 CHECK(!self->IsExceptionPending());
596 // Find the class in the loaded classes table.
597 Class* klass = LookupClass(descriptor, class_loader);
598 if (klass == NULL) {
599 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700600 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700601 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700602 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700603 const DexFile::ClassPath& class_path = ((class_loader != NULL)
604 ? ClassLoader::GetClassPath(class_loader)
605 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700606 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700607 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700608 std::string name(PrintableString(descriptor));
609 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
610 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700611 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700612 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700613 const DexFile& dex_file = *pair.first;
614 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700615 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700616 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700617 if (!init_done_) {
618 // finish up init of hand crafted class_roots_
619 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700620 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700621 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700622 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400623 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700624 klass = GetClassRoot(kJavaLangString);
625 } else if (descriptor == "Ljava/lang/reflect/Field;") {
626 klass = GetClassRoot(kJavaLangReflectField);
627 } else if (descriptor == "Ljava/lang/reflect/Method;") {
628 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700629 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700630 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700631 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700632 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700633 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700634 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700635 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700636 klass->SetDexCache(dex_cache);
637 LoadClass(dex_file, dex_class_def, klass, class_loader);
638 // Check for a pending exception during load
639 if (self->IsExceptionPending()) {
640 // TODO: free native allocations in klass
641 return NULL;
642 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700643 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700644 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700645 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700646 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700647 if (!success) {
648 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700650 // TODO: free native allocations in klass
651 klass = LookupClass(descriptor, class_loader);
652 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700653 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700654 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700655 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700656 CHECK(!klass->IsLoaded());
657 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700658 // Loading failed.
659 // TODO: CHECK(self->IsExceptionPending());
660 lock.NotifyAll();
661 return NULL;
662 }
663 CHECK(klass->IsLoaded());
664 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700665 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700666 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700667 // Linking failed.
668 // TODO: CHECK(self->IsExceptionPending());
669 lock.NotifyAll();
670 return NULL;
671 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700672 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700673 }
674 }
675 }
676 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700677 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700678 ObjectLock lock(klass);
679 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700680 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700681 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700682 return NULL;
683 }
684 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700685 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700686 lock.Wait();
687 }
688 }
689 if (klass->IsErroneous()) {
690 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
691 return NULL;
692 }
693 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700694 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700695 CHECK(!self->IsExceptionPending());
696 return klass;
697}
698
Brian Carlstrom4873d462011-08-21 15:23:39 -0700699// Precomputes size that will be needed for Class, matching LinkStaticFields
700size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
701 const DexFile::ClassDef& dex_class_def) {
702 const byte* class_data = dex_file.GetClassData(dex_class_def);
703 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
704 size_t num_static_fields = header.static_fields_size_;
705 size_t num_ref = 0;
706 size_t num_32 = 0;
707 size_t num_64 = 0;
708 if (num_static_fields != 0) {
709 uint32_t last_idx = 0;
710 for (size_t i = 0; i < num_static_fields; ++i) {
711 DexFile::Field dex_field;
712 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
713 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
714 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
715 char c = descriptor[0];
716 if (c == 'L' || c == '[') {
717 num_ref++;
718 } else if (c == 'J' || c == 'D') {
719 num_64++;
720 } else {
721 num_32++;
722 }
723 }
724 }
725
726 // start with generic class data
727 size_t size = sizeof(Class);
728 // follow with reference fields which must be contiguous at start
729 size += (num_ref * sizeof(uint32_t));
730 // if there are 64-bit fields to add, make sure they are aligned
731 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
732 if (num_32 != 0) {
733 // use an available 32-bit field for padding
734 num_32--;
735 }
736 size += sizeof(uint32_t); // either way, we are adding a word
737 DCHECK_EQ(size, RoundUp(size, 8));
738 }
739 // tack on any 64-bit fields now that alignment is assured
740 size += (num_64 * sizeof(uint64_t));
741 // tack on any remaining 32-bit fields
742 size += (num_32 * sizeof(uint32_t));
743 return size;
744}
745
Brian Carlstromf615a612011-07-23 12:50:34 -0700746void ClassLinker::LoadClass(const DexFile& dex_file,
747 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700748 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700749 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700750 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700751 CHECK(klass->GetDexCache() != NULL);
752 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700753 const byte* class_data = dex_file.GetClassData(dex_class_def);
754 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700755
Brian Carlstromf615a612011-07-23 12:50:34 -0700756 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700757 CHECK(descriptor != NULL);
758
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700759 klass->SetClass(GetClassRoot(kJavaLangClass));
760 if (klass->GetDescriptor() != NULL) {
761 DCHECK(klass->GetDescriptor()->Equals(descriptor));
762 } else {
763 klass->SetDescriptor(String::AllocFromModifiedUtf8(descriptor));
764 }
765 uint32_t access_flags = dex_class_def.access_flags_;
766 // Make sure there aren't any "bonus" flags set, since we use them for runtime
767 // state.
768 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
769 klass->SetAccessFlags(access_flags);
770 klass->SetClassLoader(class_loader);
771 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
772 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700773
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700774 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700775
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700776 size_t num_static_fields = header.static_fields_size_;
777 size_t num_instance_fields = header.instance_fields_size_;
778 size_t num_direct_methods = header.direct_methods_size_;
779 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700780
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700781 klass->SetSourceFile(String::AllocFromModifiedUtf8(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700782
783 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700784 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700785
786 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700787 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700788 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700789 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700790 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700791 DexFile::Field dex_field;
792 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400793 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700794 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700795 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700796 }
797 }
798
799 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700800 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700801 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700802 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700803 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700804 DexFile::Field dex_field;
805 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400806 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700807 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700808 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700809 }
810 }
811
812 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700813 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700814 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700815 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700816 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700817 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700818 DexFile::Method dex_method;
819 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700820 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700821 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700822 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700823 // TODO: register maps
824 }
825 }
826
827 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700828 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700829 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700830 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700831 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700832 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700833 DexFile::Method dex_method;
834 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700835 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700836 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700837 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700838 // TODO: register maps
839 }
840 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700841}
842
Brian Carlstromf615a612011-07-23 12:50:34 -0700843void ClassLinker::LoadInterfaces(const DexFile& dex_file,
844 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700845 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700846 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700847 if (list != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700848 klass->SetInterfaces(AllocObjectArray<Class>(list->Size()));
849 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
850 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700851 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700852 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700853 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700854 }
855 }
856}
857
Brian Carlstromf615a612011-07-23 12:50:34 -0700858void ClassLinker::LoadField(const DexFile& dex_file,
859 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700860 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700861 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700862 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700863 dst->SetDeclaringClass(klass);
864 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
865 dst->SetTypeIdx(field_id.type_idx_);
866 dst->SetAccessFlags(src.access_flags_);
867
868 // In order to access primitive types using GetTypeDuringLinking we need to
869 // ensure they are resolved into the dex cache
870 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
871 if (descriptor[1] == '\0') {
872 // only the descriptors of primitive types should be 1 character long
873 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
874 DCHECK(resolved->IsPrimitive());
875 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700876}
877
Brian Carlstromf615a612011-07-23 12:50:34 -0700878void ClassLinker::LoadMethod(const DexFile& dex_file,
879 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700880 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700881 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700882 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700883 dst->SetDeclaringClass(klass);
884 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700885 {
886 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700887 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700888 dst->SetSignature(String::AllocFromModifiedUtf8(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700889 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700890 dst->SetProtoIdx(method_id.proto_idx_);
891 dst->SetCodeItemOffset(src.code_off_);
892 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700893 dst->SetShorty(String::AllocFromModifiedUtf8(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700894 dst->SetAccessFlags(src.access_flags_);
895 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700896
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700897 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
898 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
899 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
900 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
901 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
902 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700903
Brian Carlstrom934486c2011-07-12 23:42:50 -0700904 // TODO: check for finalize method
905
Brian Carlstromf615a612011-07-23 12:50:34 -0700906 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700907 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700908 dst->SetNumRegisters(code_item->registers_size_);
909 dst->SetNumIns(code_item->ins_size_);
910 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700911 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700912 uint16_t num_args = Method::NumArgRegisters(shorty);
913 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700914 ++num_args;
915 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700916 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700917 // TODO: native methods
918 }
919}
920
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700921void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700922 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
923}
924
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700925void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700926 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700927 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700928 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700929}
930
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700931void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700932 RegisterDexFile(dex_file, AllocDexCache(dex_file));
933}
934
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700935void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700936 CHECK(dex_cache != NULL) << dex_file.GetLocation();
937 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700938 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700939 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700940}
941
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700942const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700943 for (size_t i = 0; i != dex_caches_.size(); ++i) {
944 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700945 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700946 }
947 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700948 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700949 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700950}
951
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700952DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstromf615a612011-07-23 12:50:34 -0700953 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700954 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700955 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700956 }
957 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700958 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700959 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700960}
961
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700962Class* ClassLinker::CreatePrimitiveClass(const char* descriptor,
963 Class::PrimitiveType type) {
964 // TODO: deduce one argument from the other
Brian Carlstrom4873d462011-08-21 15:23:39 -0700965 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700966 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700967 klass->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
968 klass->SetDescriptor(String::AllocFromModifiedUtf8(descriptor));
969 klass->SetPrimitiveType(type);
970 klass->SetStatus(Class::kStatusInitialized);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700971 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700972 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700973 return klass;
974}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700975
Brian Carlstrombe977852011-07-19 14:54:54 -0700976// Create an array class (i.e. the class object for the array, not the
977// array itself). "descriptor" looks like "[C" or "[[[[B" or
978// "[Ljava/lang/String;".
979//
980// If "descriptor" refers to an array of primitives, look up the
981// primitive type's internally-generated class object.
982//
983// "loader" is the class loader of the class that's referring to us. It's
984// used to ensure that we're looking for the element type in the right
985// context. It does NOT become the class loader for the array class; that
986// always comes from the base element class.
987//
988// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700989Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700990 const ClassLoader* class_loader) {
991 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700992
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700993 // Identify the underlying element class and the array dimension depth.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700994 Class* component_type = NULL;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700995 int array_rank;
996 if (descriptor[1] == '[') {
997 // array of arrays; keep descriptor and grab stuff from parent
998 Class* outer = FindClass(descriptor.substr(1), class_loader);
999 if (outer != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001000 // want the base class, not "outer", in our component_type
1001 component_type = outer->GetComponentType();
1002 array_rank = outer->GetArrayRank() + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001003 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001004 DCHECK(component_type == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001005 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001006 } else {
1007 array_rank = 1;
1008 if (descriptor[1] == 'L') {
1009 // array of objects; strip off "[" and look up descriptor.
1010 const StringPiece subDescriptor = descriptor.substr(1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001011 component_type = FindClass(subDescriptor, class_loader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001012 } else {
1013 // array of a primitive type
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001014 component_type = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001015 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001016 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001017
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001018 if (component_type == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001019 // failed
1020 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
1021 return NULL;
1022 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001023
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001024 // See if the component type is already loaded. Array classes are
1025 // always associated with the class loader of their underlying
1026 // element type -- an array of Strings goes with the loader for
1027 // java/lang/String -- so we need to look for it there. (The
1028 // caller should have checked for the existence of the class
1029 // before calling here, but they did so with *their* class loader,
1030 // not the component type's loader.)
1031 //
1032 // If we find it, the caller adds "loader" to the class' initiating
1033 // loader list, which should prevent us from going through this again.
1034 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001035 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001036 // are the same, because our caller (FindClass) just did the
1037 // lookup. (Even if we get this wrong we still have correct behavior,
1038 // because we effectively do this lookup again when we add the new
1039 // class to the hash table --- necessary because of possible races with
1040 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001041 if (class_loader != component_type->GetClassLoader()) {
1042 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001043 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001044 return new_class;
1045 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001046 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001047
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001048 // Fill out the fields in the Class.
1049 //
1050 // It is possible to execute some methods against arrays, because
1051 // all arrays are subclasses of java_lang_Object_, so we need to set
1052 // up a vtable. We can just point at the one in java_lang_Object_.
1053 //
1054 // Array classes are simple enough that we don't need to do a full
1055 // link step.
1056
1057 Class* new_class = NULL;
1058 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001059 // Classes that were hand created, ie not by FindSystemClass
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001060 if (descriptor == "[Ljava/lang/Object;") {
1061 new_class = GetClassRoot(kObjectArrayClass);
1062 } else if (descriptor == "[C") {
1063 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001064 } else if (descriptor == "[I") {
1065 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001066 }
1067 }
1068 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001069 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001070 if (new_class == NULL) {
1071 return NULL;
1072 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001073 new_class->SetArrayRank(array_rank);
1074 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001075 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001076 DCHECK_LE(1, new_class->GetArrayRank());
1077 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001078 if (new_class->GetDescriptor() != NULL) {
1079 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1080 } else {
1081 new_class->SetDescriptor(String::AllocFromModifiedUtf8(descriptor.ToString().c_str()));
1082 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001083 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001084 new_class->SetSuperClass(java_lang_Object);
1085 new_class->SetVTable(java_lang_Object->GetVTable());
1086 new_class->SetPrimitiveType(Class::kPrimNot);
1087 new_class->SetClassLoader(component_type->GetClassLoader());
1088 new_class->SetStatus(Class::kStatusInitialized);
1089 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001090 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001091
1092
1093 // All arrays have java/lang/Cloneable and java/io/Serializable as
1094 // interfaces. We need to set that up here, so that stuff like
1095 // "instanceof" works right.
1096 //
1097 // Note: The GC could run during the call to FindSystemClass,
1098 // so we need to make sure the class object is GC-valid while we're in
1099 // there. Do this by clearing the interface list so the GC will just
1100 // think that the entries are null.
1101
1102
1103 // Use the single, global copies of "interfaces" and "iftable"
1104 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001105 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001106 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001107
1108 // Inherit access flags from the component type. Arrays can't be
1109 // used as a superclass or interface, so we want to add "final"
1110 // and remove "interface".
1111 //
1112 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001113 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001114 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001115 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1116 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001117
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001118 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001119 return new_class;
1120 }
1121 // Another thread must have loaded the class after we
1122 // started but before we finished. Abandon what we've
1123 // done.
1124 //
1125 // (Yes, this happens.)
1126
1127 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001128 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001129 DCHECK(other_class != NULL);
1130 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001131}
1132
1133Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001134 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001135 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001136 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001137 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001138 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001139 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001140 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001141 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001142 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001143 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001144 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001145 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001146 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001147 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001148 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001149 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001150 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001151 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001152 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001153 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001154 std::string printable_type(PrintableChar(type));
1155 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1156 "Not a primitive type: %s", printable_type.c_str());
1157 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001158}
1159
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001160bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1161 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001162 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001163 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001164 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001165}
1166
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001167Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001168 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001169 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001170 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001171 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001172 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001173 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001174 return klass;
1175 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001176 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001177 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001178}
1179
1180bool ClassLinker::InitializeClass(Class* klass) {
1181 CHECK(klass->GetStatus() == Class::kStatusResolved ||
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001182 klass->GetStatus() == Class::kStatusInitializing ||
1183 klass->GetStatus() == Class::kStatusError)
1184 << PrettyDescriptor(klass->GetDescriptor()) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001185
Carl Shapirob5573532011-07-12 18:22:59 -07001186 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001187
1188 {
1189 ObjectLock lock(klass);
1190
1191 if (klass->GetStatus() < Class::kStatusVerified) {
1192 if (klass->IsErroneous()) {
1193 LG << "re-initializing failed class"; // TODO: throw
1194 return false;
1195 }
1196
1197 CHECK(klass->GetStatus() == Class::kStatusResolved);
1198
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001199 klass->SetStatus(Class::kStatusVerifying);
jeffhaobdb76512011-09-07 11:43:16 -07001200 if (!DexVerifier::VerifyClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001201 LG << "Verification failed"; // TODO: ThrowVerifyError
1202 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001203 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001204 klass->SetStatus(Class::kStatusError);
1205 return false;
1206 }
1207
1208 klass->SetStatus(Class::kStatusVerified);
1209 }
1210
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001211 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001212 return true;
1213 }
1214
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001215 while (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001216 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001217 if (klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001218 // Yes. That's fine.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001219 return true;
1220 }
1221
1222 CHECK(!self->IsExceptionPending());
1223
1224 lock.Wait(); // TODO: check for interruption
1225
1226 // When we wake up, repeat the test for init-in-progress. If
1227 // there's an exception pending (only possible if
1228 // "interruptShouldThrow" was set), bail out.
1229 if (self->IsExceptionPending()) {
1230 CHECK(false);
1231 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1232 klass->SetStatus(Class::kStatusError);
1233 return false;
1234 }
1235 if (klass->GetStatus() == Class::kStatusInitializing) {
1236 continue;
1237 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001238 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001239 klass->GetStatus() == Class::kStatusError);
1240 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001241 // The caller wants an exception, but it was thrown in a
1242 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001243 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1244 return false;
1245 }
1246 return true; // otherwise, initialized
1247 }
1248
1249 // see if we failed previously
1250 if (klass->IsErroneous()) {
1251 // might be wise to unlock before throwing; depends on which class
1252 // it is that we have locked
1253
1254 // TODO: throwEarlierClassFailure(klass);
1255 return false;
1256 }
1257
1258 if (!ValidateSuperClassDescriptors(klass)) {
1259 klass->SetStatus(Class::kStatusError);
1260 return false;
1261 }
1262
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001263 DCHECK(klass->GetStatus() < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001264
Elliott Hughesdcc24742011-09-07 14:02:44 -07001265 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001266 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001267 }
1268
1269 if (!InitializeSuperClass(klass)) {
1270 return false;
1271 }
1272
1273 InitializeStaticFields(klass);
1274
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001275 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001276 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001277 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001278 }
1279
1280 {
1281 ObjectLock lock(klass);
1282
1283 if (self->IsExceptionPending()) {
1284 klass->SetStatus(Class::kStatusError);
1285 } else {
1286 klass->SetStatus(Class::kStatusInitialized);
1287 }
1288 lock.NotifyAll();
1289 }
1290
1291 return true;
1292}
1293
1294bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1295 if (klass->IsInterface()) {
1296 return true;
1297 }
1298 // begin with the methods local to the superclass
1299 if (klass->HasSuperClass() &&
1300 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1301 const Class* super = klass->GetSuperClass();
1302 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001303 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001304 if (method != super->GetVirtualMethod(i) &&
1305 !HasSameMethodDescriptorClasses(method, super, klass)) {
1306 LG << "Classes resolve differently in superclass";
1307 return false;
1308 }
1309 }
1310 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001311 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1312 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1313 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001314 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1315 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001316 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001317 if (!HasSameMethodDescriptorClasses(method, interface,
1318 method->GetClass())) {
1319 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1320 return false;
1321 }
1322 }
1323 }
1324 }
1325 return true;
1326}
1327
1328bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001329 const Class* klass1,
1330 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001331 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001332 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001333 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001334 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001335 const char* descriptor = it->GetDescriptor();
1336 if (descriptor == NULL) {
1337 break;
1338 }
1339 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1340 // Found a non-primitive type.
1341 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1342 return false;
1343 }
1344 }
1345 }
1346 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001347 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001348 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1349 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1350 return false;
1351 }
1352 }
1353 return true;
1354}
1355
1356// Returns true if classes referenced by the descriptor are the
1357// same classes in klass1 as they are in klass2.
1358bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001359 const Class* klass1,
1360 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001361 CHECK(descriptor != NULL);
1362 CHECK(klass1 != NULL);
1363 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001364 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001365 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001366 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001367 // TODO: found2 == NULL
1368 // TODO: lookup found1 in initiating loader list
1369 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001370 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001371 if (found1 == found2) {
1372 return true;
1373 } else {
1374 return false;
1375 }
1376 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001377 return true;
1378}
1379
1380bool ClassLinker::InitializeSuperClass(Class* klass) {
1381 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001382 if (!klass->IsInterface() && klass->HasSuperClass()) {
1383 Class* super_class = klass->GetSuperClass();
1384 if (super_class->GetStatus() != Class::kStatusInitialized) {
1385 CHECK(!super_class->IsInterface());
1386 klass->MonitorExit();
1387 bool super_initialized = InitializeClass(super_class);
1388 klass->MonitorEnter();
1389 // TODO: check for a pending exception
1390 if (!super_initialized) {
1391 klass->SetStatus(Class::kStatusError);
1392 klass->NotifyAll();
1393 return false;
1394 }
1395 }
1396 }
1397 return true;
1398}
1399
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001400bool ClassLinker::EnsureInitialized(Class* c) {
1401 CHECK(c != NULL);
1402 if (c->IsInitialized()) {
1403 return true;
1404 }
1405
1406 c->MonitorExit();
1407 InitializeClass(c);
1408 c->MonitorEnter();
1409 return !Thread::Current()->IsExceptionPending();
1410}
1411
Brian Carlstromb9edb842011-08-28 16:31:06 -07001412StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1413 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001414 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1415 Class* klass = class_linker->ResolveType(type_idx, referrer);
1416 if (klass == NULL) {
1417 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1418 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001419 // If we are the <clinit> of this class, just return our storage.
1420 //
1421 // Do not set the DexCache InitializedStaticStorage, since that
1422 // implies <clinit> has finished running.
1423 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1424 return klass;
1425 }
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001426 if (!class_linker->EnsureInitialized(klass)) {
1427 CHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001428 UNIMPLEMENTED(FATAL) << "throw exception due to class initialization problem";
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001429 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001430 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001431 return klass;
1432}
1433
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001434void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1435 Class* c, std::map<int, Field*>& field_map) {
1436 const ClassLoader* cl = c->GetClassLoader();
1437 const byte* class_data = dex_file.GetClassData(dex_class_def);
1438 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1439 uint32_t last_idx = 0;
1440 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1441 DexFile::Field dex_field;
1442 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1443 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1444 }
1445}
1446
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001447void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001448 size_t num_static_fields = klass->NumStaticFields();
1449 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001450 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001451 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001452 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001453 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001454 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001455 return;
1456 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001457 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001458 const DexFile& dex_file = FindDexFile(dex_cache);
1459 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001460 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001461
1462 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1463 std::map<int, Field*> field_map;
1464 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1465
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001466 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001467 if (addr == NULL) {
1468 // All this class' static fields have default values.
1469 return;
1470 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001471 size_t array_size = DecodeUnsignedLeb128(&addr);
1472 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001473 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001474 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001475 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001476 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001477 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001478 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001479 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001480 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001481 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001482 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001483 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001484 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001485 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001486 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001487 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001488 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001489 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001490 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001491 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001492 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001493 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001494 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001495 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001496 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001497 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001498 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001499 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001500 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001501 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001502 break;
1503 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001504 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001505 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001506 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001507 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001508 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001509 break;
1510 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001511 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001512 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001513 }
1514}
1515
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001516bool ClassLinker::LinkClass(Class* klass) {
1517 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001518 if (!LinkSuperClass(klass)) {
1519 return false;
1520 }
1521 if (!LinkMethods(klass)) {
1522 return false;
1523 }
1524 if (!LinkInstanceFields(klass)) {
1525 return false;
1526 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001527 if (!LinkStaticFields(klass)) {
1528 return false;
1529 }
1530 CreateReferenceInstanceOffsets(klass);
1531 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001532 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1533 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001534 return true;
1535}
1536
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001537bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001538 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1539 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1540 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001541 if (super_class == NULL) {
1542 LG << "Failed to resolve superclass";
1543 return false;
1544 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001545 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001546 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001547 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1548 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1549 Class *interface = ResolveType(dex_file, idx, klass);
1550 klass->SetInterface(i, interface);
1551 if (interface == NULL) {
1552 LG << "Failed to resolve interface";
1553 return false;
1554 }
1555 // Verify
1556 if (!klass->CanAccess(interface)) {
1557 LG << "Inaccessible interface";
1558 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001559 }
1560 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001561 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001562 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001563 return true;
1564}
1565
1566bool ClassLinker::LinkSuperClass(Class* klass) {
1567 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001568 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001569 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001570 if (super != NULL) {
1571 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1572 return false;
1573 }
1574 // TODO: clear finalize attribute
1575 return true;
1576 }
1577 if (super == NULL) {
1578 LG << "No superclass defined"; // TODO: LinkageError
1579 return false;
1580 }
1581 // Verify
1582 if (super->IsFinal()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001583 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001584 return false;
1585 }
1586 if (super->IsInterface()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001587 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001588 return false;
1589 }
1590 if (!klass->CanAccess(super)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001591 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001592 return false;
1593 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001594#ifndef NDEBUG
1595 // Ensure super classes are fully resolved prior to resolving fields..
1596 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001597 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001598 super = super->GetSuperClass();
1599 }
1600#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001601 return true;
1602}
1603
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001604// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001605bool ClassLinker::LinkMethods(Class* klass) {
1606 if (klass->IsInterface()) {
1607 // No vtable.
1608 size_t count = klass->NumVirtualMethods();
1609 if (!IsUint(16, count)) {
1610 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1611 return false;
1612 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001613 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001614 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001615 }
jeffhaobdb76512011-09-07 11:43:16 -07001616 // Link interface method tables
1617 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001618 } else {
1619 // Link virtual method tables
1620 LinkVirtualMethods(klass);
1621
1622 // Link interface method tables
1623 LinkInterfaceMethods(klass);
1624
1625 // Insert stubs.
1626 LinkAbstractMethods(klass);
1627 }
1628 return true;
1629}
1630
1631bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001632 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001633 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1634 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001635 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001636 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001637 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001638 // See if any of our virtual methods override the superclass.
1639 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001640 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001641 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001642 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001643 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001644 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001645 // Verify
1646 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001647 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001648 return false;
1649 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001650 vtable->Set(j, local_method);
1651 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001652 break;
1653 }
1654 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001655 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001656 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001657 vtable->Set(actual_count, local_method);
1658 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001659 actual_count += 1;
1660 }
1661 }
1662 if (!IsUint(16, actual_count)) {
1663 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1664 return false;
1665 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001666 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001667 CHECK_LE(actual_count, max_count);
1668 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001669 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001670 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001671 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001672 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001673 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001674 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001675 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001676 LG << "Too many methods"; // TODO: VirtualMachineError
1677 return false;
1678 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001679 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001680 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001681 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1682 vtable->Set(i, virtual_method);
1683 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001684 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001685 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001686 }
1687 return true;
1688}
1689
1690bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001691 int miranda_count = 0;
1692 int miranda_alloc = 0;
1693 size_t super_ifcount;
1694 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001695 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001696 } else {
1697 super_ifcount = 0;
1698 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001699 size_t ifcount = super_ifcount;
1700 ifcount += klass->NumInterfaces();
1701 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001702 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001703 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001704 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001705 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001706 // DCHECK(klass->GetIfTableCount() == 0);
1707 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001708 return true;
1709 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001710 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001711 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001712 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1713 for (size_t i = 0; i < super_ifcount; i++) {
1714 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1715 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001716 }
1717 // Flatten the interface inheritance hierarchy.
1718 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001719 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001720 Class* interface = klass->GetInterface(i);
1721 DCHECK(interface != NULL);
1722 if (!interface->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001723 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1724 return false;
1725 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001726 iftable->Set(idx++, AllocInterfaceEntry(interface));
1727 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1728 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001729 }
1730 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001731 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001732 CHECK_EQ(idx, ifcount);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001733 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001734 return true;
1735 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001736 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001737 for (size_t i = 0; i < ifcount; ++i) {
1738 InterfaceEntry* interface_entry = iftable->Get(i);
1739 Class* interface = interface_entry->GetInterface();
1740 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1741 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001742 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001743 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1744 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001745 int32_t k;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001746 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1747 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001748 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1749 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001750 LG << "Implementation not public";
1751 return false;
1752 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001753 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001754 break;
1755 }
1756 }
1757 if (k < 0) {
1758 if (miranda_count == miranda_alloc) {
1759 miranda_alloc += 8;
1760 if (miranda_list.empty()) {
1761 miranda_list.resize(miranda_alloc);
1762 } else {
1763 miranda_list.resize(miranda_alloc);
1764 }
1765 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001766 Method* miranda_method = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001767 int mir;
1768 for (mir = 0; mir < miranda_count; mir++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001769 miranda_method = miranda_list[mir];
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001770 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001771 break;
1772 }
1773 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001774 // point the interface table at a phantom slot
1775 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001776 if (mir == miranda_count) {
1777 miranda_list[miranda_count++] = interface_method;
1778 }
1779 }
1780 }
1781 }
1782 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001783 int old_method_count = klass->NumVirtualMethods();
1784 int new_method_count = old_method_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001785 klass->SetVirtualMethods(
1786 klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001787
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001788 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1789 CHECK(vtable != NULL);
1790 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001791 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001792 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001793 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001794 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001795 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001796 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001797 meth->SetDeclaringClass(klass);
1798 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1799 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001800 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001801 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001802 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001803 // TODO: do not assign to the vtable field until it is fully constructed.
1804 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001805 }
1806 return true;
1807}
1808
1809void ClassLinker::LinkAbstractMethods(Class* klass) {
1810 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001811 Method* method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001812 if (method->IsAbstract()) {
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001813 LG << "AbstractMethodError";
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001814 // TODO: throw AbstractMethodError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001815 }
1816 }
1817}
1818
1819bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001820 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001821 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001822}
1823
1824bool ClassLinker::LinkStaticFields(Class* klass) {
1825 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001826 size_t allocated_class_size = klass->GetClassSize();
1827 bool success = LinkFields(klass, false);
1828 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001829 return success;
1830}
1831
Brian Carlstromdbc05252011-09-09 01:59:59 -07001832struct LinkFieldsComparator {
1833 bool operator()(const Field* field1, const Field* field2){
1834
1835 // First come reference fields, then 64-bit, and finally 32-bit
1836 const Class* type1 = field1->GetTypeDuringLinking();
1837 const Class* type2 = field2->GetTypeDuringLinking();
1838 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
1839 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
1840 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
1841 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
1842 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
1843 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
1844 if (order1 != order2) {
1845 return order1 < order2;
1846 }
1847
1848 // same basic group? then sort by string.
1849 std::string name1 = field1->GetName()->ToModifiedUtf8();
1850 std::string name2 = field2->GetName()->ToModifiedUtf8();
1851 return name1 < name2;
1852 }
1853};
1854
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001855bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001856 size_t num_fields =
1857 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1858
1859 ObjectArray<Field>* fields =
1860 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001861
1862 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07001863 size_t size;
1864 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001865 if (instance) {
1866 Class* super_class = klass->GetSuperClass();
1867 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001868 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001869 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001870 }
1871 size = field_offset.Uint32Value();
1872 } else {
1873 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07001874 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001875 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001876
Brian Carlstromdbc05252011-09-09 01:59:59 -07001877 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001878
Brian Carlstromdbc05252011-09-09 01:59:59 -07001879 // we want a relatively stable order so that adding new fields
1880 // minimizes distruption of C++ version such as Class and Method.
1881 std::deque<Field*> grouped_and_sorted_fields;
1882 for (size_t i = 0; i < num_fields; i++) {
1883 grouped_and_sorted_fields.push_back(fields->Get(i));
1884 }
1885 std::sort(grouped_and_sorted_fields.begin(),
1886 grouped_and_sorted_fields.end(),
1887 LinkFieldsComparator());
1888
1889 // References should be at the front.
1890 size_t current_field = 0;
1891 size_t num_reference_fields = 0;
1892 for (; current_field < num_fields; current_field++) {
1893 Field* field = grouped_and_sorted_fields.front();
1894 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001895 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07001896 bool isPrimitive = type != NULL && type->IsPrimitive();
1897 if (isPrimitive) {
1898 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001899 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001900 grouped_and_sorted_fields.pop_front();
1901 num_reference_fields++;
1902 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001903 field->SetOffset(field_offset);
1904 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001905 }
1906
1907 // Now we want to pack all of the double-wide fields together. If
1908 // we're not aligned, though, we want to shuffle one 32-bit field
1909 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001910 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
1911 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
1912 Field* field = grouped_and_sorted_fields[i];
1913 const Class* type = field->GetTypeDuringLinking();
1914 CHECK(type != NULL); // should only be working on primitive types
1915 DCHECK(type->IsPrimitive());
1916 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
1917 continue;
1918 }
1919 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001920 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001921 // drop the consumed field
1922 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
1923 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001924 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001925 // whether we found a 32-bit field for padding or not, we advance
1926 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001927 }
1928
1929 // Alignment is good, shuffle any double-wide fields forward, and
1930 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001931 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
1932 while (!grouped_and_sorted_fields.empty()) {
1933 Field* field = grouped_and_sorted_fields.front();
1934 grouped_and_sorted_fields.pop_front();
1935 const Class* type = field->GetTypeDuringLinking();
1936 CHECK(type != NULL); // should only be working on primitive types
1937 DCHECK(type->IsPrimitive());
1938 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001939 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001940 field_offset = MemberOffset(field_offset.Uint32Value() +
1941 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
1942 ? sizeof(uint64_t)
1943 : sizeof(uint32_t)));
1944 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001945 }
1946
1947#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001948 // Make sure that all reference fields appear before
1949 // non-reference fields, and all double-wide fields are aligned.
1950 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07001951 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001952 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001953 if (false) { // enable to debug field layout
1954 LOG(INFO) << "LinkFields:"
1955 << " class=" << klass->GetDescriptor()->ToModifiedUtf8()
1956 << " field=" << field->GetName()->ToModifiedUtf8()
1957 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
1958 }
1959 const Class* type = field->GetTypeDuringLinking();
1960 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001961 if (!seen_non_ref) {
1962 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001963 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001964 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001965 } else {
1966 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967 }
1968 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001969 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001970 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001971 }
1972#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001973 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001974 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07001975 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001976 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001977 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001978 klass->SetObjectSize(size);
1979 }
1980 } else {
1981 klass->SetNumReferenceStaticFields(num_reference_fields);
1982 klass->SetClassSize(size);
1983 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001984 return true;
1985}
1986
1987// Set the bitmap of reference offsets, refOffsets, from the ifields
1988// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001989void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001990 uint32_t reference_offsets = 0;
1991 Class* super_class = klass->GetSuperClass();
1992 if (super_class != NULL) {
1993 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001994 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001995 if (reference_offsets == CLASS_WALK_SUPER) {
1996 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001997 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001998 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001999 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002000 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002001}
2002
2003void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002004 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002005}
2006
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002007void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2008 uint32_t reference_offsets) {
2009 size_t num_reference_fields =
2010 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2011 : klass->NumReferenceStaticFieldsDuringLinking();
2012 const ObjectArray<Field>* fields =
2013 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002014 // All of the fields that contain object references are guaranteed
2015 // to be at the beginning of the fields list.
2016 for (size_t i = 0; i < num_reference_fields; ++i) {
2017 // Note that byte_offset is the offset from the beginning of
2018 // object, not the offset into instance data
2019 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002020 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002021 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2022 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2023 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002024 CHECK_NE(new_bit, 0U);
2025 reference_offsets |= new_bit;
2026 } else {
2027 reference_offsets = CLASS_WALK_SUPER;
2028 break;
2029 }
2030 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002031 // Update fields in klass
2032 if (instance) {
2033 klass->SetReferenceInstanceOffsets(reference_offsets);
2034 } else {
2035 klass->SetReferenceStaticOffsets(reference_offsets);
2036 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002037}
2038
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002039String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002040 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002041 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002042 if (resolved != NULL) {
2043 return resolved;
2044 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002045 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2046 int32_t utf16_length = dex_file.GetStringLength(string_id);
2047 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002048 // TODO: remote the const_cast below
2049 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002050 dex_cache->SetResolvedString(string_idx, string);
2051 return string;
2052}
2053
2054Class* ClassLinker::ResolveType(const DexFile& dex_file,
2055 uint32_t type_idx,
2056 DexCache* dex_cache,
2057 const ClassLoader* class_loader) {
2058 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002059 if (resolved == NULL) {
2060 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2061 if (descriptor[1] == '\0') {
2062 // only the descriptors of primitive types should be 1 character long
2063 resolved = FindPrimitiveClass(descriptor[0]);
2064 } else {
2065 resolved = FindClass(descriptor, class_loader);
2066 }
2067 if (resolved != NULL) {
2068 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2069 if (dex_cache != check->GetDexCache()) {
2070 if (check->GetClassLoader() != NULL) {
2071 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
2072 resolved = NULL;
2073 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002074 }
2075 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002076 if (resolved != NULL) {
2077 dex_cache->SetResolvedType(type_idx, resolved);
2078 } else {
2079 DCHECK(Thread::Current()->IsExceptionPending());
2080 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002081 }
2082 return resolved;
2083}
2084
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002085Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2086 uint32_t method_idx,
2087 DexCache* dex_cache,
2088 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002089 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002090 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2091 if (resolved != NULL) {
2092 return resolved;
2093 }
2094 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2095 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2096 if (klass == NULL) {
2097 return NULL;
2098 }
2099
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002100 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002101 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002102 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002103 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002104 } else if (klass->IsInterface()) {
2105 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002106 } else {
2107 resolved = klass->FindVirtualMethod(name, signature);
2108 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002109 if (resolved != NULL) {
2110 dex_cache->SetResolvedMethod(method_idx, resolved);
2111 } else {
2112 // DCHECK(Thread::Current()->IsExceptionPending());
2113 }
2114 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002115}
2116
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002117Field* ClassLinker::ResolveField(const DexFile& dex_file,
2118 uint32_t field_idx,
2119 DexCache* dex_cache,
2120 const ClassLoader* class_loader,
2121 bool is_static) {
2122 Field* resolved = dex_cache->GetResolvedField(field_idx);
2123 if (resolved != NULL) {
2124 return resolved;
2125 }
2126 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2127 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2128 if (klass == NULL) {
2129 return NULL;
2130 }
2131
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002132 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002133 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2134 // TODO: LinkageError?
2135 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002136 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002137 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002138 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002139 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002140 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002141 if (resolved != NULL) {
2142 dex_cache->SetResolvedfield(field_idx, resolved);
2143 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002144 // TODO: DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002145 }
2146 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002147}
2148
Elliott Hughese27955c2011-08-26 15:21:24 -07002149size_t ClassLinker::NumLoadedClasses() const {
2150 MutexLock mu(classes_lock_);
2151 return classes_.size();
2152}
2153
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002154} // namespace art