blob: 6d5c6436d2797054e49a976207031ccb43d2d2e7 [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);
154 array_iftable_ = new InterfaceEntry[2];
155
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
198 // Object and String just need more minimal setup, since they do not have
199 // extra C++ fields.
200 java_lang_Object->SetStatus(Class::kStatusNotReady);
201 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
202 CHECK_EQ(java_lang_Object, Object_class);
203 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
204 java_lang_String->SetStatus(Class::kStatusNotReady);
205 Class* String_class = FindSystemClass("Ljava/lang/String;");
206 CHECK_EQ(java_lang_String, String_class);
207 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
208
209 // Setup the primitive array type classes - can't be done until Object has
210 // a vtable
211 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
212 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
213
214 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
215 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
216
217 Class* found_char_array_class = FindSystemClass("[C");
218 CHECK_EQ(char_array_class, found_char_array_class);
219
220 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
221 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
222
223 Class* found_int_array_class = FindSystemClass("[I");
224 CHECK_EQ(int_array_class, found_int_array_class);
225
226 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
227 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
228
229 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
230 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
231
232 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
233 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
234
235 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
236 CHECK_EQ(object_array_class, found_object_array_class);
237
238 // Setup the single, global copies of "interfaces" and "iftable"
239 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
240 CHECK(java_lang_Cloneable != NULL);
241 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
242 CHECK(java_io_Serializable != NULL);
243 CHECK(array_interfaces_ != NULL);
244 array_interfaces_->Set(0, java_lang_Cloneable);
245 array_interfaces_->Set(1, java_io_Serializable);
246 // We assume that Cloneable/Serializable don't have superinterfaces --
247 // normally we'd have to crawl up and explicitly list all of the
248 // supers as well. These interfaces don't have any methods, so we
249 // don't have to worry about the ifviPool either.
250 array_iftable_[0].SetInterface(array_interfaces_->Get(0));
251 array_iftable_[1].SetInterface(array_interfaces_->Get(1));
252
253 // Sanity check Object[]'s interfaces
254 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
255 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700256
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700257 // run Class, Field, and Method through FindSystemClass.
258 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700259 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700260 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700261 // No sanity check on size as Class is variably sized
262
263 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700264 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700265 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700266
267 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700268 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700269 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700270
271 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
272 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700273 java_lang_ref_FinalizerReference->SetAccessFlags(
274 java_lang_ref_FinalizerReference->GetAccessFlags() |
275 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700276 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700277 java_lang_ref_PhantomReference->SetAccessFlags(
278 java_lang_ref_PhantomReference->GetAccessFlags() |
279 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700280 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700281 java_lang_ref_SoftReference->SetAccessFlags(
282 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700283 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 java_lang_ref_WeakReference->SetAccessFlags(
285 java_lang_ref_WeakReference->GetAccessFlags() |
286 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700287
288 // Let the heap know some key offsets into java.lang.ref instances
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289 // NB we hard code the field indexes here rather than using FindInstanceField
290 // as the types of the field can't be resolved prior to the runtime being
291 // fully initialized
Brian Carlstrom1f870082011-08-23 16:02:11 -0700292 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700293
294 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
295 CHECK(pendingNext->GetName()->Equals("pendingNext"));
296 CHECK(ResolveType(pendingNext->GetTypeIdx(), pendingNext) ==
297 java_lang_ref_Reference);
298
299 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
300 CHECK(queue->GetName()->Equals("queue"));
301 CHECK(ResolveType(queue->GetTypeIdx(), queue) ==
302 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
303
304 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
305 CHECK(queueNext->GetName()->Equals("queueNext"));
306 CHECK(ResolveType(queueNext->GetTypeIdx(), queueNext) ==
307 java_lang_ref_Reference);
308
309 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
310 CHECK(referent->GetName()->Equals("referent"));
311 CHECK(ResolveType(referent->GetTypeIdx(), referent) ==
312 java_lang_Object);
313
314 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
315 CHECK(zombie->GetName()->Equals("zombie"));
316 CHECK(ResolveType(zombie->GetTypeIdx(), zombie) ==
317 java_lang_Object);
318
Brian Carlstrom1f870082011-08-23 16:02:11 -0700319 Heap::SetReferenceOffsets(referent->GetOffset(),
320 queue->GetOffset(),
321 queueNext->GetOffset(),
322 pendingNext->GetOffset(),
323 zombie->GetOffset());
324
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700325 // Setup the ClassLoaders, adjusting the object_size_ as necessary
326 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
327 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
328 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
329 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
330
331 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
332 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
333 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
334
335 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
336 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
337 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
338 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
339
340 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700341 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
342 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700343 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700344
Brian Carlstroma663ea52011-08-19 23:33:41 -0700345 FinishInit();
346}
347
348void ClassLinker::FinishInit() {
349 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700350 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700351 ClassRoot class_root = static_cast<ClassRoot>(i);
352 Class* klass = GetClassRoot(class_root);
353 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700355 // note SetClassRoot does additional validation.
356 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700357 }
358
359 // disable the slow paths in FindClass and CreatePrimitiveClass now
360 // that Object, Class, and Object[] are setup
361 init_done_ = true;
362}
363
Brian Carlstroma663ea52011-08-19 23:33:41 -0700364struct ClassLinker::InitCallbackState {
365 ClassLinker* class_linker;
366
367 Class* class_roots[kClassRootsMax];
368
369 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
370 Table descriptor_to_class_root;
371
Brian Carlstroma663ea52011-08-19 23:33:41 -0700372 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
373 Set dex_caches;
374};
375
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700376void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
377 const std::vector<const DexFile*>& class_path,
378 Space* space) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700379 CHECK(!init_done_);
380
381 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
382 DCHECK(heap_bitmap != NULL);
383
384 InitCallbackState state;
385 state.class_linker = this;
386 for (size_t i = 0; i < kClassRootsMax; i++) {
387 ClassRoot class_root = static_cast<ClassRoot>(i);
388 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
389 }
390
391 // reinit clases_ table
392 heap_bitmap->Walk(InitCallback, &state);
393
394 // reinit class_roots_
395 Class* object_array_class = state.class_roots[kObjectArrayClass];
396 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
397 for (size_t i = 0; i < kClassRootsMax; i++) {
398 ClassRoot class_root = static_cast<ClassRoot>(i);
399 SetClassRoot(class_root, state.class_roots[class_root]);
400 }
401
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700402 // reinit intern table
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700403 // TODO: remove interned_array, make all strings in image interned (and remove space argument)
Brian Carlstroma663ea52011-08-19 23:33:41 -0700404 ObjectArray<Object>* interned_array = space->GetImageHeader().GetInternedArray();
405 for (int32_t i = 0; i < interned_array->GetLength(); i++) {
406 String* string = interned_array->Get(i)->AsString();
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700407 intern_table_->RegisterStrong(string);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700408 }
409
410 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
412 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700413
414 // build a map from location to DexCache to match up with DexFile::GetLocation
415 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416 typedef InitCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700417 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
418 DexCache* dex_cache = *it;
419 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
420 location_to_dex_cache[location] = dex_cache;
421 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700422 CHECK_EQ(boot_class_path.size() + class_path.size(),
423 location_to_dex_cache.size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700424
425 // reinit boot_class_path with DexFile arguments and found DexCaches
426 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700427 const DexFile* dex_file = boot_class_path[i];
428 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700429 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700430 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700431 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700432 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700433
434 // register class_path with DexFile arguments and found DexCaches
435 for (size_t i = 0; i != class_path.size(); ++i) {
436 const DexFile* dex_file = class_path[i];
437 CHECK(dex_file != NULL);
438 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
439 CHECK(dex_cache != NULL) << dex_file->GetLocation();
440 RegisterDexFile(*dex_file, dex_cache);
441 }
442
Brian Carlstroma663ea52011-08-19 23:33:41 -0700443 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444 Field::SetClass(GetClassRoot(kJavaLangReflectField));
445 Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700446 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
447 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
448 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
449 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
450 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
451 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
452 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
453 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700454 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700455 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700456
457 FinishInit();
458}
459
Brian Carlstrom4873d462011-08-21 15:23:39 -0700460void ClassLinker::InitCallback(Object* obj, void *arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700461 DCHECK(obj != NULL);
462 DCHECK(arg != NULL);
463 InitCallbackState* state = reinterpret_cast<InitCallbackState*>(arg);
464
465 if (!obj->IsClass()) {
466 return;
467 }
468 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700469 // TODO: restore ClassLoader's list of DexFiles after image load
470 // CHECK(klass->GetClassLoader() == NULL);
471 const ClassLoader* class_loader = klass->GetClassLoader();
472 if (class_loader != NULL) {
473 // TODO: replace this hack with something based on command line arguments
474 Thread::Current()->SetClassLoaderOverride(class_loader);
475 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700476
477 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700478 // restore class to ClassLinker::classes_ table
479 state->class_linker->InsertClass(descriptor, klass);
480
481 // note DexCache to match with DexFile later
482 DexCache* dex_cache = klass->GetDexCache();
483 if (dex_cache != NULL) {
484 state->dex_caches.insert(dex_cache);
485 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700486 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700487 }
488
489 // check if this is a root, if so, register it
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700490 typedef InitCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700491 It it = state->descriptor_to_class_root.find(descriptor);
492 if (it != state->descriptor_to_class_root.end()) {
493 ClassRoot class_root = it->second;
494 state->class_roots[class_root] = klass;
495 }
496}
497
498// Keep in sync with InitCallback. Anything we visit, we need to
499// reinit references to when reinitializing a ClassLinker from a
500// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700501void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
502 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700503
504 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700505 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700506 }
507
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700508 {
509 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700510 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700511 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700512 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700513 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700514 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700515
Elliott Hughes410c0c82011-09-01 17:58:25 -0700516 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700517}
518
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700519ClassLinker::~ClassLinker() {
520 delete classes_lock_;
521 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700522 Field::ResetClass();
523 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700524 BooleanArray::ResetArrayClass();
525 ByteArray::ResetArrayClass();
526 CharArray::ResetArrayClass();
527 DoubleArray::ResetArrayClass();
528 FloatArray::ResetArrayClass();
529 IntArray::ResetArrayClass();
530 LongArray::ResetArrayClass();
531 ShortArray::ResetArrayClass();
532 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700533 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700534}
535
536DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700537 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700538 dex_cache->Init(String::AllocFromModifiedUtf8(dex_file.GetLocation().c_str()),
539 AllocObjectArray<String>(dex_file.NumStringIds()),
540 AllocObjectArray<Class>(dex_file.NumTypeIds()),
541 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700542 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700543 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
544 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700545 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700546}
547
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700548CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
549 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700550}
551
Brian Carlstrom4873d462011-08-21 15:23:39 -0700552Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
553 DCHECK_GE(class_size, sizeof(Class));
554 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
556 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700557 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700558}
559
Brian Carlstrom4873d462011-08-21 15:23:39 -0700560Class* ClassLinker::AllocClass(size_t class_size) {
561 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700562}
563
Jesse Wilson35baaab2011-08-10 16:18:03 -0400564Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700565 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700566}
567
568Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700569 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700570}
571
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700572ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
573 return ObjectArray<StackTraceElement>::Alloc(
574 GetClassRoot(kJavaLangStackTraceElementArrayClass),
575 length);
576}
577
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700578Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700579 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700580 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700581 if (class_loader != NULL) {
582 Class* klass = FindClass(descriptor, NULL);
583 if (klass != NULL) {
584 return klass;
585 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700586 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700587 }
588
Carl Shapirob5573532011-07-12 18:22:59 -0700589 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700590 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700591 CHECK(!self->IsExceptionPending());
592 // Find the class in the loaded classes table.
593 Class* klass = LookupClass(descriptor, class_loader);
594 if (klass == NULL) {
595 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700596 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700597 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700598 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700599 const DexFile::ClassPath& class_path = ((class_loader != NULL)
600 ? ClassLoader::GetClassPath(class_loader)
601 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700602 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700603 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700604 std::string name(PrintableString(descriptor));
605 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
606 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700607 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700608 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700609 const DexFile& dex_file = *pair.first;
610 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700611 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700612 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700613 if (!init_done_) {
614 // finish up init of hand crafted class_roots_
615 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700616 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700617 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700618 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400619 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700620 klass = GetClassRoot(kJavaLangString);
621 } else if (descriptor == "Ljava/lang/reflect/Field;") {
622 klass = GetClassRoot(kJavaLangReflectField);
623 } else if (descriptor == "Ljava/lang/reflect/Method;") {
624 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700625 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700626 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700627 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700628 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700629 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700630 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700631 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700632 klass->SetDexCache(dex_cache);
633 LoadClass(dex_file, dex_class_def, klass, class_loader);
634 // Check for a pending exception during load
635 if (self->IsExceptionPending()) {
636 // TODO: free native allocations in klass
637 return NULL;
638 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700639 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700640 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700641 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700642 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700643 if (!success) {
644 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700645 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700646 // TODO: free native allocations in klass
647 klass = LookupClass(descriptor, class_loader);
648 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700649 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700650 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700651 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700652 CHECK(!klass->IsLoaded());
653 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700654 // Loading failed.
655 // TODO: CHECK(self->IsExceptionPending());
656 lock.NotifyAll();
657 return NULL;
658 }
659 CHECK(klass->IsLoaded());
660 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700661 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700662 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700663 // Linking failed.
664 // TODO: CHECK(self->IsExceptionPending());
665 lock.NotifyAll();
666 return NULL;
667 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700668 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700669 }
670 }
671 }
672 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700673 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700674 ObjectLock lock(klass);
675 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700676 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700677 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700678 return NULL;
679 }
680 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700681 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700682 lock.Wait();
683 }
684 }
685 if (klass->IsErroneous()) {
686 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
687 return NULL;
688 }
689 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700690 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700691 CHECK(!self->IsExceptionPending());
692 return klass;
693}
694
Brian Carlstrom4873d462011-08-21 15:23:39 -0700695// Precomputes size that will be needed for Class, matching LinkStaticFields
696size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
697 const DexFile::ClassDef& dex_class_def) {
698 const byte* class_data = dex_file.GetClassData(dex_class_def);
699 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
700 size_t num_static_fields = header.static_fields_size_;
701 size_t num_ref = 0;
702 size_t num_32 = 0;
703 size_t num_64 = 0;
704 if (num_static_fields != 0) {
705 uint32_t last_idx = 0;
706 for (size_t i = 0; i < num_static_fields; ++i) {
707 DexFile::Field dex_field;
708 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
709 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
710 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
711 char c = descriptor[0];
712 if (c == 'L' || c == '[') {
713 num_ref++;
714 } else if (c == 'J' || c == 'D') {
715 num_64++;
716 } else {
717 num_32++;
718 }
719 }
720 }
721
722 // start with generic class data
723 size_t size = sizeof(Class);
724 // follow with reference fields which must be contiguous at start
725 size += (num_ref * sizeof(uint32_t));
726 // if there are 64-bit fields to add, make sure they are aligned
727 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
728 if (num_32 != 0) {
729 // use an available 32-bit field for padding
730 num_32--;
731 }
732 size += sizeof(uint32_t); // either way, we are adding a word
733 DCHECK_EQ(size, RoundUp(size, 8));
734 }
735 // tack on any 64-bit fields now that alignment is assured
736 size += (num_64 * sizeof(uint64_t));
737 // tack on any remaining 32-bit fields
738 size += (num_32 * sizeof(uint32_t));
739 return size;
740}
741
Brian Carlstromf615a612011-07-23 12:50:34 -0700742void ClassLinker::LoadClass(const DexFile& dex_file,
743 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700744 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700745 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700746 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700747 CHECK(klass->GetDexCache() != NULL);
748 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700749 const byte* class_data = dex_file.GetClassData(dex_class_def);
750 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700751
Brian Carlstromf615a612011-07-23 12:50:34 -0700752 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700753 CHECK(descriptor != NULL);
754
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700755 klass->SetClass(GetClassRoot(kJavaLangClass));
756 if (klass->GetDescriptor() != NULL) {
757 DCHECK(klass->GetDescriptor()->Equals(descriptor));
758 } else {
759 klass->SetDescriptor(String::AllocFromModifiedUtf8(descriptor));
760 }
761 uint32_t access_flags = dex_class_def.access_flags_;
762 // Make sure there aren't any "bonus" flags set, since we use them for runtime
763 // state.
764 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
765 klass->SetAccessFlags(access_flags);
766 klass->SetClassLoader(class_loader);
767 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
768 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700769
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700770 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700771
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700772 size_t num_static_fields = header.static_fields_size_;
773 size_t num_instance_fields = header.instance_fields_size_;
774 size_t num_direct_methods = header.direct_methods_size_;
775 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700776
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700777 klass->SetSourceFile(dex_file.dexGetSourceFile(dex_class_def));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700778
779 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700780 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700781
782 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700783 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700784 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700785 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700786 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700787 DexFile::Field dex_field;
788 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400789 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700790 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700791 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700792 }
793 }
794
795 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700796 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700797 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700798 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700799 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700800 DexFile::Field dex_field;
801 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400802 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700803 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700804 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700805 }
806 }
807
808 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700809 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700810 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700811 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700812 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700813 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700814 DexFile::Method dex_method;
815 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700816 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700817 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700818 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700819 // TODO: register maps
820 }
821 }
822
823 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700824 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700825 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700826 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700827 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700828 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700829 DexFile::Method dex_method;
830 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700831 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700832 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700833 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700834 // TODO: register maps
835 }
836 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700837}
838
Brian Carlstromf615a612011-07-23 12:50:34 -0700839void ClassLinker::LoadInterfaces(const DexFile& dex_file,
840 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700841 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700842 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700843 if (list != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700844 klass->SetInterfaces(AllocObjectArray<Class>(list->Size()));
845 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
846 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700847 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700848 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700849 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700850 }
851 }
852}
853
Brian Carlstromf615a612011-07-23 12:50:34 -0700854void ClassLinker::LoadField(const DexFile& dex_file,
855 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700856 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700857 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700858 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700859 dst->SetDeclaringClass(klass);
860 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
861 dst->SetTypeIdx(field_id.type_idx_);
862 dst->SetAccessFlags(src.access_flags_);
863
864 // In order to access primitive types using GetTypeDuringLinking we need to
865 // ensure they are resolved into the dex cache
866 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
867 if (descriptor[1] == '\0') {
868 // only the descriptors of primitive types should be 1 character long
869 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
870 DCHECK(resolved->IsPrimitive());
871 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700872}
873
Brian Carlstromf615a612011-07-23 12:50:34 -0700874void ClassLinker::LoadMethod(const DexFile& dex_file,
875 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700876 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700877 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700878 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700879 dst->SetDeclaringClass(klass);
880 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700881 {
882 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700883 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700884 dst->SetSignature(String::AllocFromModifiedUtf8(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700885 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700886 dst->SetProtoIdx(method_id.proto_idx_);
887 dst->SetCodeItemOffset(src.code_off_);
888 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
889 dst->SetShorty(shorty);
890 dst->SetAccessFlags(src.access_flags_);
891 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700892
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700893 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
894 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
895 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
896 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
897 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
898 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700899
Brian Carlstrom934486c2011-07-12 23:42:50 -0700900 // TODO: check for finalize method
901
Brian Carlstromf615a612011-07-23 12:50:34 -0700902 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700903 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700904 dst->SetNumRegisters(code_item->registers_size_);
905 dst->SetNumIns(code_item->ins_size_);
906 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700907 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700908 uint16_t num_args = Method::NumArgRegisters(shorty);
909 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700910 ++num_args;
911 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700912 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700913 // TODO: native methods
914 }
915}
916
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700917void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700918 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
919}
920
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700921void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700922 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700923 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700924 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700925}
926
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700927void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700928 RegisterDexFile(dex_file, AllocDexCache(dex_file));
929}
930
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700931void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700932 CHECK(dex_cache != NULL) << dex_file.GetLocation();
933 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700934 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700935 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700936}
937
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700938const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700939 for (size_t i = 0; i != dex_caches_.size(); ++i) {
940 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700941 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700942 }
943 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700944 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700945 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700946}
947
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700948DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstromf615a612011-07-23 12:50:34 -0700949 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700950 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700951 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700952 }
953 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700954 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700955 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700956}
957
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700958Class* ClassLinker::CreatePrimitiveClass(const char* descriptor,
959 Class::PrimitiveType type) {
960 // TODO: deduce one argument from the other
Brian Carlstrom4873d462011-08-21 15:23:39 -0700961 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700962 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700963 klass->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
964 klass->SetDescriptor(String::AllocFromModifiedUtf8(descriptor));
965 klass->SetPrimitiveType(type);
966 klass->SetStatus(Class::kStatusInitialized);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700967 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700968 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700969 return klass;
970}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700971
Brian Carlstrombe977852011-07-19 14:54:54 -0700972// Create an array class (i.e. the class object for the array, not the
973// array itself). "descriptor" looks like "[C" or "[[[[B" or
974// "[Ljava/lang/String;".
975//
976// If "descriptor" refers to an array of primitives, look up the
977// primitive type's internally-generated class object.
978//
979// "loader" is the class loader of the class that's referring to us. It's
980// used to ensure that we're looking for the element type in the right
981// context. It does NOT become the class loader for the array class; that
982// always comes from the base element class.
983//
984// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700985Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700986 const ClassLoader* class_loader) {
987 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700988
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700989 // Identify the underlying element class and the array dimension depth.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700990 Class* component_type = NULL;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700991 int array_rank;
992 if (descriptor[1] == '[') {
993 // array of arrays; keep descriptor and grab stuff from parent
994 Class* outer = FindClass(descriptor.substr(1), class_loader);
995 if (outer != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700996 // want the base class, not "outer", in our component_type
997 component_type = outer->GetComponentType();
998 array_rank = outer->GetArrayRank() + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700999 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001000 DCHECK(component_type == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001001 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001002 } else {
1003 array_rank = 1;
1004 if (descriptor[1] == 'L') {
1005 // array of objects; strip off "[" and look up descriptor.
1006 const StringPiece subDescriptor = descriptor.substr(1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001007 component_type = FindClass(subDescriptor, class_loader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001008 } else {
1009 // array of a primitive type
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001010 component_type = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001011 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001012 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001013
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001014 if (component_type == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001015 // failed
1016 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
1017 return NULL;
1018 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001019
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001020 // See if the component type is already loaded. Array classes are
1021 // always associated with the class loader of their underlying
1022 // element type -- an array of Strings goes with the loader for
1023 // java/lang/String -- so we need to look for it there. (The
1024 // caller should have checked for the existence of the class
1025 // before calling here, but they did so with *their* class loader,
1026 // not the component type's loader.)
1027 //
1028 // If we find it, the caller adds "loader" to the class' initiating
1029 // loader list, which should prevent us from going through this again.
1030 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001031 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001032 // are the same, because our caller (FindClass) just did the
1033 // lookup. (Even if we get this wrong we still have correct behavior,
1034 // because we effectively do this lookup again when we add the new
1035 // class to the hash table --- necessary because of possible races with
1036 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001037 if (class_loader != component_type->GetClassLoader()) {
1038 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001039 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001040 return new_class;
1041 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001042 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001043
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001044 // Fill out the fields in the Class.
1045 //
1046 // It is possible to execute some methods against arrays, because
1047 // all arrays are subclasses of java_lang_Object_, so we need to set
1048 // up a vtable. We can just point at the one in java_lang_Object_.
1049 //
1050 // Array classes are simple enough that we don't need to do a full
1051 // link step.
1052
1053 Class* new_class = NULL;
1054 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001055 // Classes that were hand created, ie not by FindSystemClass
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001056 if (descriptor == "[Ljava/lang/Object;") {
1057 new_class = GetClassRoot(kObjectArrayClass);
1058 } else if (descriptor == "[C") {
1059 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001060 } else if (descriptor == "[I") {
1061 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001062 }
1063 }
1064 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001065 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001066 if (new_class == NULL) {
1067 return NULL;
1068 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001069 new_class->SetArrayRank(array_rank);
1070 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001071 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001072 DCHECK_LE(1, new_class->GetArrayRank());
1073 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001074 if (new_class->GetDescriptor() != NULL) {
1075 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1076 } else {
1077 new_class->SetDescriptor(String::AllocFromModifiedUtf8(descriptor.ToString().c_str()));
1078 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001079 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001080 new_class->SetSuperClass(java_lang_Object);
1081 new_class->SetVTable(java_lang_Object->GetVTable());
1082 new_class->SetPrimitiveType(Class::kPrimNot);
1083 new_class->SetClassLoader(component_type->GetClassLoader());
1084 new_class->SetStatus(Class::kStatusInitialized);
1085 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001086 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001087
1088
1089 // All arrays have java/lang/Cloneable and java/io/Serializable as
1090 // interfaces. We need to set that up here, so that stuff like
1091 // "instanceof" works right.
1092 //
1093 // Note: The GC could run during the call to FindSystemClass,
1094 // so we need to make sure the class object is GC-valid while we're in
1095 // there. Do this by clearing the interface list so the GC will just
1096 // think that the entries are null.
1097
1098
1099 // Use the single, global copies of "interfaces" and "iftable"
1100 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001101 new_class->SetInterfaces(array_interfaces_);
1102 new_class->SetIFTableCount(2);
1103 new_class->SetIFTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001104
1105 // Inherit access flags from the component type. Arrays can't be
1106 // used as a superclass or interface, so we want to add "final"
1107 // and remove "interface".
1108 //
1109 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001110 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001111 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001112 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1113 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001114
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001115 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001116 return new_class;
1117 }
1118 // Another thread must have loaded the class after we
1119 // started but before we finished. Abandon what we've
1120 // done.
1121 //
1122 // (Yes, this happens.)
1123
1124 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001125 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001126 DCHECK(other_class != NULL);
1127 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001128}
1129
1130Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001131 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001132 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001133 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001134 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001135 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001136 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001137 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001138 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001139 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001140 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001141 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001142 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001143 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001144 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001145 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001146 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001147 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001148 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001149 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001150 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001151 std::string printable_type(PrintableChar(type));
1152 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1153 "Not a primitive type: %s", printable_type.c_str());
1154 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001155}
1156
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001157bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1158 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001159 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001160 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001161 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001162}
1163
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001164Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001165 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001166 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001167 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001168 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001169 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001170 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001171 return klass;
1172 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001173 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001174 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001175}
1176
1177bool ClassLinker::InitializeClass(Class* klass) {
1178 CHECK(klass->GetStatus() == Class::kStatusResolved ||
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001179 klass->GetStatus() == Class::kStatusError) << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001180
Carl Shapirob5573532011-07-12 18:22:59 -07001181 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001182
1183 {
1184 ObjectLock lock(klass);
1185
1186 if (klass->GetStatus() < Class::kStatusVerified) {
1187 if (klass->IsErroneous()) {
1188 LG << "re-initializing failed class"; // TODO: throw
1189 return false;
1190 }
1191
1192 CHECK(klass->GetStatus() == Class::kStatusResolved);
1193
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001194 klass->SetStatus(Class::kStatusVerifying);
jeffhaobdb76512011-09-07 11:43:16 -07001195 if (!DexVerifier::VerifyClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001196 LG << "Verification failed"; // TODO: ThrowVerifyError
1197 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001198 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001199 klass->SetStatus(Class::kStatusError);
1200 return false;
1201 }
1202
1203 klass->SetStatus(Class::kStatusVerified);
1204 }
1205
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001206 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001207 return true;
1208 }
1209
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001210 while (klass->GetStatus() == Class::kStatusInitializing) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001211 // we caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001212 if (klass->GetClinitThreadId() == self->GetTid()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001213 LG << "recursive <clinit>";
1214 return true;
1215 }
1216
1217 CHECK(!self->IsExceptionPending());
1218
1219 lock.Wait(); // TODO: check for interruption
1220
1221 // When we wake up, repeat the test for init-in-progress. If
1222 // there's an exception pending (only possible if
1223 // "interruptShouldThrow" was set), bail out.
1224 if (self->IsExceptionPending()) {
1225 CHECK(false);
1226 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1227 klass->SetStatus(Class::kStatusError);
1228 return false;
1229 }
1230 if (klass->GetStatus() == Class::kStatusInitializing) {
1231 continue;
1232 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001233 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001234 klass->GetStatus() == Class::kStatusError);
1235 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001236 // The caller wants an exception, but it was thrown in a
1237 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001238 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1239 return false;
1240 }
1241 return true; // otherwise, initialized
1242 }
1243
1244 // see if we failed previously
1245 if (klass->IsErroneous()) {
1246 // might be wise to unlock before throwing; depends on which class
1247 // it is that we have locked
1248
1249 // TODO: throwEarlierClassFailure(klass);
1250 return false;
1251 }
1252
1253 if (!ValidateSuperClassDescriptors(klass)) {
1254 klass->SetStatus(Class::kStatusError);
1255 return false;
1256 }
1257
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001258 DCHECK(klass->GetStatus() < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001259
Elliott Hughesdcc24742011-09-07 14:02:44 -07001260 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001261 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001262 }
1263
1264 if (!InitializeSuperClass(klass)) {
1265 return false;
1266 }
1267
1268 InitializeStaticFields(klass);
1269
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001270 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001271 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001272 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001273 }
1274
1275 {
1276 ObjectLock lock(klass);
1277
1278 if (self->IsExceptionPending()) {
1279 klass->SetStatus(Class::kStatusError);
1280 } else {
1281 klass->SetStatus(Class::kStatusInitialized);
1282 }
1283 lock.NotifyAll();
1284 }
1285
1286 return true;
1287}
1288
1289bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1290 if (klass->IsInterface()) {
1291 return true;
1292 }
1293 // begin with the methods local to the superclass
1294 if (klass->HasSuperClass() &&
1295 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1296 const Class* super = klass->GetSuperClass();
1297 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001298 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001299 if (method != super->GetVirtualMethod(i) &&
1300 !HasSameMethodDescriptorClasses(method, super, klass)) {
1301 LG << "Classes resolve differently in superclass";
1302 return false;
1303 }
1304 }
1305 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001306 for (size_t i = 0; i < klass->GetIFTableCount(); ++i) {
1307 const InterfaceEntry* iftable = &klass->GetIFTable()[i];
Brian Carlstrom30b94452011-08-25 21:35:26 -07001308 Class* interface = iftable->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001309 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1310 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001311 uint32_t vtable_index = iftable->GetMethodIndexArray()[j];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001312 const Method* method = klass->GetVirtualMethod(vtable_index);
1313 if (!HasSameMethodDescriptorClasses(method, interface,
1314 method->GetClass())) {
1315 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1316 return false;
1317 }
1318 }
1319 }
1320 }
1321 return true;
1322}
1323
1324bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001325 const Class* klass1,
1326 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001327 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001328 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001329 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001330 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001331 const char* descriptor = it->GetDescriptor();
1332 if (descriptor == NULL) {
1333 break;
1334 }
1335 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1336 // Found a non-primitive type.
1337 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1338 return false;
1339 }
1340 }
1341 }
1342 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001343 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001344 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1345 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1346 return false;
1347 }
1348 }
1349 return true;
1350}
1351
1352// Returns true if classes referenced by the descriptor are the
1353// same classes in klass1 as they are in klass2.
1354bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001355 const Class* klass1,
1356 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001357 CHECK(descriptor != NULL);
1358 CHECK(klass1 != NULL);
1359 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001360 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001361 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001362 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001363 // TODO: found2 == NULL
1364 // TODO: lookup found1 in initiating loader list
1365 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001366 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001367 if (found1 == found2) {
1368 return true;
1369 } else {
1370 return false;
1371 }
1372 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001373 return true;
1374}
1375
1376bool ClassLinker::InitializeSuperClass(Class* klass) {
1377 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001378 if (!klass->IsInterface() && klass->HasSuperClass()) {
1379 Class* super_class = klass->GetSuperClass();
1380 if (super_class->GetStatus() != Class::kStatusInitialized) {
1381 CHECK(!super_class->IsInterface());
1382 klass->MonitorExit();
1383 bool super_initialized = InitializeClass(super_class);
1384 klass->MonitorEnter();
1385 // TODO: check for a pending exception
1386 if (!super_initialized) {
1387 klass->SetStatus(Class::kStatusError);
1388 klass->NotifyAll();
1389 return false;
1390 }
1391 }
1392 }
1393 return true;
1394}
1395
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001396bool ClassLinker::EnsureInitialized(Class* c) {
1397 CHECK(c != NULL);
1398 if (c->IsInitialized()) {
1399 return true;
1400 }
1401
1402 c->MonitorExit();
1403 InitializeClass(c);
1404 c->MonitorEnter();
1405 return !Thread::Current()->IsExceptionPending();
1406}
1407
Brian Carlstromb9edb842011-08-28 16:31:06 -07001408StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1409 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001410 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1411 Class* klass = class_linker->ResolveType(type_idx, referrer);
1412 if (klass == NULL) {
1413 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1414 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001415 // If we are the <clinit> of this class, just return our storage.
1416 //
1417 // Do not set the DexCache InitializedStaticStorage, since that
1418 // implies <clinit> has finished running.
1419 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1420 return klass;
1421 }
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001422 if (!class_linker->EnsureInitialized(klass)) {
1423 CHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001424 UNIMPLEMENTED(FATAL) << "throw exception due to class initialization problem";
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001425 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001426 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001427 return klass;
1428}
1429
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001430void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1431 Class* c, std::map<int, Field*>& field_map) {
1432 const ClassLoader* cl = c->GetClassLoader();
1433 const byte* class_data = dex_file.GetClassData(dex_class_def);
1434 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1435 uint32_t last_idx = 0;
1436 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1437 DexFile::Field dex_field;
1438 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1439 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1440 }
1441}
1442
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001443void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001444 size_t num_static_fields = klass->NumStaticFields();
1445 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001446 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001447 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001448 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001449 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001450 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001451 return;
1452 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001453 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001454 const DexFile& dex_file = FindDexFile(dex_cache);
1455 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001456 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001457
1458 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1459 std::map<int, Field*> field_map;
1460 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1461
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001462 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001463 if (addr == NULL) {
1464 // All this class' static fields have default values.
1465 return;
1466 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001467 size_t array_size = DecodeUnsignedLeb128(&addr);
1468 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001469 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001470 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001471 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001472 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001473 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001474 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001475 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001476 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001477 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001478 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001479 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001480 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001481 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001482 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001483 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001484 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001485 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001486 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001487 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001488 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001489 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001490 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001491 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001492 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001493 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001494 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001495 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001496 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001497 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001498 break;
1499 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001500 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001501 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001502 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001503 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001504 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001505 break;
1506 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001507 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001508 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001509 }
1510}
1511
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001512bool ClassLinker::LinkClass(Class* klass) {
1513 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001514 if (!LinkSuperClass(klass)) {
1515 return false;
1516 }
1517 if (!LinkMethods(klass)) {
1518 return false;
1519 }
1520 if (!LinkInstanceFields(klass)) {
1521 return false;
1522 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001523 if (!LinkStaticFields(klass)) {
1524 return false;
1525 }
1526 CreateReferenceInstanceOffsets(klass);
1527 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001528 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1529 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001530 return true;
1531}
1532
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001533bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001534 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1535 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1536 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001537 if (super_class == NULL) {
1538 LG << "Failed to resolve superclass";
1539 return false;
1540 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001541 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001542 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001543 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1544 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1545 Class *interface = ResolveType(dex_file, idx, klass);
1546 klass->SetInterface(i, interface);
1547 if (interface == NULL) {
1548 LG << "Failed to resolve interface";
1549 return false;
1550 }
1551 // Verify
1552 if (!klass->CanAccess(interface)) {
1553 LG << "Inaccessible interface";
1554 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001555 }
1556 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001557 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001558 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001559 return true;
1560}
1561
1562bool ClassLinker::LinkSuperClass(Class* klass) {
1563 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001564 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001565 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001566 if (super != NULL) {
1567 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1568 return false;
1569 }
1570 // TODO: clear finalize attribute
1571 return true;
1572 }
1573 if (super == NULL) {
1574 LG << "No superclass defined"; // TODO: LinkageError
1575 return false;
1576 }
1577 // Verify
1578 if (super->IsFinal()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001579 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001580 return false;
1581 }
1582 if (super->IsInterface()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001583 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001584 return false;
1585 }
1586 if (!klass->CanAccess(super)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001587 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001588 return false;
1589 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001590#ifndef NDEBUG
1591 // Ensure super classes are fully resolved prior to resolving fields..
1592 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001593 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001594 super = super->GetSuperClass();
1595 }
1596#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001597 return true;
1598}
1599
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001600// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001601bool ClassLinker::LinkMethods(Class* klass) {
1602 if (klass->IsInterface()) {
1603 // No vtable.
1604 size_t count = klass->NumVirtualMethods();
1605 if (!IsUint(16, count)) {
1606 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1607 return false;
1608 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001609 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001610 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001611 }
jeffhaobdb76512011-09-07 11:43:16 -07001612 // Link interface method tables
1613 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001614 } else {
1615 // Link virtual method tables
1616 LinkVirtualMethods(klass);
1617
1618 // Link interface method tables
1619 LinkInterfaceMethods(klass);
1620
1621 // Insert stubs.
1622 LinkAbstractMethods(klass);
1623 }
1624 return true;
1625}
1626
1627bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001628 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001629 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1630 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001631 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001632 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001633 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001634 // See if any of our virtual methods override the superclass.
1635 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001636 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001637 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001638 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001639 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001640 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001641 // Verify
1642 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001643 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001644 return false;
1645 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001646 vtable->Set(j, local_method);
1647 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001648 break;
1649 }
1650 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001651 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001652 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001653 vtable->Set(actual_count, local_method);
1654 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001655 actual_count += 1;
1656 }
1657 }
1658 if (!IsUint(16, actual_count)) {
1659 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1660 return false;
1661 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001662 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001663 CHECK_LE(actual_count, max_count);
1664 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001665 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001666 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001667 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001668 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001669 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001670 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001671 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001672 LG << "Too many methods"; // TODO: VirtualMachineError
1673 return false;
1674 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001675 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001676 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001677 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1678 vtable->Set(i, virtual_method);
1679 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001680 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001681 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001682 }
1683 return true;
1684}
1685
1686bool ClassLinker::LinkInterfaceMethods(Class* klass) {
1687 int pool_offset = 0;
1688 int pool_size = 0;
1689 int miranda_count = 0;
1690 int miranda_alloc = 0;
1691 size_t super_ifcount;
1692 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001693 super_ifcount = klass->GetSuperClass()->GetIFTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001694 } else {
1695 super_ifcount = 0;
1696 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001697 size_t ifcount = super_ifcount;
1698 ifcount += klass->NumInterfaces();
1699 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001700 ifcount += klass->GetInterface(i)->GetIFTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001701 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001702 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001703 // TODO: enable these asserts with klass status validation
1704 // DCHECK(klass->GetIFTableCount() == 0);
1705 // DCHECK(klass->GetIFTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001706 return true;
1707 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001708 InterfaceEntry* iftable = new InterfaceEntry[ifcount];
1709 memset(iftable, 0x00, sizeof(InterfaceEntry) * ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710 if (super_ifcount != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001711 memcpy(iftable, klass->GetSuperClass()->GetIFTable(),
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001712 sizeof(InterfaceEntry) * super_ifcount);
1713 }
1714 // Flatten the interface inheritance hierarchy.
1715 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001716 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1717 Class* interf = klass->GetInterface(i);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001718 DCHECK(interf != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001719 if (!interf->IsInterface()) {
1720 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1721 return false;
1722 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001723 iftable[idx++].SetInterface(interf);
1724 for (size_t j = 0; j < interf->GetIFTableCount(); j++) {
1725 iftable[idx++].SetInterface(interf->GetIFTable()[j].GetInterface());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001726 }
1727 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001728 klass->SetIFTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001729 CHECK_EQ(idx, ifcount);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001730 klass->SetIFTableCount(ifcount);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001731 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001732 return true;
1733 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001734 for (size_t i = super_ifcount; i < ifcount; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001735 pool_size += iftable[i].GetInterface()->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001736 }
1737 if (pool_size == 0) {
1738 return true;
1739 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001740 klass->SetIfviPoolCount(pool_size);
1741 uint32_t* ifvi_pool = new uint32_t[pool_size];
1742 klass->SetIfviPool(ifvi_pool);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001743 std::vector<Method*> miranda_list;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001744 for (size_t i = super_ifcount; i < ifcount; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001745 iftable[i].SetMethodIndexArray(ifvi_pool + pool_offset);
1746 Class* interface = iftable[i].GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001747 pool_offset += interface->NumVirtualMethods(); // end here
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001748 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001749 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1750 Method* interface_method = interface->GetVirtualMethod(j);
1751 int k; // must be signed
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001752 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1753 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001754 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1755 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001756 LG << "Implementation not public";
1757 return false;
1758 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001759 iftable[i].GetMethodIndexArray()[j] = k;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001760 break;
1761 }
1762 }
1763 if (k < 0) {
1764 if (miranda_count == miranda_alloc) {
1765 miranda_alloc += 8;
1766 if (miranda_list.empty()) {
1767 miranda_list.resize(miranda_alloc);
1768 } else {
1769 miranda_list.resize(miranda_alloc);
1770 }
1771 }
1772 int mir;
1773 for (mir = 0; mir < miranda_count; mir++) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001774 Method* miranda_method = miranda_list[mir];
1775 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001776 break;
1777 }
1778 }
1779 // point the interface table at a phantom slot index
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001780 iftable[i].GetMethodIndexArray()[j] =
1781 vtable->GetLength() + mir;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001782 if (mir == miranda_count) {
1783 miranda_list[miranda_count++] = interface_method;
1784 }
1785 }
1786 }
1787 }
1788 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001789 int old_method_count = klass->NumVirtualMethods();
1790 int new_method_count = old_method_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001791 klass->SetVirtualMethods(
1792 klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001793
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001794 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1795 CHECK(vtable != NULL);
1796 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001797 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001798 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001799 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001800 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001801 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001802 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001803 meth->SetDeclaringClass(klass);
1804 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1805 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001806 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001807 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001808 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001809 // TODO: do not assign to the vtable field until it is fully constructed.
1810 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001811 }
1812 return true;
1813}
1814
1815void ClassLinker::LinkAbstractMethods(Class* klass) {
1816 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001817 Method* method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001818 if (method->IsAbstract()) {
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001819 LG << "AbstractMethodError";
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001820 // TODO: throw AbstractMethodError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001821 }
1822 }
1823}
1824
1825bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001826 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001827 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001828}
1829
1830bool ClassLinker::LinkStaticFields(Class* klass) {
1831 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001832 size_t allocated_class_size = klass->GetClassSize();
1833 bool success = LinkFields(klass, false);
1834 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001835 return success;
1836}
1837
Brian Carlstromdbc05252011-09-09 01:59:59 -07001838struct LinkFieldsComparator {
1839 bool operator()(const Field* field1, const Field* field2){
1840
1841 // First come reference fields, then 64-bit, and finally 32-bit
1842 const Class* type1 = field1->GetTypeDuringLinking();
1843 const Class* type2 = field2->GetTypeDuringLinking();
1844 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
1845 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
1846 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
1847 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
1848 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
1849 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
1850 if (order1 != order2) {
1851 return order1 < order2;
1852 }
1853
1854 // same basic group? then sort by string.
1855 std::string name1 = field1->GetName()->ToModifiedUtf8();
1856 std::string name2 = field2->GetName()->ToModifiedUtf8();
1857 return name1 < name2;
1858 }
1859};
1860
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001861bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001862 size_t num_fields =
1863 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1864
1865 ObjectArray<Field>* fields =
1866 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001867
1868 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07001869 size_t size;
1870 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001871 if (instance) {
1872 Class* super_class = klass->GetSuperClass();
1873 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001874 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001875 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001876 }
1877 size = field_offset.Uint32Value();
1878 } else {
1879 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07001880 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001881 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001882
Brian Carlstromdbc05252011-09-09 01:59:59 -07001883 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001884
Brian Carlstromdbc05252011-09-09 01:59:59 -07001885 // we want a relatively stable order so that adding new fields
1886 // minimizes distruption of C++ version such as Class and Method.
1887 std::deque<Field*> grouped_and_sorted_fields;
1888 for (size_t i = 0; i < num_fields; i++) {
1889 grouped_and_sorted_fields.push_back(fields->Get(i));
1890 }
1891 std::sort(grouped_and_sorted_fields.begin(),
1892 grouped_and_sorted_fields.end(),
1893 LinkFieldsComparator());
1894
1895 // References should be at the front.
1896 size_t current_field = 0;
1897 size_t num_reference_fields = 0;
1898 for (; current_field < num_fields; current_field++) {
1899 Field* field = grouped_and_sorted_fields.front();
1900 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001901 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07001902 bool isPrimitive = type != NULL && type->IsPrimitive();
1903 if (isPrimitive) {
1904 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001905 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001906 grouped_and_sorted_fields.pop_front();
1907 num_reference_fields++;
1908 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001909 field->SetOffset(field_offset);
1910 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001911 }
1912
1913 // Now we want to pack all of the double-wide fields together. If
1914 // we're not aligned, though, we want to shuffle one 32-bit field
1915 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001916 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
1917 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
1918 Field* field = grouped_and_sorted_fields[i];
1919 const Class* type = field->GetTypeDuringLinking();
1920 CHECK(type != NULL); // should only be working on primitive types
1921 DCHECK(type->IsPrimitive());
1922 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
1923 continue;
1924 }
1925 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001926 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001927 // drop the consumed field
1928 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
1929 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001930 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001931 // whether we found a 32-bit field for padding or not, we advance
1932 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001933 }
1934
1935 // Alignment is good, shuffle any double-wide fields forward, and
1936 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001937 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
1938 while (!grouped_and_sorted_fields.empty()) {
1939 Field* field = grouped_and_sorted_fields.front();
1940 grouped_and_sorted_fields.pop_front();
1941 const Class* type = field->GetTypeDuringLinking();
1942 CHECK(type != NULL); // should only be working on primitive types
1943 DCHECK(type->IsPrimitive());
1944 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001945 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001946 field_offset = MemberOffset(field_offset.Uint32Value() +
1947 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
1948 ? sizeof(uint64_t)
1949 : sizeof(uint32_t)));
1950 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001951 }
1952
1953#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001954 // Make sure that all reference fields appear before
1955 // non-reference fields, and all double-wide fields are aligned.
1956 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07001957 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001958 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001959 if (false) { // enable to debug field layout
1960 LOG(INFO) << "LinkFields:"
1961 << " class=" << klass->GetDescriptor()->ToModifiedUtf8()
1962 << " field=" << field->GetName()->ToModifiedUtf8()
1963 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
1964 }
1965 const Class* type = field->GetTypeDuringLinking();
1966 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001967 if (!seen_non_ref) {
1968 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001969 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001970 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001971 } else {
1972 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001973 }
1974 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001975 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001976 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001977 }
1978#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001979 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001980 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07001981 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001982 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001983 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001984 klass->SetObjectSize(size);
1985 }
1986 } else {
1987 klass->SetNumReferenceStaticFields(num_reference_fields);
1988 klass->SetClassSize(size);
1989 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001990 return true;
1991}
1992
1993// Set the bitmap of reference offsets, refOffsets, from the ifields
1994// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001995void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001996 uint32_t reference_offsets = 0;
1997 Class* super_class = klass->GetSuperClass();
1998 if (super_class != NULL) {
1999 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002000 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002001 if (reference_offsets == CLASS_WALK_SUPER) {
2002 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002003 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002004 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002005 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002006 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002007}
2008
2009void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002010 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002011}
2012
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002013void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2014 uint32_t reference_offsets) {
2015 size_t num_reference_fields =
2016 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2017 : klass->NumReferenceStaticFieldsDuringLinking();
2018 const ObjectArray<Field>* fields =
2019 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002020 // All of the fields that contain object references are guaranteed
2021 // to be at the beginning of the fields list.
2022 for (size_t i = 0; i < num_reference_fields; ++i) {
2023 // Note that byte_offset is the offset from the beginning of
2024 // object, not the offset into instance data
2025 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002026 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002027 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2028 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2029 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002030 CHECK_NE(new_bit, 0U);
2031 reference_offsets |= new_bit;
2032 } else {
2033 reference_offsets = CLASS_WALK_SUPER;
2034 break;
2035 }
2036 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002037 // Update fields in klass
2038 if (instance) {
2039 klass->SetReferenceInstanceOffsets(reference_offsets);
2040 } else {
2041 klass->SetReferenceStaticOffsets(reference_offsets);
2042 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002043}
2044
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002045String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002046 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002047 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002048 if (resolved != NULL) {
2049 return resolved;
2050 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002051 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2052 int32_t utf16_length = dex_file.GetStringLength(string_id);
2053 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002054 // TODO: remote the const_cast below
2055 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002056 dex_cache->SetResolvedString(string_idx, string);
2057 return string;
2058}
2059
2060Class* ClassLinker::ResolveType(const DexFile& dex_file,
2061 uint32_t type_idx,
2062 DexCache* dex_cache,
2063 const ClassLoader* class_loader) {
2064 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002065 if (resolved == NULL) {
2066 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2067 if (descriptor[1] == '\0') {
2068 // only the descriptors of primitive types should be 1 character long
2069 resolved = FindPrimitiveClass(descriptor[0]);
2070 } else {
2071 resolved = FindClass(descriptor, class_loader);
2072 }
2073 if (resolved != NULL) {
2074 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2075 if (dex_cache != check->GetDexCache()) {
2076 if (check->GetClassLoader() != NULL) {
2077 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
2078 resolved = NULL;
2079 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002080 }
2081 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002082 if (resolved != NULL) {
2083 dex_cache->SetResolvedType(type_idx, resolved);
2084 } else {
2085 DCHECK(Thread::Current()->IsExceptionPending());
2086 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002087 }
2088 return resolved;
2089}
2090
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002091Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2092 uint32_t method_idx,
2093 DexCache* dex_cache,
2094 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002095 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002096 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2097 if (resolved != NULL) {
2098 return resolved;
2099 }
2100 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2101 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2102 if (klass == NULL) {
2103 return NULL;
2104 }
2105
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002106 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002107 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002108 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002109 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002110 } else if (klass->IsInterface()) {
2111 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002112 } else {
2113 resolved = klass->FindVirtualMethod(name, signature);
2114 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002115 if (resolved != NULL) {
2116 dex_cache->SetResolvedMethod(method_idx, resolved);
2117 } else {
2118 // DCHECK(Thread::Current()->IsExceptionPending());
2119 }
2120 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002121}
2122
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002123Field* ClassLinker::ResolveField(const DexFile& dex_file,
2124 uint32_t field_idx,
2125 DexCache* dex_cache,
2126 const ClassLoader* class_loader,
2127 bool is_static) {
2128 Field* resolved = dex_cache->GetResolvedField(field_idx);
2129 if (resolved != NULL) {
2130 return resolved;
2131 }
2132 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2133 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2134 if (klass == NULL) {
2135 return NULL;
2136 }
2137
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002138 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002139 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2140 // TODO: LinkageError?
2141 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002142 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002143 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002144 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002145 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002146 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002147 if (resolved != NULL) {
2148 dex_cache->SetResolvedfield(field_idx, resolved);
2149 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002150 // TODO: DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002151 }
2152 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002153}
2154
Elliott Hughese27955c2011-08-26 15:21:24 -07002155size_t ClassLinker::NumLoadedClasses() const {
2156 MutexLock mu(classes_lock_);
2157 return classes_.size();
2158}
2159
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002160} // namespace art