blob: 8595bfc897b3ffb2bf9a50ae8425cf5997b574cd [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)
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070074 : classes_lock_(Mutex::Create("ClassLinker::Lock")),
75 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() {
517 delete classes_lock_;
518 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700519 Field::ResetClass();
520 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700521 BooleanArray::ResetArrayClass();
522 ByteArray::ResetArrayClass();
523 CharArray::ResetArrayClass();
524 DoubleArray::ResetArrayClass();
525 FloatArray::ResetArrayClass();
526 IntArray::ResetArrayClass();
527 LongArray::ResetArrayClass();
528 ShortArray::ResetArrayClass();
529 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700530 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700531}
532
533DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700534 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700535 dex_cache->Init(String::AllocFromModifiedUtf8(dex_file.GetLocation().c_str()),
536 AllocObjectArray<String>(dex_file.NumStringIds()),
537 AllocObjectArray<Class>(dex_file.NumTypeIds()),
538 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700539 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700540 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
541 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700542 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700543}
544
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700545CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
546 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700547}
548
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700549InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
550 DCHECK(interface->IsInterface());
551 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
552 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
553 interface_entry->SetInterface(interface);
554 return interface_entry;
555}
556
Brian Carlstrom4873d462011-08-21 15:23:39 -0700557Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
558 DCHECK_GE(class_size, sizeof(Class));
559 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700560 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
561 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700562 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700563}
564
Brian Carlstrom4873d462011-08-21 15:23:39 -0700565Class* ClassLinker::AllocClass(size_t class_size) {
566 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700567}
568
Jesse Wilson35baaab2011-08-10 16:18:03 -0400569Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700570 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700571}
572
573Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700574 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700575}
576
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700577ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
578 return ObjectArray<StackTraceElement>::Alloc(
579 GetClassRoot(kJavaLangStackTraceElementArrayClass),
580 length);
581}
582
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700583Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700584 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700585 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700586 if (class_loader != NULL) {
587 Class* klass = FindClass(descriptor, NULL);
588 if (klass != NULL) {
589 return klass;
590 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700591 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700592 }
593
Carl Shapirob5573532011-07-12 18:22:59 -0700594 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700595 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700596 CHECK(!self->IsExceptionPending());
597 // Find the class in the loaded classes table.
598 Class* klass = LookupClass(descriptor, class_loader);
599 if (klass == NULL) {
600 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700601 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700602 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700603 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700604 const DexFile::ClassPath& class_path = ((class_loader != NULL)
605 ? ClassLoader::GetClassPath(class_loader)
606 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700607 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700608 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700609 std::string name(PrintableString(descriptor));
610 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
611 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700612 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700613 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700614 const DexFile& dex_file = *pair.first;
615 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700616 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700617 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700618 if (!init_done_) {
619 // finish up init of hand crafted class_roots_
620 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700621 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700622 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700623 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400624 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700625 klass = GetClassRoot(kJavaLangString);
626 } else if (descriptor == "Ljava/lang/reflect/Field;") {
627 klass = GetClassRoot(kJavaLangReflectField);
628 } else if (descriptor == "Ljava/lang/reflect/Method;") {
629 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700630 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700631 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700632 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700633 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700634 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700635 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700636 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700637 klass->SetDexCache(dex_cache);
638 LoadClass(dex_file, dex_class_def, klass, class_loader);
639 // Check for a pending exception during load
640 if (self->IsExceptionPending()) {
641 // TODO: free native allocations in klass
642 return NULL;
643 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700644 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700645 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700646 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700647 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700648 if (!success) {
649 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700650 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700651 // TODO: free native allocations in klass
652 klass = LookupClass(descriptor, class_loader);
653 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700654 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700655 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700656 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700657 CHECK(!klass->IsLoaded());
658 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700659 // Loading failed.
660 // TODO: CHECK(self->IsExceptionPending());
661 lock.NotifyAll();
662 return NULL;
663 }
664 CHECK(klass->IsLoaded());
665 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700666 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700667 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700668 // Linking failed.
669 // TODO: CHECK(self->IsExceptionPending());
670 lock.NotifyAll();
671 return NULL;
672 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700673 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700674 }
675 }
676 }
677 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700678 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700679 ObjectLock lock(klass);
680 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700681 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700682 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700683 return NULL;
684 }
685 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700686 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700687 lock.Wait();
688 }
689 }
690 if (klass->IsErroneous()) {
691 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
692 return NULL;
693 }
694 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700695 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700696 CHECK(!self->IsExceptionPending());
697 return klass;
698}
699
Brian Carlstrom4873d462011-08-21 15:23:39 -0700700// Precomputes size that will be needed for Class, matching LinkStaticFields
701size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
702 const DexFile::ClassDef& dex_class_def) {
703 const byte* class_data = dex_file.GetClassData(dex_class_def);
704 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
705 size_t num_static_fields = header.static_fields_size_;
706 size_t num_ref = 0;
707 size_t num_32 = 0;
708 size_t num_64 = 0;
709 if (num_static_fields != 0) {
710 uint32_t last_idx = 0;
711 for (size_t i = 0; i < num_static_fields; ++i) {
712 DexFile::Field dex_field;
713 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
714 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
715 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
716 char c = descriptor[0];
717 if (c == 'L' || c == '[') {
718 num_ref++;
719 } else if (c == 'J' || c == 'D') {
720 num_64++;
721 } else {
722 num_32++;
723 }
724 }
725 }
726
727 // start with generic class data
728 size_t size = sizeof(Class);
729 // follow with reference fields which must be contiguous at start
730 size += (num_ref * sizeof(uint32_t));
731 // if there are 64-bit fields to add, make sure they are aligned
732 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
733 if (num_32 != 0) {
734 // use an available 32-bit field for padding
735 num_32--;
736 }
737 size += sizeof(uint32_t); // either way, we are adding a word
738 DCHECK_EQ(size, RoundUp(size, 8));
739 }
740 // tack on any 64-bit fields now that alignment is assured
741 size += (num_64 * sizeof(uint64_t));
742 // tack on any remaining 32-bit fields
743 size += (num_32 * sizeof(uint32_t));
744 return size;
745}
746
Brian Carlstromf615a612011-07-23 12:50:34 -0700747void ClassLinker::LoadClass(const DexFile& dex_file,
748 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700749 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700750 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700751 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700752 CHECK(klass->GetDexCache() != NULL);
753 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700754 const byte* class_data = dex_file.GetClassData(dex_class_def);
755 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700756
Brian Carlstromf615a612011-07-23 12:50:34 -0700757 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700758 CHECK(descriptor != NULL);
759
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700760 klass->SetClass(GetClassRoot(kJavaLangClass));
761 if (klass->GetDescriptor() != NULL) {
762 DCHECK(klass->GetDescriptor()->Equals(descriptor));
763 } else {
764 klass->SetDescriptor(String::AllocFromModifiedUtf8(descriptor));
765 }
766 uint32_t access_flags = dex_class_def.access_flags_;
767 // Make sure there aren't any "bonus" flags set, since we use them for runtime
768 // state.
769 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
770 klass->SetAccessFlags(access_flags);
771 klass->SetClassLoader(class_loader);
772 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
773 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700774
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700775 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700776
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700777 size_t num_static_fields = header.static_fields_size_;
778 size_t num_instance_fields = header.instance_fields_size_;
779 size_t num_direct_methods = header.direct_methods_size_;
780 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700781
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700782 klass->SetSourceFile(String::AllocFromModifiedUtf8(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700783
784 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700785 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700786
787 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700788 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700789 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700790 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700791 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700792 DexFile::Field dex_field;
793 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400794 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700795 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700796 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700797 }
798 }
799
800 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700801 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700802 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700803 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700804 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700805 DexFile::Field dex_field;
806 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400807 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700808 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700809 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700810 }
811 }
812
813 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700814 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700815 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700816 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700817 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700818 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700819 DexFile::Method dex_method;
820 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700821 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700822 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700823 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700824 // TODO: register maps
825 }
826 }
827
828 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700829 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700830 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700831 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700832 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700833 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700834 DexFile::Method dex_method;
835 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700836 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700837 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700838 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700839 // TODO: register maps
840 }
841 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700842}
843
Brian Carlstromf615a612011-07-23 12:50:34 -0700844void ClassLinker::LoadInterfaces(const DexFile& dex_file,
845 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700846 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700847 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700848 if (list != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700849 klass->SetInterfaces(AllocObjectArray<Class>(list->Size()));
850 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
851 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700852 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700853 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700854 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700855 }
856 }
857}
858
Brian Carlstromf615a612011-07-23 12:50:34 -0700859void ClassLinker::LoadField(const DexFile& dex_file,
860 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700861 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700862 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700863 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700864 dst->SetDeclaringClass(klass);
865 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
866 dst->SetTypeIdx(field_id.type_idx_);
867 dst->SetAccessFlags(src.access_flags_);
868
869 // In order to access primitive types using GetTypeDuringLinking we need to
870 // ensure they are resolved into the dex cache
871 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
872 if (descriptor[1] == '\0') {
873 // only the descriptors of primitive types should be 1 character long
874 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
875 DCHECK(resolved->IsPrimitive());
876 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700877}
878
Brian Carlstromf615a612011-07-23 12:50:34 -0700879void ClassLinker::LoadMethod(const DexFile& dex_file,
880 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700881 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700882 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700883 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700884 dst->SetDeclaringClass(klass);
885 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700886 {
887 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700888 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700889 dst->SetSignature(String::AllocFromModifiedUtf8(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700890 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700891 dst->SetProtoIdx(method_id.proto_idx_);
892 dst->SetCodeItemOffset(src.code_off_);
893 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstrom2ed67392011-09-09 14:53:28 -0700894 dst->SetShorty(String::AllocFromModifiedUtf8(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700895 dst->SetAccessFlags(src.access_flags_);
896 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700897
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700898 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
899 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
900 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
901 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
902 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
903 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700904
Brian Carlstrom934486c2011-07-12 23:42:50 -0700905 // TODO: check for finalize method
906
Brian Carlstromf615a612011-07-23 12:50:34 -0700907 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700908 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700909 dst->SetNumRegisters(code_item->registers_size_);
910 dst->SetNumIns(code_item->ins_size_);
911 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700912 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700913 uint16_t num_args = Method::NumArgRegisters(shorty);
914 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700915 ++num_args;
916 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700917 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700918 // TODO: native methods
919 }
920}
921
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700922void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700923 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
924}
925
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700926void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700927 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700928 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700929 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700930}
931
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700932void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700933 RegisterDexFile(dex_file, AllocDexCache(dex_file));
934}
935
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700936void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700937 CHECK(dex_cache != NULL) << dex_file.GetLocation();
938 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700939 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700940 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700941}
942
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700943const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700944 for (size_t i = 0; i != dex_caches_.size(); ++i) {
945 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700946 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700947 }
948 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700949 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700950 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700951}
952
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700953DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstromf615a612011-07-23 12:50:34 -0700954 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700955 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700956 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700957 }
958 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700959 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700960 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700961}
962
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700963Class* ClassLinker::CreatePrimitiveClass(const char* descriptor,
964 Class::PrimitiveType type) {
965 // TODO: deduce one argument from the other
Brian Carlstrom4873d462011-08-21 15:23:39 -0700966 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700967 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700968 klass->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
969 klass->SetDescriptor(String::AllocFromModifiedUtf8(descriptor));
970 klass->SetPrimitiveType(type);
971 klass->SetStatus(Class::kStatusInitialized);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700972 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700973 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700974 return klass;
975}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700976
Brian Carlstrombe977852011-07-19 14:54:54 -0700977// Create an array class (i.e. the class object for the array, not the
978// array itself). "descriptor" looks like "[C" or "[[[[B" or
979// "[Ljava/lang/String;".
980//
981// If "descriptor" refers to an array of primitives, look up the
982// primitive type's internally-generated class object.
983//
984// "loader" is the class loader of the class that's referring to us. It's
985// used to ensure that we're looking for the element type in the right
986// context. It does NOT become the class loader for the array class; that
987// always comes from the base element class.
988//
989// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700990Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700991 const ClassLoader* class_loader) {
992 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700993
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700994 // Identify the underlying element class and the array dimension depth.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700995 Class* component_type = NULL;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700996 int array_rank;
997 if (descriptor[1] == '[') {
998 // array of arrays; keep descriptor and grab stuff from parent
999 Class* outer = FindClass(descriptor.substr(1), class_loader);
1000 if (outer != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001001 // want the base class, not "outer", in our component_type
1002 component_type = outer->GetComponentType();
1003 array_rank = outer->GetArrayRank() + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001004 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001005 DCHECK(component_type == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001006 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001007 } else {
1008 array_rank = 1;
1009 if (descriptor[1] == 'L') {
1010 // array of objects; strip off "[" and look up descriptor.
1011 const StringPiece subDescriptor = descriptor.substr(1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001012 component_type = FindClass(subDescriptor, class_loader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001013 } else {
1014 // array of a primitive type
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001015 component_type = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001016 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001017 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001018
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001019 if (component_type == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001020 // failed
1021 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
1022 return NULL;
1023 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001024
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001025 // See if the component type is already loaded. Array classes are
1026 // always associated with the class loader of their underlying
1027 // element type -- an array of Strings goes with the loader for
1028 // java/lang/String -- so we need to look for it there. (The
1029 // caller should have checked for the existence of the class
1030 // before calling here, but they did so with *their* class loader,
1031 // not the component type's loader.)
1032 //
1033 // If we find it, the caller adds "loader" to the class' initiating
1034 // loader list, which should prevent us from going through this again.
1035 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001036 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001037 // are the same, because our caller (FindClass) just did the
1038 // lookup. (Even if we get this wrong we still have correct behavior,
1039 // because we effectively do this lookup again when we add the new
1040 // class to the hash table --- necessary because of possible races with
1041 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001042 if (class_loader != component_type->GetClassLoader()) {
1043 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001044 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001045 return new_class;
1046 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001047 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001048
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001049 // Fill out the fields in the Class.
1050 //
1051 // It is possible to execute some methods against arrays, because
1052 // all arrays are subclasses of java_lang_Object_, so we need to set
1053 // up a vtable. We can just point at the one in java_lang_Object_.
1054 //
1055 // Array classes are simple enough that we don't need to do a full
1056 // link step.
1057
1058 Class* new_class = NULL;
1059 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001060 // Classes that were hand created, ie not by FindSystemClass
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001061 if (descriptor == "[Ljava/lang/Object;") {
1062 new_class = GetClassRoot(kObjectArrayClass);
1063 } else if (descriptor == "[C") {
1064 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001065 } else if (descriptor == "[I") {
1066 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001067 }
1068 }
1069 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001070 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001071 if (new_class == NULL) {
1072 return NULL;
1073 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001074 new_class->SetArrayRank(array_rank);
1075 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001076 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001077 DCHECK_LE(1, new_class->GetArrayRank());
1078 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001079 if (new_class->GetDescriptor() != NULL) {
1080 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1081 } else {
1082 new_class->SetDescriptor(String::AllocFromModifiedUtf8(descriptor.ToString().c_str()));
1083 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001084 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001085 new_class->SetSuperClass(java_lang_Object);
1086 new_class->SetVTable(java_lang_Object->GetVTable());
1087 new_class->SetPrimitiveType(Class::kPrimNot);
1088 new_class->SetClassLoader(component_type->GetClassLoader());
1089 new_class->SetStatus(Class::kStatusInitialized);
1090 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001091 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001092
1093
1094 // All arrays have java/lang/Cloneable and java/io/Serializable as
1095 // interfaces. We need to set that up here, so that stuff like
1096 // "instanceof" works right.
1097 //
1098 // Note: The GC could run during the call to FindSystemClass,
1099 // so we need to make sure the class object is GC-valid while we're in
1100 // there. Do this by clearing the interface list so the GC will just
1101 // think that the entries are null.
1102
1103
1104 // Use the single, global copies of "interfaces" and "iftable"
1105 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001106 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001107 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001108
1109 // Inherit access flags from the component type. Arrays can't be
1110 // used as a superclass or interface, so we want to add "final"
1111 // and remove "interface".
1112 //
1113 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001114 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001115 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001116 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1117 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001118
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001119 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001120 return new_class;
1121 }
1122 // Another thread must have loaded the class after we
1123 // started but before we finished. Abandon what we've
1124 // done.
1125 //
1126 // (Yes, this happens.)
1127
1128 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001129 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001130 DCHECK(other_class != NULL);
1131 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001132}
1133
1134Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001135 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001136 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001137 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001138 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001139 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001140 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001141 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001142 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001143 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001144 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001145 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001146 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001147 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001148 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001149 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001150 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001151 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001152 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001153 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001154 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001155 std::string printable_type(PrintableChar(type));
1156 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1157 "Not a primitive type: %s", printable_type.c_str());
1158 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001159}
1160
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001161bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1162 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001163 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001164 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001165 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001166}
1167
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001168Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001169 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001170 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001171 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001172 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001173 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001174 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001175 return klass;
1176 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001177 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001178 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001179}
1180
1181bool ClassLinker::InitializeClass(Class* klass) {
1182 CHECK(klass->GetStatus() == Class::kStatusResolved ||
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001183 klass->GetStatus() == Class::kStatusError) << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001184
Carl Shapirob5573532011-07-12 18:22:59 -07001185 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001186
1187 {
1188 ObjectLock lock(klass);
1189
1190 if (klass->GetStatus() < Class::kStatusVerified) {
1191 if (klass->IsErroneous()) {
1192 LG << "re-initializing failed class"; // TODO: throw
1193 return false;
1194 }
1195
1196 CHECK(klass->GetStatus() == Class::kStatusResolved);
1197
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001198 klass->SetStatus(Class::kStatusVerifying);
jeffhaobdb76512011-09-07 11:43:16 -07001199 if (!DexVerifier::VerifyClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001200 LG << "Verification failed"; // TODO: ThrowVerifyError
1201 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001202 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001203 klass->SetStatus(Class::kStatusError);
1204 return false;
1205 }
1206
1207 klass->SetStatus(Class::kStatusVerified);
1208 }
1209
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001210 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001211 return true;
1212 }
1213
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001214 while (klass->GetStatus() == Class::kStatusInitializing) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001215 // we caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001216 if (klass->GetClinitThreadId() == self->GetTid()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001217 LG << "recursive <clinit>";
1218 return true;
1219 }
1220
1221 CHECK(!self->IsExceptionPending());
1222
1223 lock.Wait(); // TODO: check for interruption
1224
1225 // When we wake up, repeat the test for init-in-progress. If
1226 // there's an exception pending (only possible if
1227 // "interruptShouldThrow" was set), bail out.
1228 if (self->IsExceptionPending()) {
1229 CHECK(false);
1230 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1231 klass->SetStatus(Class::kStatusError);
1232 return false;
1233 }
1234 if (klass->GetStatus() == Class::kStatusInitializing) {
1235 continue;
1236 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001237 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001238 klass->GetStatus() == Class::kStatusError);
1239 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001240 // The caller wants an exception, but it was thrown in a
1241 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001242 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1243 return false;
1244 }
1245 return true; // otherwise, initialized
1246 }
1247
1248 // see if we failed previously
1249 if (klass->IsErroneous()) {
1250 // might be wise to unlock before throwing; depends on which class
1251 // it is that we have locked
1252
1253 // TODO: throwEarlierClassFailure(klass);
1254 return false;
1255 }
1256
1257 if (!ValidateSuperClassDescriptors(klass)) {
1258 klass->SetStatus(Class::kStatusError);
1259 return false;
1260 }
1261
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001262 DCHECK(klass->GetStatus() < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001263
Elliott Hughesdcc24742011-09-07 14:02:44 -07001264 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001265 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001266 }
1267
1268 if (!InitializeSuperClass(klass)) {
1269 return false;
1270 }
1271
1272 InitializeStaticFields(klass);
1273
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001274 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001275 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001276 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001277 }
1278
1279 {
1280 ObjectLock lock(klass);
1281
1282 if (self->IsExceptionPending()) {
1283 klass->SetStatus(Class::kStatusError);
1284 } else {
1285 klass->SetStatus(Class::kStatusInitialized);
1286 }
1287 lock.NotifyAll();
1288 }
1289
1290 return true;
1291}
1292
1293bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1294 if (klass->IsInterface()) {
1295 return true;
1296 }
1297 // begin with the methods local to the superclass
1298 if (klass->HasSuperClass() &&
1299 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1300 const Class* super = klass->GetSuperClass();
1301 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001302 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001303 if (method != super->GetVirtualMethod(i) &&
1304 !HasSameMethodDescriptorClasses(method, super, klass)) {
1305 LG << "Classes resolve differently in superclass";
1306 return false;
1307 }
1308 }
1309 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001310 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1311 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1312 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001313 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1314 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001315 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001316 if (!HasSameMethodDescriptorClasses(method, interface,
1317 method->GetClass())) {
1318 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1319 return false;
1320 }
1321 }
1322 }
1323 }
1324 return true;
1325}
1326
1327bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001328 const Class* klass1,
1329 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001330 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001331 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001332 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001333 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001334 const char* descriptor = it->GetDescriptor();
1335 if (descriptor == NULL) {
1336 break;
1337 }
1338 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1339 // Found a non-primitive type.
1340 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1341 return false;
1342 }
1343 }
1344 }
1345 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001346 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001347 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1348 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1349 return false;
1350 }
1351 }
1352 return true;
1353}
1354
1355// Returns true if classes referenced by the descriptor are the
1356// same classes in klass1 as they are in klass2.
1357bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001358 const Class* klass1,
1359 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001360 CHECK(descriptor != NULL);
1361 CHECK(klass1 != NULL);
1362 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001363 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001364 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001365 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001366 // TODO: found2 == NULL
1367 // TODO: lookup found1 in initiating loader list
1368 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001369 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001370 if (found1 == found2) {
1371 return true;
1372 } else {
1373 return false;
1374 }
1375 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001376 return true;
1377}
1378
1379bool ClassLinker::InitializeSuperClass(Class* klass) {
1380 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001381 if (!klass->IsInterface() && klass->HasSuperClass()) {
1382 Class* super_class = klass->GetSuperClass();
1383 if (super_class->GetStatus() != Class::kStatusInitialized) {
1384 CHECK(!super_class->IsInterface());
1385 klass->MonitorExit();
1386 bool super_initialized = InitializeClass(super_class);
1387 klass->MonitorEnter();
1388 // TODO: check for a pending exception
1389 if (!super_initialized) {
1390 klass->SetStatus(Class::kStatusError);
1391 klass->NotifyAll();
1392 return false;
1393 }
1394 }
1395 }
1396 return true;
1397}
1398
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001399bool ClassLinker::EnsureInitialized(Class* c) {
1400 CHECK(c != NULL);
1401 if (c->IsInitialized()) {
1402 return true;
1403 }
1404
1405 c->MonitorExit();
1406 InitializeClass(c);
1407 c->MonitorEnter();
1408 return !Thread::Current()->IsExceptionPending();
1409}
1410
Brian Carlstromb9edb842011-08-28 16:31:06 -07001411StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1412 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001413 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1414 Class* klass = class_linker->ResolveType(type_idx, referrer);
1415 if (klass == NULL) {
1416 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1417 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001418 // If we are the <clinit> of this class, just return our storage.
1419 //
1420 // Do not set the DexCache InitializedStaticStorage, since that
1421 // implies <clinit> has finished running.
1422 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1423 return klass;
1424 }
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001425 if (!class_linker->EnsureInitialized(klass)) {
1426 CHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001427 UNIMPLEMENTED(FATAL) << "throw exception due to class initialization problem";
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001428 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001429 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001430 return klass;
1431}
1432
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001433void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1434 Class* c, std::map<int, Field*>& field_map) {
1435 const ClassLoader* cl = c->GetClassLoader();
1436 const byte* class_data = dex_file.GetClassData(dex_class_def);
1437 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1438 uint32_t last_idx = 0;
1439 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1440 DexFile::Field dex_field;
1441 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1442 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1443 }
1444}
1445
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001446void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001447 size_t num_static_fields = klass->NumStaticFields();
1448 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001449 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001450 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001451 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001452 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001453 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001454 return;
1455 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001456 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001457 const DexFile& dex_file = FindDexFile(dex_cache);
1458 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001459 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001460
1461 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1462 std::map<int, Field*> field_map;
1463 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1464
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001465 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001466 if (addr == NULL) {
1467 // All this class' static fields have default values.
1468 return;
1469 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001470 size_t array_size = DecodeUnsignedLeb128(&addr);
1471 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001472 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001473 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001474 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001475 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001476 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001477 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001478 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001479 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001480 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001481 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001482 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001483 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001484 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001485 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001486 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001487 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001488 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001489 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001490 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001491 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001492 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001493 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001494 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001495 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001496 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001497 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001498 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001499 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001500 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001501 break;
1502 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001503 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001504 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001505 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001506 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001507 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001508 break;
1509 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001510 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001511 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001512 }
1513}
1514
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001515bool ClassLinker::LinkClass(Class* klass) {
1516 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001517 if (!LinkSuperClass(klass)) {
1518 return false;
1519 }
1520 if (!LinkMethods(klass)) {
1521 return false;
1522 }
1523 if (!LinkInstanceFields(klass)) {
1524 return false;
1525 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001526 if (!LinkStaticFields(klass)) {
1527 return false;
1528 }
1529 CreateReferenceInstanceOffsets(klass);
1530 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001531 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1532 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001533 return true;
1534}
1535
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001536bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001537 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1538 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1539 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001540 if (super_class == NULL) {
1541 LG << "Failed to resolve superclass";
1542 return false;
1543 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001544 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001545 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001546 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1547 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1548 Class *interface = ResolveType(dex_file, idx, klass);
1549 klass->SetInterface(i, interface);
1550 if (interface == NULL) {
1551 LG << "Failed to resolve interface";
1552 return false;
1553 }
1554 // Verify
1555 if (!klass->CanAccess(interface)) {
1556 LG << "Inaccessible interface";
1557 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001558 }
1559 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001560 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001561 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001562 return true;
1563}
1564
1565bool ClassLinker::LinkSuperClass(Class* klass) {
1566 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001567 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001568 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001569 if (super != NULL) {
1570 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1571 return false;
1572 }
1573 // TODO: clear finalize attribute
1574 return true;
1575 }
1576 if (super == NULL) {
1577 LG << "No superclass defined"; // TODO: LinkageError
1578 return false;
1579 }
1580 // Verify
1581 if (super->IsFinal()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001582 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001583 return false;
1584 }
1585 if (super->IsInterface()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001586 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001587 return false;
1588 }
1589 if (!klass->CanAccess(super)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001590 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001591 return false;
1592 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001593#ifndef NDEBUG
1594 // Ensure super classes are fully resolved prior to resolving fields..
1595 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001596 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001597 super = super->GetSuperClass();
1598 }
1599#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001600 return true;
1601}
1602
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001603// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001604bool ClassLinker::LinkMethods(Class* klass) {
1605 if (klass->IsInterface()) {
1606 // No vtable.
1607 size_t count = klass->NumVirtualMethods();
1608 if (!IsUint(16, count)) {
1609 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1610 return false;
1611 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001612 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001613 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001614 }
jeffhaobdb76512011-09-07 11:43:16 -07001615 // Link interface method tables
1616 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001617 } else {
1618 // Link virtual method tables
1619 LinkVirtualMethods(klass);
1620
1621 // Link interface method tables
1622 LinkInterfaceMethods(klass);
1623
1624 // Insert stubs.
1625 LinkAbstractMethods(klass);
1626 }
1627 return true;
1628}
1629
1630bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001631 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001632 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1633 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001634 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001635 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001636 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001637 // See if any of our virtual methods override the superclass.
1638 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001639 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001641 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001642 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001643 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001644 // Verify
1645 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001646 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001647 return false;
1648 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001649 vtable->Set(j, local_method);
1650 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001651 break;
1652 }
1653 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001654 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001655 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001656 vtable->Set(actual_count, local_method);
1657 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001658 actual_count += 1;
1659 }
1660 }
1661 if (!IsUint(16, actual_count)) {
1662 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1663 return false;
1664 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001665 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001666 CHECK_LE(actual_count, max_count);
1667 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001668 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001669 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001670 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001671 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001672 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001673 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001674 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001675 LG << "Too many methods"; // TODO: VirtualMachineError
1676 return false;
1677 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001678 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001679 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001680 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1681 vtable->Set(i, virtual_method);
1682 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001683 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001684 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001685 }
1686 return true;
1687}
1688
1689bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001690 int miranda_count = 0;
1691 int miranda_alloc = 0;
1692 size_t super_ifcount;
1693 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001694 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001695 } else {
1696 super_ifcount = 0;
1697 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001698 size_t ifcount = super_ifcount;
1699 ifcount += klass->NumInterfaces();
1700 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001701 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001702 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001703 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001704 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001705 // DCHECK(klass->GetIfTableCount() == 0);
1706 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001707 return true;
1708 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001709 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001711 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1712 for (size_t i = 0; i < super_ifcount; i++) {
1713 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1714 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001715 }
1716 // Flatten the interface inheritance hierarchy.
1717 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001718 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001719 Class* interface = klass->GetInterface(i);
1720 DCHECK(interface != NULL);
1721 if (!interface->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001722 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1723 return false;
1724 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001725 iftable->Set(idx++, AllocInterfaceEntry(interface));
1726 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1727 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001728 }
1729 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001730 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001731 CHECK_EQ(idx, ifcount);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001732 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001733 return true;
1734 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001735 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001736 for (size_t i = 0; i < ifcount; ++i) {
1737 InterfaceEntry* interface_entry = iftable->Get(i);
1738 Class* interface = interface_entry->GetInterface();
1739 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1740 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001741 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001742 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1743 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001744 int32_t k;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001745 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1746 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001747 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1748 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001749 LG << "Implementation not public";
1750 return false;
1751 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001752 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001753 break;
1754 }
1755 }
1756 if (k < 0) {
1757 if (miranda_count == miranda_alloc) {
1758 miranda_alloc += 8;
1759 if (miranda_list.empty()) {
1760 miranda_list.resize(miranda_alloc);
1761 } else {
1762 miranda_list.resize(miranda_alloc);
1763 }
1764 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001765 Method* miranda_method = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001766 int mir;
1767 for (mir = 0; mir < miranda_count; mir++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001768 miranda_method = miranda_list[mir];
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001769 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001770 break;
1771 }
1772 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001773 // point the interface table at a phantom slot
1774 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001775 if (mir == miranda_count) {
1776 miranda_list[miranda_count++] = interface_method;
1777 }
1778 }
1779 }
1780 }
1781 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001782 int old_method_count = klass->NumVirtualMethods();
1783 int new_method_count = old_method_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001784 klass->SetVirtualMethods(
1785 klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001786
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001787 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1788 CHECK(vtable != NULL);
1789 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001790 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001791 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001792 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001793 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001794 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001796 meth->SetDeclaringClass(klass);
1797 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1798 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001799 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001800 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001801 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001802 // TODO: do not assign to the vtable field until it is fully constructed.
1803 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001804 }
1805 return true;
1806}
1807
1808void ClassLinker::LinkAbstractMethods(Class* klass) {
1809 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001810 Method* method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001811 if (method->IsAbstract()) {
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001812 LG << "AbstractMethodError";
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001813 // TODO: throw AbstractMethodError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001814 }
1815 }
1816}
1817
1818bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001819 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001820 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001821}
1822
1823bool ClassLinker::LinkStaticFields(Class* klass) {
1824 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001825 size_t allocated_class_size = klass->GetClassSize();
1826 bool success = LinkFields(klass, false);
1827 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001828 return success;
1829}
1830
Brian Carlstromdbc05252011-09-09 01:59:59 -07001831struct LinkFieldsComparator {
1832 bool operator()(const Field* field1, const Field* field2){
1833
1834 // First come reference fields, then 64-bit, and finally 32-bit
1835 const Class* type1 = field1->GetTypeDuringLinking();
1836 const Class* type2 = field2->GetTypeDuringLinking();
1837 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
1838 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
1839 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
1840 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
1841 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
1842 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
1843 if (order1 != order2) {
1844 return order1 < order2;
1845 }
1846
1847 // same basic group? then sort by string.
1848 std::string name1 = field1->GetName()->ToModifiedUtf8();
1849 std::string name2 = field2->GetName()->ToModifiedUtf8();
1850 return name1 < name2;
1851 }
1852};
1853
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001854bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001855 size_t num_fields =
1856 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1857
1858 ObjectArray<Field>* fields =
1859 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001860
1861 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07001862 size_t size;
1863 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001864 if (instance) {
1865 Class* super_class = klass->GetSuperClass();
1866 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001867 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001868 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001869 }
1870 size = field_offset.Uint32Value();
1871 } else {
1872 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07001873 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001874 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001875
Brian Carlstromdbc05252011-09-09 01:59:59 -07001876 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001877
Brian Carlstromdbc05252011-09-09 01:59:59 -07001878 // we want a relatively stable order so that adding new fields
1879 // minimizes distruption of C++ version such as Class and Method.
1880 std::deque<Field*> grouped_and_sorted_fields;
1881 for (size_t i = 0; i < num_fields; i++) {
1882 grouped_and_sorted_fields.push_back(fields->Get(i));
1883 }
1884 std::sort(grouped_and_sorted_fields.begin(),
1885 grouped_and_sorted_fields.end(),
1886 LinkFieldsComparator());
1887
1888 // References should be at the front.
1889 size_t current_field = 0;
1890 size_t num_reference_fields = 0;
1891 for (; current_field < num_fields; current_field++) {
1892 Field* field = grouped_and_sorted_fields.front();
1893 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001894 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07001895 bool isPrimitive = type != NULL && type->IsPrimitive();
1896 if (isPrimitive) {
1897 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001898 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001899 grouped_and_sorted_fields.pop_front();
1900 num_reference_fields++;
1901 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001902 field->SetOffset(field_offset);
1903 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001904 }
1905
1906 // Now we want to pack all of the double-wide fields together. If
1907 // we're not aligned, though, we want to shuffle one 32-bit field
1908 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001909 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
1910 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
1911 Field* field = grouped_and_sorted_fields[i];
1912 const Class* type = field->GetTypeDuringLinking();
1913 CHECK(type != NULL); // should only be working on primitive types
1914 DCHECK(type->IsPrimitive());
1915 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
1916 continue;
1917 }
1918 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001919 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001920 // drop the consumed field
1921 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
1922 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001923 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001924 // whether we found a 32-bit field for padding or not, we advance
1925 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001926 }
1927
1928 // Alignment is good, shuffle any double-wide fields forward, and
1929 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001930 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
1931 while (!grouped_and_sorted_fields.empty()) {
1932 Field* field = grouped_and_sorted_fields.front();
1933 grouped_and_sorted_fields.pop_front();
1934 const Class* type = field->GetTypeDuringLinking();
1935 CHECK(type != NULL); // should only be working on primitive types
1936 DCHECK(type->IsPrimitive());
1937 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001938 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001939 field_offset = MemberOffset(field_offset.Uint32Value() +
1940 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
1941 ? sizeof(uint64_t)
1942 : sizeof(uint32_t)));
1943 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001944 }
1945
1946#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001947 // Make sure that all reference fields appear before
1948 // non-reference fields, and all double-wide fields are aligned.
1949 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07001950 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001951 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001952 if (false) { // enable to debug field layout
1953 LOG(INFO) << "LinkFields:"
1954 << " class=" << klass->GetDescriptor()->ToModifiedUtf8()
1955 << " field=" << field->GetName()->ToModifiedUtf8()
1956 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
1957 }
1958 const Class* type = field->GetTypeDuringLinking();
1959 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001960 if (!seen_non_ref) {
1961 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001962 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001963 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001964 } else {
1965 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001966 }
1967 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001968 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001969 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001970 }
1971#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001972 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001973 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07001974 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001975 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001976 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001977 klass->SetObjectSize(size);
1978 }
1979 } else {
1980 klass->SetNumReferenceStaticFields(num_reference_fields);
1981 klass->SetClassSize(size);
1982 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001983 return true;
1984}
1985
1986// Set the bitmap of reference offsets, refOffsets, from the ifields
1987// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001988void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001989 uint32_t reference_offsets = 0;
1990 Class* super_class = klass->GetSuperClass();
1991 if (super_class != NULL) {
1992 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001993 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001994 if (reference_offsets == CLASS_WALK_SUPER) {
1995 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001996 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001997 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001998 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001999 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002000}
2001
2002void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002003 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002004}
2005
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002006void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2007 uint32_t reference_offsets) {
2008 size_t num_reference_fields =
2009 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2010 : klass->NumReferenceStaticFieldsDuringLinking();
2011 const ObjectArray<Field>* fields =
2012 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002013 // All of the fields that contain object references are guaranteed
2014 // to be at the beginning of the fields list.
2015 for (size_t i = 0; i < num_reference_fields; ++i) {
2016 // Note that byte_offset is the offset from the beginning of
2017 // object, not the offset into instance data
2018 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002019 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002020 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2021 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2022 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002023 CHECK_NE(new_bit, 0U);
2024 reference_offsets |= new_bit;
2025 } else {
2026 reference_offsets = CLASS_WALK_SUPER;
2027 break;
2028 }
2029 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002030 // Update fields in klass
2031 if (instance) {
2032 klass->SetReferenceInstanceOffsets(reference_offsets);
2033 } else {
2034 klass->SetReferenceStaticOffsets(reference_offsets);
2035 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002036}
2037
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002038String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002039 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002040 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 if (resolved != NULL) {
2042 return resolved;
2043 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002044 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2045 int32_t utf16_length = dex_file.GetStringLength(string_id);
2046 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002047 // TODO: remote the const_cast below
2048 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002049 dex_cache->SetResolvedString(string_idx, string);
2050 return string;
2051}
2052
2053Class* ClassLinker::ResolveType(const DexFile& dex_file,
2054 uint32_t type_idx,
2055 DexCache* dex_cache,
2056 const ClassLoader* class_loader) {
2057 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002058 if (resolved == NULL) {
2059 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2060 if (descriptor[1] == '\0') {
2061 // only the descriptors of primitive types should be 1 character long
2062 resolved = FindPrimitiveClass(descriptor[0]);
2063 } else {
2064 resolved = FindClass(descriptor, class_loader);
2065 }
2066 if (resolved != NULL) {
2067 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2068 if (dex_cache != check->GetDexCache()) {
2069 if (check->GetClassLoader() != NULL) {
2070 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
2071 resolved = NULL;
2072 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002073 }
2074 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002075 if (resolved != NULL) {
2076 dex_cache->SetResolvedType(type_idx, resolved);
2077 } else {
2078 DCHECK(Thread::Current()->IsExceptionPending());
2079 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002080 }
2081 return resolved;
2082}
2083
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002084Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2085 uint32_t method_idx,
2086 DexCache* dex_cache,
2087 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002088 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002089 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2090 if (resolved != NULL) {
2091 return resolved;
2092 }
2093 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2094 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2095 if (klass == NULL) {
2096 return NULL;
2097 }
2098
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002099 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002100 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002101 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002102 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002103 } else if (klass->IsInterface()) {
2104 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002105 } else {
2106 resolved = klass->FindVirtualMethod(name, signature);
2107 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002108 if (resolved != NULL) {
2109 dex_cache->SetResolvedMethod(method_idx, resolved);
2110 } else {
2111 // DCHECK(Thread::Current()->IsExceptionPending());
2112 }
2113 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002114}
2115
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002116Field* ClassLinker::ResolveField(const DexFile& dex_file,
2117 uint32_t field_idx,
2118 DexCache* dex_cache,
2119 const ClassLoader* class_loader,
2120 bool is_static) {
2121 Field* resolved = dex_cache->GetResolvedField(field_idx);
2122 if (resolved != NULL) {
2123 return resolved;
2124 }
2125 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2126 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2127 if (klass == NULL) {
2128 return NULL;
2129 }
2130
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002131 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002132 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2133 // TODO: LinkageError?
2134 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002135 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002136 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002137 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002138 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002139 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002140 if (resolved != NULL) {
2141 dex_cache->SetResolvedfield(field_idx, resolved);
2142 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002143 // TODO: DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002144 }
2145 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002146}
2147
Elliott Hughese27955c2011-08-26 15:21:24 -07002148size_t ClassLinker::NumLoadedClasses() const {
2149 MutexLock mu(classes_lock_);
2150 return classes_.size();
2151}
2152
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002153} // namespace art