blob: f25bac0040803895df9ddafeda0d3b40648b0375 [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,
Brian Carlstromc74255f2011-09-11 22:47:39 -070061 InternTable* intern_table, bool image) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070062 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -070063 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstromc74255f2011-09-11 22:47:39 -070064 if (image) {
65 class_linker->InitFromImage(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -070066 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -070067 class_linker->Init(boot_class_path, class_path);
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 Carlstrom16192862011-09-12 17:50:06 -070074 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070075 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070076 array_interfaces_(NULL),
77 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -070078 init_done_(false),
79 intern_table_(intern_table) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070080}
Brian Carlstroma663ea52011-08-19 23:33:41 -070081
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070082void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
83 const std::vector<const DexFile*>& class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070084 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070085
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070086 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070087 Class* java_lang_Class = down_cast<Class*>(
88 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070089 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070090 java_lang_Class->SetClass(java_lang_Class);
91 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070092 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -070093
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070094 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -070095 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070096 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070097 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070098 java_lang_Class->SetSuperClass(java_lang_Object);
99 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700100
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700101 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700102 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700103 object_array_class->SetArrayRank(1);
104 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700105
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700106 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700107 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700108 char_array_class->SetArrayRank(1);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700109 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700110
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700111 // Setup String
112 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
113 String::SetClass(java_lang_String);
114 java_lang_String->SetObjectSize(sizeof(String));
115 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400116
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700117 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700118 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
119 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
120 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
121 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
122 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700123
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700124 // Create storage for root classes, save away our work so far (requires
125 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700126 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700127 SetClassRoot(kJavaLangClass, java_lang_Class);
128 SetClassRoot(kJavaLangObject, java_lang_Object);
129 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700130 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700131 SetClassRoot(kJavaLangString, java_lang_String);
132
133 // Setup the primitive type classes.
134 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
135 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
136 SetClassRoot(kPrimitiveChar, CreatePrimitiveClass("C", Class::kPrimChar));
137 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
138 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
139 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
140 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
141 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
142 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
143
144 // Backfill component type of char[]
145 char_array_class->SetComponentType(GetClassRoot(kPrimitiveChar));
146
147 // Create array interface entries to populate once we can load system classes
148 array_interfaces_ = AllocObjectArray<Class>(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700149 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700150
151 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
152 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
153 int_array_class->SetArrayRank(1);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700154 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700155 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
156 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700157 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700158
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700159 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700160
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700161 // setup boot_class_path_ and register class_path now that we can
162 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700163 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700164 const DexFile* dex_file = boot_class_path[i];
165 CHECK(dex_file != NULL);
166 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700167 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700168 for (size_t i = 0; i != class_path.size(); ++i) {
169 const DexFile* dex_file = class_path[i];
170 CHECK(dex_file != NULL);
171 RegisterDexFile(*dex_file);
172 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700173
174 // Field and Method are necessary so that FindClass can link members
175 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
176 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700177 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700178 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
179 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
180 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
181 Field::SetClass(java_lang_reflect_Field);
182
183 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700184 java_lang_reflect_Method->SetDescriptor(
185 intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700186 CHECK(java_lang_reflect_Method != NULL);
187 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
188 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
189 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
190 Method::SetClass(java_lang_reflect_Method);
191
192 // now we can use FindSystemClass
193
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700194 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700195 java_lang_Object->SetStatus(Class::kStatusNotReady);
196 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
197 CHECK_EQ(java_lang_Object, Object_class);
198 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
199 java_lang_String->SetStatus(Class::kStatusNotReady);
200 Class* String_class = FindSystemClass("Ljava/lang/String;");
201 CHECK_EQ(java_lang_String, String_class);
202 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
203
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700204 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700205 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
206 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
207
208 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
209 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
210
211 Class* found_char_array_class = FindSystemClass("[C");
212 CHECK_EQ(char_array_class, found_char_array_class);
213
214 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
215 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
216
217 Class* found_int_array_class = FindSystemClass("[I");
218 CHECK_EQ(int_array_class, found_int_array_class);
219
220 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
221 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
222
223 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
224 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
225
226 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
227 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
228
229 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
230 CHECK_EQ(object_array_class, found_object_array_class);
231
232 // Setup the single, global copies of "interfaces" and "iftable"
233 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
234 CHECK(java_lang_Cloneable != NULL);
235 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
236 CHECK(java_io_Serializable != NULL);
237 CHECK(array_interfaces_ != NULL);
238 array_interfaces_->Set(0, java_lang_Cloneable);
239 array_interfaces_->Set(1, java_io_Serializable);
240 // We assume that Cloneable/Serializable don't have superinterfaces --
241 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700242 // supers as well.
243 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
244 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700245
246 // Sanity check Object[]'s interfaces
247 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
248 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700249
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700250 // run Class, Field, and Method through FindSystemClass.
251 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700252 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700253 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254
255 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700256 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700257 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258
259 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700260 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700261 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700262
263 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
264 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700265 java_lang_ref_FinalizerReference->SetAccessFlags(
266 java_lang_ref_FinalizerReference->GetAccessFlags() |
267 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700268 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700269 java_lang_ref_PhantomReference->SetAccessFlags(
270 java_lang_ref_PhantomReference->GetAccessFlags() |
271 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700272 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700273 java_lang_ref_SoftReference->SetAccessFlags(
274 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700275 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700276 java_lang_ref_WeakReference->SetAccessFlags(
277 java_lang_ref_WeakReference->GetAccessFlags() |
278 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700279
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700280 // Setup the ClassLoaders, adjusting the object_size_ as necessary
281 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
282 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
283 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
284 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
285
286 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
287 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
288 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
289
290 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
291 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
292 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
293 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
294
295 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700296 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
297 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700298 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700299
Brian Carlstroma663ea52011-08-19 23:33:41 -0700300 FinishInit();
301}
302
303void ClassLinker::FinishInit() {
Brian Carlstrom16192862011-09-12 17:50:06 -0700304
305 // Let the heap know some key offsets into java.lang.ref instances
306 // NB we hard code the field indexes here rather than using FindInstanceField
307 // as the types of the field can't be resolved prior to the runtime being
308 // fully initialized
309 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
310 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
311
312 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
313 CHECK(pendingNext->GetName()->Equals("pendingNext"));
314 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
315
316 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
317 CHECK(queue->GetName()->Equals("queue"));
318 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
319 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
320
321 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
322 CHECK(queueNext->GetName()->Equals("queueNext"));
323 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
324
325 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
326 CHECK(referent->GetName()->Equals("referent"));
327 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
328
329 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
330 CHECK(zombie->GetName()->Equals("zombie"));
331 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
332
333 Heap::SetReferenceOffsets(referent->GetOffset(),
334 queue->GetOffset(),
335 queueNext->GetOffset(),
336 pendingNext->GetOffset(),
337 zombie->GetOffset());
338
Brian Carlstroma663ea52011-08-19 23:33:41 -0700339 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700340 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700341 ClassRoot class_root = static_cast<ClassRoot>(i);
342 Class* klass = GetClassRoot(class_root);
343 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700345 // note SetClassRoot does additional validation.
346 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700347 }
348
349 // disable the slow paths in FindClass and CreatePrimitiveClass now
350 // that Object, Class, and Object[] are setup
351 init_done_ = true;
352}
353
Brian Carlstromc74255f2011-09-11 22:47:39 -0700354struct ClassLinker::InitFromImageCallbackState {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700355 ClassLinker* class_linker;
356
357 Class* class_roots[kClassRootsMax];
358
359 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
360 Table descriptor_to_class_root;
361
Brian Carlstroma663ea52011-08-19 23:33:41 -0700362 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
363 Set dex_caches;
364};
365
Brian Carlstromc74255f2011-09-11 22:47:39 -0700366void ClassLinker::InitFromImage(const std::vector<const DexFile*>& boot_class_path,
367 const std::vector<const DexFile*>& class_path) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700368 CHECK(!init_done_);
369
370 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
371 DCHECK(heap_bitmap != NULL);
372
Brian Carlstromc74255f2011-09-11 22:47:39 -0700373 InitFromImageCallbackState state;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700374 state.class_linker = this;
375 for (size_t i = 0; i < kClassRootsMax; i++) {
376 ClassRoot class_root = static_cast<ClassRoot>(i);
377 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
378 }
379
380 // reinit clases_ table
Brian Carlstromc74255f2011-09-11 22:47:39 -0700381 heap_bitmap->Walk(InitFromImageCallback, &state);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700382
383 // reinit class_roots_
384 Class* object_array_class = state.class_roots[kObjectArrayClass];
385 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
386 for (size_t i = 0; i < kClassRootsMax; i++) {
387 ClassRoot class_root = static_cast<ClassRoot>(i);
388 SetClassRoot(class_root, state.class_roots[class_root]);
389 }
390
Brian Carlstroma663ea52011-08-19 23:33:41 -0700391 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
393 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700394
395 // build a map from location to DexCache to match up with DexFile::GetLocation
396 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Brian Carlstromc74255f2011-09-11 22:47:39 -0700397 typedef InitFromImageCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700398 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
399 DexCache* dex_cache = *it;
400 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
401 location_to_dex_cache[location] = dex_cache;
402 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700403 CHECK_EQ(boot_class_path.size() + class_path.size(),
404 location_to_dex_cache.size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700405
406 // reinit boot_class_path with DexFile arguments and found DexCaches
407 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700408 const DexFile* dex_file = boot_class_path[i];
409 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700410 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700411 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700412 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700413 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700414
415 // register class_path with DexFile arguments and found DexCaches
416 for (size_t i = 0; i != class_path.size(); ++i) {
417 const DexFile* dex_file = class_path[i];
418 CHECK(dex_file != NULL);
419 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
420 CHECK(dex_cache != NULL) << dex_file->GetLocation();
421 RegisterDexFile(*dex_file, dex_cache);
422 }
423
Brian Carlstroma663ea52011-08-19 23:33:41 -0700424 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425 Field::SetClass(GetClassRoot(kJavaLangReflectField));
426 Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700427 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
428 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
429 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
430 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
431 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
432 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
433 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
434 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700435 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700436 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700437
438 FinishInit();
439}
440
Brian Carlstromc74255f2011-09-11 22:47:39 -0700441void ClassLinker::InitFromImageCallback(Object* obj, void *arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700442 DCHECK(obj != NULL);
443 DCHECK(arg != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700444 InitFromImageCallbackState* state = reinterpret_cast<InitFromImageCallbackState*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700445
Brian Carlstromc74255f2011-09-11 22:47:39 -0700446 if (obj->IsString()) {
447 state->class_linker->intern_table_->RegisterStrong(obj->AsString());
448 return;
449 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700450 if (!obj->IsClass()) {
451 return;
452 }
453 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700454 // TODO: restore ClassLoader's list of DexFiles after image load
455 // CHECK(klass->GetClassLoader() == NULL);
456 const ClassLoader* class_loader = klass->GetClassLoader();
457 if (class_loader != NULL) {
458 // TODO: replace this hack with something based on command line arguments
459 Thread::Current()->SetClassLoaderOverride(class_loader);
460 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700461
462 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700463 // restore class to ClassLinker::classes_ table
464 state->class_linker->InsertClass(descriptor, klass);
465
466 // note DexCache to match with DexFile later
467 DexCache* dex_cache = klass->GetDexCache();
468 if (dex_cache != NULL) {
469 state->dex_caches.insert(dex_cache);
470 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700471 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700472 }
473
474 // check if this is a root, if so, register it
Brian Carlstromc74255f2011-09-11 22:47:39 -0700475 typedef InitFromImageCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700476 It it = state->descriptor_to_class_root.find(descriptor);
477 if (it != state->descriptor_to_class_root.end()) {
478 ClassRoot class_root = it->second;
479 state->class_roots[class_root] = klass;
480 }
481}
482
483// Keep in sync with InitCallback. Anything we visit, we need to
484// reinit references to when reinitializing a ClassLinker from a
485// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700486void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
487 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700488
489 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700490 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700491 }
492
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700493 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700494 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700495 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700496 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700497 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700498 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700499 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700500
Elliott Hughes410c0c82011-09-01 17:58:25 -0700501 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700502}
503
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700504ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700505 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700506 Field::ResetClass();
507 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700508 BooleanArray::ResetArrayClass();
509 ByteArray::ResetArrayClass();
510 CharArray::ResetArrayClass();
511 DoubleArray::ResetArrayClass();
512 FloatArray::ResetArrayClass();
513 IntArray::ResetArrayClass();
514 LongArray::ResetArrayClass();
515 ShortArray::ResetArrayClass();
516 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700517 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700518}
519
520DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700521 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700522 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700523 AllocObjectArray<String>(dex_file.NumStringIds()),
524 AllocObjectArray<Class>(dex_file.NumTypeIds()),
525 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700526 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700527 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
528 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700529 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700530}
531
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700532CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
533 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700534}
535
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700536InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
537 DCHECK(interface->IsInterface());
538 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
539 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
540 interface_entry->SetInterface(interface);
541 return interface_entry;
542}
543
Brian Carlstrom4873d462011-08-21 15:23:39 -0700544Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
545 DCHECK_GE(class_size, sizeof(Class));
546 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700547 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
548 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700549 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550}
551
Brian Carlstrom4873d462011-08-21 15:23:39 -0700552Class* ClassLinker::AllocClass(size_t class_size) {
553 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700554}
555
Jesse Wilson35baaab2011-08-10 16:18:03 -0400556Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700557 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700558}
559
560Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700561 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700562}
563
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700564ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
565 return ObjectArray<StackTraceElement>::Alloc(
566 GetClassRoot(kJavaLangStackTraceElementArrayClass),
567 length);
568}
569
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700570Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700571 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700572 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700573 if (class_loader != NULL) {
574 Class* klass = FindClass(descriptor, NULL);
575 if (klass != NULL) {
576 return klass;
577 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700578 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700579 }
580
Carl Shapirob5573532011-07-12 18:22:59 -0700581 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700582 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700583 CHECK(!self->IsExceptionPending());
584 // Find the class in the loaded classes table.
585 Class* klass = LookupClass(descriptor, class_loader);
586 if (klass == NULL) {
587 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700588 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700589 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700590 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700591 const DexFile::ClassPath& class_path = ((class_loader != NULL)
592 ? ClassLoader::GetClassPath(class_loader)
593 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700594 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700595 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700596 std::string name(PrintableString(descriptor));
597 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
598 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700599 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700600 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700601 const DexFile& dex_file = *pair.first;
602 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700603 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700604 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700605 if (!init_done_) {
606 // finish up init of hand crafted class_roots_
607 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700608 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700609 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700610 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400611 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700612 klass = GetClassRoot(kJavaLangString);
613 } else if (descriptor == "Ljava/lang/reflect/Field;") {
614 klass = GetClassRoot(kJavaLangReflectField);
615 } else if (descriptor == "Ljava/lang/reflect/Method;") {
616 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700617 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700618 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700619 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700620 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700621 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700622 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700623 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700624 klass->SetDexCache(dex_cache);
625 LoadClass(dex_file, dex_class_def, klass, class_loader);
626 // Check for a pending exception during load
627 if (self->IsExceptionPending()) {
628 // TODO: free native allocations in klass
629 return NULL;
630 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700631 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700632 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700633 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700634 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700635 if (!success) {
636 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700637 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700638 // TODO: free native allocations in klass
639 klass = LookupClass(descriptor, class_loader);
640 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700641 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700642 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700643 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700644 CHECK(!klass->IsLoaded());
645 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700646 // Loading failed.
647 // TODO: CHECK(self->IsExceptionPending());
648 lock.NotifyAll();
649 return NULL;
650 }
651 CHECK(klass->IsLoaded());
652 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700653 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700654 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700655 // Linking failed.
656 // TODO: CHECK(self->IsExceptionPending());
657 lock.NotifyAll();
658 return NULL;
659 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700660 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700661 }
662 }
663 }
664 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700665 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700666 ObjectLock lock(klass);
667 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700668 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700669 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700670 return NULL;
671 }
672 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700673 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700674 lock.Wait();
675 }
676 }
677 if (klass->IsErroneous()) {
678 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
679 return NULL;
680 }
681 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700682 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700683 CHECK(!self->IsExceptionPending());
684 return klass;
685}
686
Brian Carlstrom4873d462011-08-21 15:23:39 -0700687// Precomputes size that will be needed for Class, matching LinkStaticFields
688size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
689 const DexFile::ClassDef& dex_class_def) {
690 const byte* class_data = dex_file.GetClassData(dex_class_def);
691 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
692 size_t num_static_fields = header.static_fields_size_;
693 size_t num_ref = 0;
694 size_t num_32 = 0;
695 size_t num_64 = 0;
696 if (num_static_fields != 0) {
697 uint32_t last_idx = 0;
698 for (size_t i = 0; i < num_static_fields; ++i) {
699 DexFile::Field dex_field;
700 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
701 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
702 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
703 char c = descriptor[0];
704 if (c == 'L' || c == '[') {
705 num_ref++;
706 } else if (c == 'J' || c == 'D') {
707 num_64++;
708 } else {
709 num_32++;
710 }
711 }
712 }
713
714 // start with generic class data
715 size_t size = sizeof(Class);
716 // follow with reference fields which must be contiguous at start
717 size += (num_ref * sizeof(uint32_t));
718 // if there are 64-bit fields to add, make sure they are aligned
719 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
720 if (num_32 != 0) {
721 // use an available 32-bit field for padding
722 num_32--;
723 }
724 size += sizeof(uint32_t); // either way, we are adding a word
725 DCHECK_EQ(size, RoundUp(size, 8));
726 }
727 // tack on any 64-bit fields now that alignment is assured
728 size += (num_64 * sizeof(uint64_t));
729 // tack on any remaining 32-bit fields
730 size += (num_32 * sizeof(uint32_t));
731 return size;
732}
733
Brian Carlstromf615a612011-07-23 12:50:34 -0700734void ClassLinker::LoadClass(const DexFile& dex_file,
735 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700736 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700737 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700738 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700739 CHECK(klass->GetDexCache() != NULL);
740 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700741 const byte* class_data = dex_file.GetClassData(dex_class_def);
742 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700743
Brian Carlstromf615a612011-07-23 12:50:34 -0700744 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700745 CHECK(descriptor != NULL);
746
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700747 klass->SetClass(GetClassRoot(kJavaLangClass));
748 if (klass->GetDescriptor() != NULL) {
749 DCHECK(klass->GetDescriptor()->Equals(descriptor));
750 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700751 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700752 }
753 uint32_t access_flags = dex_class_def.access_flags_;
754 // Make sure there aren't any "bonus" flags set, since we use them for runtime
755 // state.
756 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
757 klass->SetAccessFlags(access_flags);
758 klass->SetClassLoader(class_loader);
759 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
760 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700761
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700762 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700763
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700764 size_t num_static_fields = header.static_fields_size_;
765 size_t num_instance_fields = header.instance_fields_size_;
766 size_t num_direct_methods = header.direct_methods_size_;
767 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700768
Brian Carlstromc74255f2011-09-11 22:47:39 -0700769 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700770
771 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700772 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700773
774 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700775 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700776 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700777 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700778 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700779 DexFile::Field dex_field;
780 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400781 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700782 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700783 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700784 }
785 }
786
787 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700788 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700789 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700790 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700791 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700792 DexFile::Field dex_field;
793 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400794 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700795 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700796 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700797 }
798 }
799
800 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700801 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700802 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700803 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700804 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700805 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700806 DexFile::Method dex_method;
807 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700808 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700809 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700810 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700811 // TODO: register maps
812 }
813 }
814
815 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700816 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700817 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700818 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700819 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700820 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700821 DexFile::Method dex_method;
822 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700823 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700824 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700825 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700826 // TODO: register maps
827 }
828 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700829}
830
Brian Carlstromf615a612011-07-23 12:50:34 -0700831void ClassLinker::LoadInterfaces(const DexFile& dex_file,
832 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700833 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700834 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700835 if (list != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700836 klass->SetInterfaces(AllocObjectArray<Class>(list->Size()));
837 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
838 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700839 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700840 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700841 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700842 }
843 }
844}
845
Brian Carlstromf615a612011-07-23 12:50:34 -0700846void ClassLinker::LoadField(const DexFile& dex_file,
847 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700848 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700849 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700850 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700851 dst->SetDeclaringClass(klass);
852 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
853 dst->SetTypeIdx(field_id.type_idx_);
854 dst->SetAccessFlags(src.access_flags_);
855
856 // In order to access primitive types using GetTypeDuringLinking we need to
857 // ensure they are resolved into the dex cache
858 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
859 if (descriptor[1] == '\0') {
860 // only the descriptors of primitive types should be 1 character long
861 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
862 DCHECK(resolved->IsPrimitive());
863 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700864}
865
Brian Carlstromf615a612011-07-23 12:50:34 -0700866void ClassLinker::LoadMethod(const DexFile& dex_file,
867 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700868 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700869 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700870 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700871 dst->SetDeclaringClass(klass);
872 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700873 {
874 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700875 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700876 dst->SetSignature(intern_table_->InternStrong(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700877 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700878 dst->SetProtoIdx(method_id.proto_idx_);
879 dst->SetCodeItemOffset(src.code_off_);
880 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700881 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700882 dst->SetAccessFlags(src.access_flags_);
883 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700884
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700885 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
886 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
887 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
888 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
889 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
890 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700891
Brian Carlstrom934486c2011-07-12 23:42:50 -0700892 // TODO: check for finalize method
893
Brian Carlstromf615a612011-07-23 12:50:34 -0700894 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700895 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700896 dst->SetNumRegisters(code_item->registers_size_);
897 dst->SetNumIns(code_item->ins_size_);
898 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700899 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700900 uint16_t num_args = Method::NumArgRegisters(shorty);
901 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700902 ++num_args;
903 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700904 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700905 // TODO: native methods
906 }
907}
908
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700909void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700910 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
911}
912
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700913void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700914 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700915 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700916 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700917}
918
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700919void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700920 RegisterDexFile(dex_file, AllocDexCache(dex_file));
921}
922
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700923void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -0700924 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700925 CHECK(dex_cache != NULL) << dex_file.GetLocation();
926 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700927 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700928 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700929}
930
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700931const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700932 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700933 for (size_t i = 0; i != dex_caches_.size(); ++i) {
934 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700935 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700936 }
937 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700938 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700939 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700940}
941
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700942DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700943 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -0700944 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700945 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700946 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700947 }
948 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700949 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700950 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700951}
952
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700953Class* ClassLinker::CreatePrimitiveClass(const char* descriptor,
954 Class::PrimitiveType type) {
955 // TODO: deduce one argument from the other
Brian Carlstrom4873d462011-08-21 15:23:39 -0700956 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700957 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700958 klass->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700959 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700960 klass->SetPrimitiveType(type);
961 klass->SetStatus(Class::kStatusInitialized);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700962 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700963 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700964 return klass;
965}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700966
Brian Carlstrombe977852011-07-19 14:54:54 -0700967// Create an array class (i.e. the class object for the array, not the
968// array itself). "descriptor" looks like "[C" or "[[[[B" or
969// "[Ljava/lang/String;".
970//
971// If "descriptor" refers to an array of primitives, look up the
972// primitive type's internally-generated class object.
973//
974// "loader" is the class loader of the class that's referring to us. It's
975// used to ensure that we're looking for the element type in the right
976// context. It does NOT become the class loader for the array class; that
977// always comes from the base element class.
978//
979// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700980Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700981 const ClassLoader* class_loader) {
982 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700983
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700984 // Identify the underlying element class and the array dimension depth.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700985 Class* component_type = NULL;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700986 int array_rank;
987 if (descriptor[1] == '[') {
988 // array of arrays; keep descriptor and grab stuff from parent
989 Class* outer = FindClass(descriptor.substr(1), class_loader);
990 if (outer != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700991 // want the base class, not "outer", in our component_type
992 component_type = outer->GetComponentType();
993 array_rank = outer->GetArrayRank() + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700994 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700995 DCHECK(component_type == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700996 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700997 } else {
998 array_rank = 1;
999 if (descriptor[1] == 'L') {
1000 // array of objects; strip off "[" and look up descriptor.
1001 const StringPiece subDescriptor = descriptor.substr(1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001002 component_type = FindClass(subDescriptor, class_loader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001003 } else {
1004 // array of a primitive type
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001005 component_type = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001006 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001007 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001008
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001009 if (component_type == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001010 // failed
1011 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
1012 return NULL;
1013 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001014
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001015 // See if the component type is already loaded. Array classes are
1016 // always associated with the class loader of their underlying
1017 // element type -- an array of Strings goes with the loader for
1018 // java/lang/String -- so we need to look for it there. (The
1019 // caller should have checked for the existence of the class
1020 // before calling here, but they did so with *their* class loader,
1021 // not the component type's loader.)
1022 //
1023 // If we find it, the caller adds "loader" to the class' initiating
1024 // loader list, which should prevent us from going through this again.
1025 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001026 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001027 // are the same, because our caller (FindClass) just did the
1028 // lookup. (Even if we get this wrong we still have correct behavior,
1029 // because we effectively do this lookup again when we add the new
1030 // class to the hash table --- necessary because of possible races with
1031 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001032 if (class_loader != component_type->GetClassLoader()) {
1033 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001034 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001035 return new_class;
1036 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001037 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001038
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001039 // Fill out the fields in the Class.
1040 //
1041 // It is possible to execute some methods against arrays, because
1042 // all arrays are subclasses of java_lang_Object_, so we need to set
1043 // up a vtable. We can just point at the one in java_lang_Object_.
1044 //
1045 // Array classes are simple enough that we don't need to do a full
1046 // link step.
1047
1048 Class* new_class = NULL;
1049 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001050 // Classes that were hand created, ie not by FindSystemClass
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001051 if (descriptor == "[Ljava/lang/Object;") {
1052 new_class = GetClassRoot(kObjectArrayClass);
1053 } else if (descriptor == "[C") {
1054 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001055 } else if (descriptor == "[I") {
1056 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001057 }
1058 }
1059 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001060 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001061 if (new_class == NULL) {
1062 return NULL;
1063 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001064 new_class->SetArrayRank(array_rank);
1065 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001066 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001067 DCHECK_LE(1, new_class->GetArrayRank());
1068 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001069 if (new_class->GetDescriptor() != NULL) {
1070 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1071 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001072 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001073 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001074 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001075 new_class->SetSuperClass(java_lang_Object);
1076 new_class->SetVTable(java_lang_Object->GetVTable());
1077 new_class->SetPrimitiveType(Class::kPrimNot);
1078 new_class->SetClassLoader(component_type->GetClassLoader());
1079 new_class->SetStatus(Class::kStatusInitialized);
1080 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001081 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001082
1083
1084 // All arrays have java/lang/Cloneable and java/io/Serializable as
1085 // interfaces. We need to set that up here, so that stuff like
1086 // "instanceof" works right.
1087 //
1088 // Note: The GC could run during the call to FindSystemClass,
1089 // so we need to make sure the class object is GC-valid while we're in
1090 // there. Do this by clearing the interface list so the GC will just
1091 // think that the entries are null.
1092
1093
1094 // Use the single, global copies of "interfaces" and "iftable"
1095 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001096 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001097 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001098
1099 // Inherit access flags from the component type. Arrays can't be
1100 // used as a superclass or interface, so we want to add "final"
1101 // and remove "interface".
1102 //
1103 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001104 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001105 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001106 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1107 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001108
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001109 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001110 return new_class;
1111 }
1112 // Another thread must have loaded the class after we
1113 // started but before we finished. Abandon what we've
1114 // done.
1115 //
1116 // (Yes, this happens.)
1117
1118 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001119 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001120 DCHECK(other_class != NULL);
1121 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001122}
1123
1124Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001125 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001126 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001127 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001128 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001129 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001130 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001131 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001132 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001133 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001134 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001135 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001136 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001137 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001138 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001139 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001140 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001141 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001142 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001143 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001144 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001145 std::string printable_type(PrintableChar(type));
1146 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1147 "Not a primitive type: %s", printable_type.c_str());
1148 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001149}
1150
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001151bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1152 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001153 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001154 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001155 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001156}
1157
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001158Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001159 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001160 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001161 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001162 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001163 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001164 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001165 return klass;
1166 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001167 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001168 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001169}
1170
1171bool ClassLinker::InitializeClass(Class* klass) {
1172 CHECK(klass->GetStatus() == Class::kStatusResolved ||
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001173 klass->GetStatus() == Class::kStatusInitializing ||
1174 klass->GetStatus() == Class::kStatusError)
1175 << PrettyDescriptor(klass->GetDescriptor()) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001176
Carl Shapirob5573532011-07-12 18:22:59 -07001177 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001178
1179 {
1180 ObjectLock lock(klass);
1181
1182 if (klass->GetStatus() < Class::kStatusVerified) {
1183 if (klass->IsErroneous()) {
1184 LG << "re-initializing failed class"; // TODO: throw
1185 return false;
1186 }
1187
1188 CHECK(klass->GetStatus() == Class::kStatusResolved);
1189
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001190 klass->SetStatus(Class::kStatusVerifying);
jeffhaobdb76512011-09-07 11:43:16 -07001191 if (!DexVerifier::VerifyClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001192 LG << "Verification failed"; // TODO: ThrowVerifyError
1193 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001194 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001195 klass->SetStatus(Class::kStatusError);
1196 return false;
1197 }
1198
1199 klass->SetStatus(Class::kStatusVerified);
1200 }
1201
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001202 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001203 return true;
1204 }
1205
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001206 while (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001207 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001208 if (klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001209 // Yes. That's fine.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001210 return true;
1211 }
1212
1213 CHECK(!self->IsExceptionPending());
1214
1215 lock.Wait(); // TODO: check for interruption
1216
1217 // When we wake up, repeat the test for init-in-progress. If
1218 // there's an exception pending (only possible if
1219 // "interruptShouldThrow" was set), bail out.
1220 if (self->IsExceptionPending()) {
1221 CHECK(false);
1222 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1223 klass->SetStatus(Class::kStatusError);
1224 return false;
1225 }
1226 if (klass->GetStatus() == Class::kStatusInitializing) {
1227 continue;
1228 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001229 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001230 klass->GetStatus() == Class::kStatusError);
1231 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001232 // The caller wants an exception, but it was thrown in a
1233 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001234 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1235 return false;
1236 }
1237 return true; // otherwise, initialized
1238 }
1239
1240 // see if we failed previously
1241 if (klass->IsErroneous()) {
1242 // might be wise to unlock before throwing; depends on which class
1243 // it is that we have locked
1244
1245 // TODO: throwEarlierClassFailure(klass);
1246 return false;
1247 }
1248
1249 if (!ValidateSuperClassDescriptors(klass)) {
1250 klass->SetStatus(Class::kStatusError);
1251 return false;
1252 }
1253
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001254 DCHECK(klass->GetStatus() < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001255
Elliott Hughesdcc24742011-09-07 14:02:44 -07001256 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001257 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001258 }
1259
1260 if (!InitializeSuperClass(klass)) {
1261 return false;
1262 }
1263
1264 InitializeStaticFields(klass);
1265
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001266 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001267 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001268 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001269 }
1270
1271 {
1272 ObjectLock lock(klass);
1273
1274 if (self->IsExceptionPending()) {
1275 klass->SetStatus(Class::kStatusError);
1276 } else {
1277 klass->SetStatus(Class::kStatusInitialized);
1278 }
1279 lock.NotifyAll();
1280 }
1281
1282 return true;
1283}
1284
1285bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1286 if (klass->IsInterface()) {
1287 return true;
1288 }
1289 // begin with the methods local to the superclass
1290 if (klass->HasSuperClass() &&
1291 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1292 const Class* super = klass->GetSuperClass();
1293 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001294 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001295 if (method != super->GetVirtualMethod(i) &&
1296 !HasSameMethodDescriptorClasses(method, super, klass)) {
1297 LG << "Classes resolve differently in superclass";
1298 return false;
1299 }
1300 }
1301 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001302 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1303 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1304 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001305 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1306 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001307 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001308 if (!HasSameMethodDescriptorClasses(method, interface,
1309 method->GetClass())) {
1310 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1311 return false;
1312 }
1313 }
1314 }
1315 }
1316 return true;
1317}
1318
1319bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001320 const Class* klass1,
1321 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001322 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001323 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001324 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001325 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001326 const char* descriptor = it->GetDescriptor();
1327 if (descriptor == NULL) {
1328 break;
1329 }
1330 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1331 // Found a non-primitive type.
1332 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1333 return false;
1334 }
1335 }
1336 }
1337 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001338 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001339 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1340 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1341 return false;
1342 }
1343 }
1344 return true;
1345}
1346
1347// Returns true if classes referenced by the descriptor are the
1348// same classes in klass1 as they are in klass2.
1349bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001350 const Class* klass1,
1351 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001352 CHECK(descriptor != NULL);
1353 CHECK(klass1 != NULL);
1354 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001355 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001356 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001357 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001358 // TODO: found2 == NULL
1359 // TODO: lookup found1 in initiating loader list
1360 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001361 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001362 if (found1 == found2) {
1363 return true;
1364 } else {
1365 return false;
1366 }
1367 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001368 return true;
1369}
1370
1371bool ClassLinker::InitializeSuperClass(Class* klass) {
1372 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001373 if (!klass->IsInterface() && klass->HasSuperClass()) {
1374 Class* super_class = klass->GetSuperClass();
1375 if (super_class->GetStatus() != Class::kStatusInitialized) {
1376 CHECK(!super_class->IsInterface());
1377 klass->MonitorExit();
1378 bool super_initialized = InitializeClass(super_class);
1379 klass->MonitorEnter();
1380 // TODO: check for a pending exception
1381 if (!super_initialized) {
1382 klass->SetStatus(Class::kStatusError);
1383 klass->NotifyAll();
1384 return false;
1385 }
1386 }
1387 }
1388 return true;
1389}
1390
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001391bool ClassLinker::EnsureInitialized(Class* c) {
1392 CHECK(c != NULL);
1393 if (c->IsInitialized()) {
1394 return true;
1395 }
1396
1397 c->MonitorExit();
1398 InitializeClass(c);
1399 c->MonitorEnter();
1400 return !Thread::Current()->IsExceptionPending();
1401}
1402
Brian Carlstromb9edb842011-08-28 16:31:06 -07001403StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1404 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001405 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1406 Class* klass = class_linker->ResolveType(type_idx, referrer);
1407 if (klass == NULL) {
1408 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1409 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001410 // If we are the <clinit> of this class, just return our storage.
1411 //
1412 // Do not set the DexCache InitializedStaticStorage, since that
1413 // implies <clinit> has finished running.
1414 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1415 return klass;
1416 }
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001417 if (!class_linker->EnsureInitialized(klass)) {
1418 CHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001419 UNIMPLEMENTED(FATAL) << "throw exception due to class initialization problem";
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001420 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001421 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001422 return klass;
1423}
1424
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001425void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1426 Class* c, std::map<int, Field*>& field_map) {
1427 const ClassLoader* cl = c->GetClassLoader();
1428 const byte* class_data = dex_file.GetClassData(dex_class_def);
1429 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1430 uint32_t last_idx = 0;
1431 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1432 DexFile::Field dex_field;
1433 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1434 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1435 }
1436}
1437
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001438void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001439 size_t num_static_fields = klass->NumStaticFields();
1440 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001441 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001442 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001443 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001444 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001445 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001446 return;
1447 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001448 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001449 const DexFile& dex_file = FindDexFile(dex_cache);
1450 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001451 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001452
1453 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1454 std::map<int, Field*> field_map;
1455 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1456
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001457 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001458 if (addr == NULL) {
1459 // All this class' static fields have default values.
1460 return;
1461 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001462 size_t array_size = DecodeUnsignedLeb128(&addr);
1463 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001464 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001465 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001466 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001467 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001468 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001469 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001470 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001471 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001472 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001473 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001474 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001475 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001476 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001477 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001478 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001479 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001480 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001481 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001482 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001483 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001484 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001485 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001486 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001487 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001488 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001489 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001490 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001491 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001492 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001493 break;
1494 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001495 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001496 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001497 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001498 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001499 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001500 break;
1501 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001502 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001503 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001504 }
1505}
1506
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001507bool ClassLinker::LinkClass(Class* klass) {
1508 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001509 if (!LinkSuperClass(klass)) {
1510 return false;
1511 }
1512 if (!LinkMethods(klass)) {
1513 return false;
1514 }
1515 if (!LinkInstanceFields(klass)) {
1516 return false;
1517 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001518 if (!LinkStaticFields(klass)) {
1519 return false;
1520 }
1521 CreateReferenceInstanceOffsets(klass);
1522 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001523 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1524 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001525 return true;
1526}
1527
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001528bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001529 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1530 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1531 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001532 if (super_class == NULL) {
1533 LG << "Failed to resolve superclass";
1534 return false;
1535 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001536 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001537 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001538 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1539 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1540 Class *interface = ResolveType(dex_file, idx, klass);
1541 klass->SetInterface(i, interface);
1542 if (interface == NULL) {
1543 LG << "Failed to resolve interface";
1544 return false;
1545 }
1546 // Verify
1547 if (!klass->CanAccess(interface)) {
1548 LG << "Inaccessible interface";
1549 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001550 }
1551 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001552 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001553 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001554 return true;
1555}
1556
1557bool ClassLinker::LinkSuperClass(Class* klass) {
1558 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001559 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001560 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001561 if (super != NULL) {
1562 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1563 return false;
1564 }
1565 // TODO: clear finalize attribute
1566 return true;
1567 }
1568 if (super == NULL) {
1569 LG << "No superclass defined"; // TODO: LinkageError
1570 return false;
1571 }
1572 // Verify
1573 if (super->IsFinal()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001574 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001575 return false;
1576 }
1577 if (super->IsInterface()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001578 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001579 return false;
1580 }
1581 if (!klass->CanAccess(super)) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001582 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001583 return false;
1584 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001585#ifndef NDEBUG
1586 // Ensure super classes are fully resolved prior to resolving fields..
1587 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001588 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001589 super = super->GetSuperClass();
1590 }
1591#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001592 return true;
1593}
1594
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001595// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001596bool ClassLinker::LinkMethods(Class* klass) {
1597 if (klass->IsInterface()) {
1598 // No vtable.
1599 size_t count = klass->NumVirtualMethods();
1600 if (!IsUint(16, count)) {
1601 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1602 return false;
1603 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001604 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001605 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001606 }
jeffhaobdb76512011-09-07 11:43:16 -07001607 // Link interface method tables
1608 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001609 } else {
1610 // Link virtual method tables
1611 LinkVirtualMethods(klass);
1612
1613 // Link interface method tables
1614 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001615 }
1616 return true;
1617}
1618
1619bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001620 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001621 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1622 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001623 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001624 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001625 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001626 // See if any of our virtual methods override the superclass.
1627 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001628 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001629 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001630 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001631 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001632 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001633 // Verify
1634 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001635 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001636 return false;
1637 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001638 vtable->Set(j, local_method);
1639 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640 break;
1641 }
1642 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001643 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001644 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001645 vtable->Set(actual_count, local_method);
1646 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001647 actual_count += 1;
1648 }
1649 }
1650 if (!IsUint(16, actual_count)) {
1651 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1652 return false;
1653 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001654 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001655 CHECK_LE(actual_count, max_count);
1656 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001657 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001658 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001659 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001660 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001661 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001662 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001663 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001664 LG << "Too many methods"; // TODO: VirtualMachineError
1665 return false;
1666 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001667 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001668 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001669 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1670 vtable->Set(i, virtual_method);
1671 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001672 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001673 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001674 }
1675 return true;
1676}
1677
1678bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001679 int miranda_count = 0;
1680 int miranda_alloc = 0;
1681 size_t super_ifcount;
1682 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001683 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001684 } else {
1685 super_ifcount = 0;
1686 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001687 size_t ifcount = super_ifcount;
1688 ifcount += klass->NumInterfaces();
1689 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001690 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001691 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001692 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001693 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001694 // DCHECK(klass->GetIfTableCount() == 0);
1695 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001696 return true;
1697 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001698 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001699 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001700 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1701 for (size_t i = 0; i < super_ifcount; i++) {
1702 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1703 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001704 }
1705 // Flatten the interface inheritance hierarchy.
1706 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001707 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001708 Class* interface = klass->GetInterface(i);
1709 DCHECK(interface != NULL);
1710 if (!interface->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001711 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1712 return false;
1713 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001714 iftable->Set(idx++, AllocInterfaceEntry(interface));
1715 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1716 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001717 }
1718 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001719 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001720 CHECK_EQ(idx, ifcount);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001721 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001722 return true;
1723 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001724 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001725 for (size_t i = 0; i < ifcount; ++i) {
1726 InterfaceEntry* interface_entry = iftable->Get(i);
1727 Class* interface = interface_entry->GetInterface();
1728 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1729 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001730 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001731 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1732 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001733 int32_t k;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001734 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1735 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001736 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1737 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001738 LG << "Implementation not public";
1739 return false;
1740 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001741 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001742 break;
1743 }
1744 }
1745 if (k < 0) {
1746 if (miranda_count == miranda_alloc) {
1747 miranda_alloc += 8;
1748 if (miranda_list.empty()) {
1749 miranda_list.resize(miranda_alloc);
1750 } else {
1751 miranda_list.resize(miranda_alloc);
1752 }
1753 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001754 Method* miranda_method = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001755 int mir;
1756 for (mir = 0; mir < miranda_count; mir++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001757 miranda_method = miranda_list[mir];
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001758 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001759 break;
1760 }
1761 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001762 // point the interface table at a phantom slot
1763 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001764 if (mir == miranda_count) {
1765 miranda_list[miranda_count++] = interface_method;
1766 }
1767 }
1768 }
1769 }
1770 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001771 int old_method_count = klass->NumVirtualMethods();
1772 int new_method_count = old_method_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001773 klass->SetVirtualMethods(
1774 klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001775
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001776 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1777 CHECK(vtable != NULL);
1778 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001779 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001780 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001781 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001782 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001783 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001784 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001785 meth->SetDeclaringClass(klass);
1786 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1787 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001788 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001789 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001790 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001791 // TODO: do not assign to the vtable field until it is fully constructed.
1792 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001793 }
1794 return true;
1795}
1796
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001797bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001798 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001799 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001800}
1801
1802bool ClassLinker::LinkStaticFields(Class* klass) {
1803 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001804 size_t allocated_class_size = klass->GetClassSize();
1805 bool success = LinkFields(klass, false);
1806 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001807 return success;
1808}
1809
Brian Carlstromdbc05252011-09-09 01:59:59 -07001810struct LinkFieldsComparator {
1811 bool operator()(const Field* field1, const Field* field2){
1812
1813 // First come reference fields, then 64-bit, and finally 32-bit
1814 const Class* type1 = field1->GetTypeDuringLinking();
1815 const Class* type2 = field2->GetTypeDuringLinking();
1816 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
1817 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
1818 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
1819 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
1820 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
1821 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
1822 if (order1 != order2) {
1823 return order1 < order2;
1824 }
1825
1826 // same basic group? then sort by string.
1827 std::string name1 = field1->GetName()->ToModifiedUtf8();
1828 std::string name2 = field2->GetName()->ToModifiedUtf8();
1829 return name1 < name2;
1830 }
1831};
1832
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001833bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001834 size_t num_fields =
1835 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1836
1837 ObjectArray<Field>* fields =
1838 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001839
1840 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07001841 size_t size;
1842 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001843 if (instance) {
1844 Class* super_class = klass->GetSuperClass();
1845 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001846 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001847 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001848 }
1849 size = field_offset.Uint32Value();
1850 } else {
1851 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07001852 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001853 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001854
Brian Carlstromdbc05252011-09-09 01:59:59 -07001855 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001856
Brian Carlstromdbc05252011-09-09 01:59:59 -07001857 // we want a relatively stable order so that adding new fields
1858 // minimizes distruption of C++ version such as Class and Method.
1859 std::deque<Field*> grouped_and_sorted_fields;
1860 for (size_t i = 0; i < num_fields; i++) {
1861 grouped_and_sorted_fields.push_back(fields->Get(i));
1862 }
1863 std::sort(grouped_and_sorted_fields.begin(),
1864 grouped_and_sorted_fields.end(),
1865 LinkFieldsComparator());
1866
1867 // References should be at the front.
1868 size_t current_field = 0;
1869 size_t num_reference_fields = 0;
1870 for (; current_field < num_fields; current_field++) {
1871 Field* field = grouped_and_sorted_fields.front();
1872 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001873 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07001874 bool isPrimitive = type != NULL && type->IsPrimitive();
1875 if (isPrimitive) {
1876 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001877 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001878 grouped_and_sorted_fields.pop_front();
1879 num_reference_fields++;
1880 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001881 field->SetOffset(field_offset);
1882 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001883 }
1884
1885 // Now we want to pack all of the double-wide fields together. If
1886 // we're not aligned, though, we want to shuffle one 32-bit field
1887 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001888 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
1889 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
1890 Field* field = grouped_and_sorted_fields[i];
1891 const Class* type = field->GetTypeDuringLinking();
1892 CHECK(type != NULL); // should only be working on primitive types
1893 DCHECK(type->IsPrimitive());
1894 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
1895 continue;
1896 }
1897 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001898 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001899 // drop the consumed field
1900 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
1901 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001902 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001903 // whether we found a 32-bit field for padding or not, we advance
1904 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001905 }
1906
1907 // Alignment is good, shuffle any double-wide fields forward, and
1908 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07001909 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
1910 while (!grouped_and_sorted_fields.empty()) {
1911 Field* field = grouped_and_sorted_fields.front();
1912 grouped_and_sorted_fields.pop_front();
1913 const Class* type = field->GetTypeDuringLinking();
1914 CHECK(type != NULL); // should only be working on primitive types
1915 DCHECK(type->IsPrimitive());
1916 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001917 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001918 field_offset = MemberOffset(field_offset.Uint32Value() +
1919 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
1920 ? sizeof(uint64_t)
1921 : sizeof(uint32_t)));
1922 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001923 }
1924
1925#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001926 // Make sure that all reference fields appear before
1927 // non-reference fields, and all double-wide fields are aligned.
1928 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07001929 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001930 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001931 if (false) { // enable to debug field layout
1932 LOG(INFO) << "LinkFields:"
1933 << " class=" << klass->GetDescriptor()->ToModifiedUtf8()
1934 << " field=" << field->GetName()->ToModifiedUtf8()
1935 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
1936 }
1937 const Class* type = field->GetTypeDuringLinking();
1938 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001939 if (!seen_non_ref) {
1940 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001941 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001942 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001943 } else {
1944 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001945 }
1946 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001947 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001948 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001949 }
1950#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001951 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001952 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07001953 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001954 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07001955 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001956 klass->SetObjectSize(size);
1957 }
1958 } else {
1959 klass->SetNumReferenceStaticFields(num_reference_fields);
1960 klass->SetClassSize(size);
1961 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001962 return true;
1963}
1964
1965// Set the bitmap of reference offsets, refOffsets, from the ifields
1966// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001967void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001968 uint32_t reference_offsets = 0;
1969 Class* super_class = klass->GetSuperClass();
1970 if (super_class != NULL) {
1971 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001972 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001973 if (reference_offsets == CLASS_WALK_SUPER) {
1974 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001975 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001976 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001977 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001978 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001979}
1980
1981void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001982 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001983}
1984
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001985void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
1986 uint32_t reference_offsets) {
1987 size_t num_reference_fields =
1988 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
1989 : klass->NumReferenceStaticFieldsDuringLinking();
1990 const ObjectArray<Field>* fields =
1991 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001992 // All of the fields that contain object references are guaranteed
1993 // to be at the beginning of the fields list.
1994 for (size_t i = 0; i < num_reference_fields; ++i) {
1995 // Note that byte_offset is the offset from the beginning of
1996 // object, not the offset into instance data
1997 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001998 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001999 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2000 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2001 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002002 CHECK_NE(new_bit, 0U);
2003 reference_offsets |= new_bit;
2004 } else {
2005 reference_offsets = CLASS_WALK_SUPER;
2006 break;
2007 }
2008 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002009 // Update fields in klass
2010 if (instance) {
2011 klass->SetReferenceInstanceOffsets(reference_offsets);
2012 } else {
2013 klass->SetReferenceStaticOffsets(reference_offsets);
2014 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002015}
2016
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002017String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002018 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002019 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 if (resolved != NULL) {
2021 return resolved;
2022 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002023 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2024 int32_t utf16_length = dex_file.GetStringLength(string_id);
2025 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002026 // TODO: remote the const_cast below
2027 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002028 dex_cache->SetResolvedString(string_idx, string);
2029 return string;
2030}
2031
2032Class* ClassLinker::ResolveType(const DexFile& dex_file,
2033 uint32_t type_idx,
2034 DexCache* dex_cache,
2035 const ClassLoader* class_loader) {
2036 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002037 if (resolved == NULL) {
2038 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2039 if (descriptor[1] == '\0') {
2040 // only the descriptors of primitive types should be 1 character long
2041 resolved = FindPrimitiveClass(descriptor[0]);
2042 } else {
2043 resolved = FindClass(descriptor, class_loader);
2044 }
2045 if (resolved != NULL) {
2046 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2047 if (dex_cache != check->GetDexCache()) {
2048 if (check->GetClassLoader() != NULL) {
2049 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
2050 resolved = NULL;
2051 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002052 }
2053 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002054 if (resolved != NULL) {
2055 dex_cache->SetResolvedType(type_idx, resolved);
2056 } else {
2057 DCHECK(Thread::Current()->IsExceptionPending());
2058 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002059 }
2060 return resolved;
2061}
2062
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002063Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2064 uint32_t method_idx,
2065 DexCache* dex_cache,
2066 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002067 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002068 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2069 if (resolved != NULL) {
2070 return resolved;
2071 }
2072 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2073 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2074 if (klass == NULL) {
2075 return NULL;
2076 }
2077
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002078 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002079 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002080 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002081 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002082 } else if (klass->IsInterface()) {
2083 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002084 } else {
2085 resolved = klass->FindVirtualMethod(name, signature);
2086 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002087 if (resolved != NULL) {
2088 dex_cache->SetResolvedMethod(method_idx, resolved);
2089 } else {
2090 // DCHECK(Thread::Current()->IsExceptionPending());
2091 }
2092 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002093}
2094
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002095Field* ClassLinker::ResolveField(const DexFile& dex_file,
2096 uint32_t field_idx,
2097 DexCache* dex_cache,
2098 const ClassLoader* class_loader,
2099 bool is_static) {
2100 Field* resolved = dex_cache->GetResolvedField(field_idx);
2101 if (resolved != NULL) {
2102 return resolved;
2103 }
2104 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2105 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2106 if (klass == NULL) {
2107 return NULL;
2108 }
2109
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002110 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002111 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2112 // TODO: LinkageError?
2113 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002114 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002115 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002116 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002117 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002118 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002119 if (resolved != NULL) {
2120 dex_cache->SetResolvedfield(field_idx, resolved);
2121 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002122 // TODO: DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002123 }
2124 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002125}
2126
Elliott Hughese27955c2011-08-26 15:21:24 -07002127size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002128 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002129 return classes_.size();
2130}
2131
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002132} // namespace art