blob: 9a6470b5d2414c406700570c395ef1244fb375bf [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
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07005#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07006#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07007#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07008
Elliott Hughes90a33692011-08-30 13:27:07 -07009#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070011#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070012#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070013#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "dex_verifier.h"
15#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070016#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "logging.h"
18#include "monitor.h"
19#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include "runtime.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070021#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070022#include "thread.h"
23#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070024
25namespace art {
26
Brian Carlstroma663ea52011-08-19 23:33:41 -070027const char* ClassLinker::class_roots_descriptors_[kClassRootsMax] = {
28 "Ljava/lang/Class;",
29 "Ljava/lang/Object;",
30 "[Ljava/lang/Object;",
31 "Ljava/lang/String;",
32 "Ljava/lang/reflect/Field;",
33 "Ljava/lang/reflect/Method;",
34 "Ljava/lang/ClassLoader;",
35 "Ldalvik/system/BaseDexClassLoader;",
36 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070037 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070038 "Z",
39 "B",
40 "C",
41 "D",
42 "F",
43 "I",
44 "J",
45 "S",
46 "V",
47 "[Z",
48 "[B",
49 "[C",
50 "[D",
51 "[F",
52 "[I",
53 "[J",
54 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070055 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070056};
57
Elliott Hughescf4c6c42011-09-01 15:16:42 -070058ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path,
59 InternTable* intern_table, Space* space) {
60 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstroma663ea52011-08-19 23:33:41 -070061 if (space == NULL) {
62 class_linker->Init(boot_class_path);
63 } else {
64 class_linker->Init(boot_class_path, space);
65 }
Carl Shapiro61e019d2011-07-14 16:53:09 -070066 // TODO: check for failure during initialization
67 return class_linker.release();
68}
69
Elliott Hughescf4c6c42011-09-01 15:16:42 -070070ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070071 : classes_lock_(Mutex::Create("ClassLinker::Lock")),
72 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070073 array_interfaces_(NULL),
74 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -070075 init_done_(false),
76 intern_table_(intern_table) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070077}
Brian Carlstroma663ea52011-08-19 23:33:41 -070078
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -070079void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070080 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070081
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070082 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070083 Class* java_lang_Class = down_cast<Class*>(
84 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070085 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070086 java_lang_Class->SetClass(java_lang_Class);
87 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070088 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -070089
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070090 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -070091 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070092 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -070093 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070094 java_lang_Class->SetSuperClass(java_lang_Object);
95 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -070096
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070097 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -070098 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070099 object_array_class->SetArrayRank(1);
100 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700101
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700102
103 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700104 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700105 char_array_class->SetArrayRank(1);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700106 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700107
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700108 // Setup String
109 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
110 String::SetClass(java_lang_String);
111 java_lang_String->SetObjectSize(sizeof(String));
112 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400113
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700114 // Backfill Class descriptors missing until this point
115 // TODO: intern these strings
116 java_lang_Class->SetDescriptor(
117 String::AllocFromModifiedUtf8("Ljava/lang/Class;"));
118 java_lang_Object->SetDescriptor(
119 String::AllocFromModifiedUtf8("Ljava/lang/Object;"));
120 object_array_class->SetDescriptor(
121 String::AllocFromModifiedUtf8("[Ljava/lang/Object;"));
122 java_lang_String->SetDescriptor(
123 String::AllocFromModifiedUtf8("Ljava/lang/String;"));
124 char_array_class->SetDescriptor(String::AllocFromModifiedUtf8("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700125
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700126 // Create storage for root classes, save away our work so far (requires
127 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700128 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700129 SetClassRoot(kJavaLangClass, java_lang_Class);
130 SetClassRoot(kJavaLangObject, java_lang_Object);
131 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700132 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700133 SetClassRoot(kJavaLangString, java_lang_String);
134
135 // Setup the primitive type classes.
136 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
137 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
138 SetClassRoot(kPrimitiveChar, CreatePrimitiveClass("C", Class::kPrimChar));
139 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
140 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
141 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
142 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
143 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
144 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
145
146 // Backfill component type of char[]
147 char_array_class->SetComponentType(GetClassRoot(kPrimitiveChar));
148
149 // Create array interface entries to populate once we can load system classes
150 array_interfaces_ = AllocObjectArray<Class>(2);
151 array_iftable_ = new InterfaceEntry[2];
152
153 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
154 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
155 int_array_class->SetArrayRank(1);
156 int_array_class->SetDescriptor(String::AllocFromModifiedUtf8("[I"));
157 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
158 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700159 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700160
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700161 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700162
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700163 // setup boot_class_path_ now that we can use AllocObjectArray to
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700164 // create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700165 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700166 const DexFile* dex_file = boot_class_path[i];
167 CHECK(dex_file != NULL);
168 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700169 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700170
171 // Field and Method are necessary so that FindClass can link members
172 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
173 CHECK(java_lang_reflect_Field != NULL);
174 java_lang_reflect_Field->SetDescriptor(String::AllocFromModifiedUtf8("Ljava/lang/reflect/Field;"));
175 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
176 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
177 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
178 Field::SetClass(java_lang_reflect_Field);
179
180 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
181 java_lang_reflect_Method->SetDescriptor(String::AllocFromModifiedUtf8("Ljava/lang/reflect/Method;"));
182 CHECK(java_lang_reflect_Method != NULL);
183 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
184 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
185 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
186 Method::SetClass(java_lang_reflect_Method);
187
188 // now we can use FindSystemClass
189
190 // Object and String just need more minimal setup, since they do not have
191 // extra C++ fields.
192 java_lang_Object->SetStatus(Class::kStatusNotReady);
193 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
194 CHECK_EQ(java_lang_Object, Object_class);
195 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
196 java_lang_String->SetStatus(Class::kStatusNotReady);
197 Class* String_class = FindSystemClass("Ljava/lang/String;");
198 CHECK_EQ(java_lang_String, String_class);
199 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
200
201 // Setup the primitive array type classes - can't be done until Object has
202 // a vtable
203 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
204 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
205
206 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
207 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
208
209 Class* found_char_array_class = FindSystemClass("[C");
210 CHECK_EQ(char_array_class, found_char_array_class);
211
212 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
213 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
214
215 Class* found_int_array_class = FindSystemClass("[I");
216 CHECK_EQ(int_array_class, found_int_array_class);
217
218 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
219 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
220
221 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
222 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
223
224 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
225 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
226
227 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
228 CHECK_EQ(object_array_class, found_object_array_class);
229
230 // Setup the single, global copies of "interfaces" and "iftable"
231 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
232 CHECK(java_lang_Cloneable != NULL);
233 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
234 CHECK(java_io_Serializable != NULL);
235 CHECK(array_interfaces_ != NULL);
236 array_interfaces_->Set(0, java_lang_Cloneable);
237 array_interfaces_->Set(1, java_io_Serializable);
238 // We assume that Cloneable/Serializable don't have superinterfaces --
239 // normally we'd have to crawl up and explicitly list all of the
240 // supers as well. These interfaces don't have any methods, so we
241 // don't have to worry about the ifviPool either.
242 array_iftable_[0].SetInterface(array_interfaces_->Get(0));
243 array_iftable_[1].SetInterface(array_interfaces_->Get(1));
244
245 // Sanity check Object[]'s interfaces
246 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
247 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700248
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700249 // run Class, Field, and Method through FindSystemClass.
250 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700251 // we also override their object_size_ values to accommodate the extra C++ fields.
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 // No sanity check on size as Class is variably sized
255
256 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700257 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700258 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700259 CHECK_LT(java_lang_reflect_Field->GetObjectSize(), sizeof(Field));
260 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
261
262 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700263 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700264 CHECK_EQ(java_lang_reflect_Method, Method_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700265 CHECK_LT(java_lang_reflect_Method->GetObjectSize(), sizeof(Method));
266 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom1f870082011-08-23 16:02:11 -0700267
268 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
269 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 java_lang_ref_FinalizerReference->SetAccessFlags(
271 java_lang_ref_FinalizerReference->GetAccessFlags() |
272 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700273 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700274 java_lang_ref_PhantomReference->SetAccessFlags(
275 java_lang_ref_PhantomReference->GetAccessFlags() |
276 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700277 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700278 java_lang_ref_SoftReference->SetAccessFlags(
279 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700280 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700281 java_lang_ref_WeakReference->SetAccessFlags(
282 java_lang_ref_WeakReference->GetAccessFlags() |
283 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700284
285 // Let the heap know some key offsets into java.lang.ref instances
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700286 // NB we hard code the field indexes here rather than using FindInstanceField
287 // as the types of the field can't be resolved prior to the runtime being
288 // fully initialized
Brian Carlstrom1f870082011-08-23 16:02:11 -0700289 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700290
291 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
292 CHECK(pendingNext->GetName()->Equals("pendingNext"));
293 CHECK(ResolveType(pendingNext->GetTypeIdx(), pendingNext) ==
294 java_lang_ref_Reference);
295
296 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
297 CHECK(queue->GetName()->Equals("queue"));
298 CHECK(ResolveType(queue->GetTypeIdx(), queue) ==
299 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
300
301 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
302 CHECK(queueNext->GetName()->Equals("queueNext"));
303 CHECK(ResolveType(queueNext->GetTypeIdx(), queueNext) ==
304 java_lang_ref_Reference);
305
306 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
307 CHECK(referent->GetName()->Equals("referent"));
308 CHECK(ResolveType(referent->GetTypeIdx(), referent) ==
309 java_lang_Object);
310
311 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
312 CHECK(zombie->GetName()->Equals("zombie"));
313 CHECK(ResolveType(zombie->GetTypeIdx(), zombie) ==
314 java_lang_Object);
315
Brian Carlstrom1f870082011-08-23 16:02:11 -0700316 Heap::SetReferenceOffsets(referent->GetOffset(),
317 queue->GetOffset(),
318 queueNext->GetOffset(),
319 pendingNext->GetOffset(),
320 zombie->GetOffset());
321
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322 // Setup the ClassLoaders, adjusting the object_size_ as necessary
323 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
324 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
325 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
326 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
327
328 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
329 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
330 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
331
332 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
333 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
334 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
335 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
336
337 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700338 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
339 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700340 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700341
Brian Carlstroma663ea52011-08-19 23:33:41 -0700342 FinishInit();
343}
344
345void ClassLinker::FinishInit() {
346 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700347 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700348 ClassRoot class_root = static_cast<ClassRoot>(i);
349 Class* klass = GetClassRoot(class_root);
350 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700352 // note SetClassRoot does additional validation.
353 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700354 }
355
356 // disable the slow paths in FindClass and CreatePrimitiveClass now
357 // that Object, Class, and Object[] are setup
358 init_done_ = true;
359}
360
Brian Carlstroma663ea52011-08-19 23:33:41 -0700361struct ClassLinker::InitCallbackState {
362 ClassLinker* class_linker;
363
364 Class* class_roots[kClassRootsMax];
365
366 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
367 Table descriptor_to_class_root;
368
369 struct DexCacheHash {
370 size_t operator()(art::DexCache* const& obj) const {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371 return reinterpret_cast<size_t>(&obj);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700372 }
373 };
374 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
375 Set dex_caches;
376};
377
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700378void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path, Space* space) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700379 CHECK(!init_done_);
380
381 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
382 DCHECK(heap_bitmap != NULL);
383
384 InitCallbackState state;
385 state.class_linker = this;
386 for (size_t i = 0; i < kClassRootsMax; i++) {
387 ClassRoot class_root = static_cast<ClassRoot>(i);
388 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
389 }
390
391 // reinit clases_ table
392 heap_bitmap->Walk(InitCallback, &state);
393
394 // reinit class_roots_
395 Class* object_array_class = state.class_roots[kObjectArrayClass];
396 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
397 for (size_t i = 0; i < kClassRootsMax; i++) {
398 ClassRoot class_root = static_cast<ClassRoot>(i);
399 SetClassRoot(class_root, state.class_roots[class_root]);
400 }
401
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700402 // reinit intern table
Brian Carlstroma663ea52011-08-19 23:33:41 -0700403 ObjectArray<Object>* interned_array = space->GetImageHeader().GetInternedArray();
404 for (int32_t i = 0; i < interned_array->GetLength(); i++) {
405 String* string = interned_array->Get(i)->AsString();
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700406 intern_table_->RegisterStrong(string);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700407 }
408
409 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
411 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700412
413 // build a map from location to DexCache to match up with DexFile::GetLocation
414 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700415 typedef InitCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700416 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
417 DexCache* dex_cache = *it;
418 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
419 location_to_dex_cache[location] = dex_cache;
420 }
421
422 // reinit boot_class_path with DexFile arguments and found DexCaches
423 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700424 const DexFile* dex_file = boot_class_path[i];
425 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700426 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700427 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700428 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700429 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700430 Field::SetClass(GetClassRoot(kJavaLangReflectField));
431 Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700432 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
433 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
434 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
435 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
436 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
437 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
438 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
439 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700440 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700441 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700442
443 FinishInit();
444}
445
Brian Carlstrom4873d462011-08-21 15:23:39 -0700446void ClassLinker::InitCallback(Object* obj, void *arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700447 DCHECK(obj != NULL);
448 DCHECK(arg != NULL);
449 InitCallbackState* state = reinterpret_cast<InitCallbackState*>(arg);
450
451 if (!obj->IsClass()) {
452 return;
453 }
454 Class* klass = obj->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455 CHECK(klass->GetClassLoader() == NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700456
457 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
458
459 // restore class to ClassLinker::classes_ table
460 state->class_linker->InsertClass(descriptor, klass);
461
462 // note DexCache to match with DexFile later
463 DexCache* dex_cache = klass->GetDexCache();
464 if (dex_cache != NULL) {
465 state->dex_caches.insert(dex_cache);
466 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700467 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700468 }
469
470 // check if this is a root, if so, register it
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471 typedef InitCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700472 It it = state->descriptor_to_class_root.find(descriptor);
473 if (it != state->descriptor_to_class_root.end()) {
474 ClassRoot class_root = it->second;
475 state->class_roots[class_root] = klass;
476 }
477}
478
479// Keep in sync with InitCallback. Anything we visit, we need to
480// reinit references to when reinitializing a ClassLinker from a
481// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700482void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
483 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700484
485 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700486 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700487 }
488
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700489 {
490 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700491 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700492 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700493 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700494 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700495 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700496
Elliott Hughes410c0c82011-09-01 17:58:25 -0700497 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700498}
499
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700500ClassLinker::~ClassLinker() {
501 delete classes_lock_;
502 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700503 Field::ResetClass();
504 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700505 BooleanArray::ResetArrayClass();
506 ByteArray::ResetArrayClass();
507 CharArray::ResetArrayClass();
508 DoubleArray::ResetArrayClass();
509 FloatArray::ResetArrayClass();
510 IntArray::ResetArrayClass();
511 LongArray::ResetArrayClass();
512 ShortArray::ResetArrayClass();
513 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700514 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700515}
516
517DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700518 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700519 dex_cache->Init(String::AllocFromModifiedUtf8(dex_file.GetLocation().c_str()),
520 AllocObjectArray<String>(dex_file.NumStringIds()),
521 AllocObjectArray<Class>(dex_file.NumTypeIds()),
522 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700523 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700524 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
525 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700526 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700527}
528
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700529CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
530 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700531}
532
Brian Carlstrom4873d462011-08-21 15:23:39 -0700533Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
534 DCHECK_GE(class_size, sizeof(Class));
535 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700536 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
537 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700538 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700539}
540
Brian Carlstrom4873d462011-08-21 15:23:39 -0700541Class* ClassLinker::AllocClass(size_t class_size) {
542 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700543}
544
Jesse Wilson35baaab2011-08-10 16:18:03 -0400545Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700546 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700547}
548
549Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700550 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700551}
552
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700553ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
554 return ObjectArray<StackTraceElement>::Alloc(
555 GetClassRoot(kJavaLangStackTraceElementArrayClass),
556 length);
557}
558
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700559Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700560 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700561 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700562 if (class_loader != NULL) {
563 Class* klass = FindClass(descriptor, NULL);
564 if (klass != NULL) {
565 return klass;
566 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700567 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700568 }
569
Carl Shapirob5573532011-07-12 18:22:59 -0700570 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700571 DCHECK(self != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700572 CHECK(!self->IsExceptionPending());
573 // Find the class in the loaded classes table.
574 Class* klass = LookupClass(descriptor, class_loader);
575 if (klass == NULL) {
576 // Class is not yet loaded.
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700577 if (descriptor[0] == '[') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700578 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700579 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700580 const DexFile::ClassPath& class_path = ((class_loader != NULL)
581 ? ClassLoader::GetClassPath(class_loader)
582 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700583 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700584 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700585 std::string name(PrintableString(descriptor));
586 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
587 "Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700588 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700589 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700590 const DexFile& dex_file = *pair.first;
591 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700592 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700593 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700594 if (!init_done_) {
595 // finish up init of hand crafted class_roots_
596 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700597 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700598 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700599 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400600 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700601 klass = GetClassRoot(kJavaLangString);
602 } else if (descriptor == "Ljava/lang/reflect/Field;") {
603 klass = GetClassRoot(kJavaLangReflectField);
604 } else if (descriptor == "Ljava/lang/reflect/Method;") {
605 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700606 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700607 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700608 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700609 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700610 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700611 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700612 if (!klass->IsLinked()) {
613 klass->SetDexCache(dex_cache);
614 LoadClass(dex_file, dex_class_def, klass, class_loader);
615 // Check for a pending exception during load
616 if (self->IsExceptionPending()) {
617 // TODO: free native allocations in klass
618 return NULL;
619 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700620 ObjectLock lock(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700621 klass->SetClinitThreadId(self->GetId());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700622 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700623 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700624 if (!success) {
625 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700626 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700627 // TODO: free native allocations in klass
628 klass = LookupClass(descriptor, class_loader);
629 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700630 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700631 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700632 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700633 CHECK(!klass->IsLoaded());
634 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700635 // Loading failed.
636 // TODO: CHECK(self->IsExceptionPending());
637 lock.NotifyAll();
638 return NULL;
639 }
640 CHECK(klass->IsLoaded());
641 // Link the class (if necessary)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700642 CHECK(!klass->IsLinked());
643 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700644 // Linking failed.
645 // TODO: CHECK(self->IsExceptionPending());
646 lock.NotifyAll();
647 return NULL;
648 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700649 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700650 }
651 }
652 }
653 // Link the class if it has not already been linked.
654 if (!klass->IsLinked() && !klass->IsErroneous()) {
655 ObjectLock lock(klass);
656 // Check for circular dependencies between classes.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700657 if (!klass->IsLinked() && klass->GetClinitThreadId() == self->GetId()) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700658 self->ThrowNewException("Ljava/lang/ClassCircularityError;", NULL); // TODO: detail
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700659 return NULL;
660 }
661 // Wait for the pending initialization to complete.
662 while (!klass->IsLinked() && !klass->IsErroneous()) {
663 lock.Wait();
664 }
665 }
666 if (klass->IsErroneous()) {
667 LG << "EarlierClassFailure"; // TODO: EarlierClassFailure
668 return NULL;
669 }
670 // Return the loaded class. No exceptions should be pending.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700671 CHECK(klass->IsLinked());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700672 CHECK(!self->IsExceptionPending());
673 return klass;
674}
675
Brian Carlstrom4873d462011-08-21 15:23:39 -0700676// Precomputes size that will be needed for Class, matching LinkStaticFields
677size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
678 const DexFile::ClassDef& dex_class_def) {
679 const byte* class_data = dex_file.GetClassData(dex_class_def);
680 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
681 size_t num_static_fields = header.static_fields_size_;
682 size_t num_ref = 0;
683 size_t num_32 = 0;
684 size_t num_64 = 0;
685 if (num_static_fields != 0) {
686 uint32_t last_idx = 0;
687 for (size_t i = 0; i < num_static_fields; ++i) {
688 DexFile::Field dex_field;
689 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
690 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
691 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
692 char c = descriptor[0];
693 if (c == 'L' || c == '[') {
694 num_ref++;
695 } else if (c == 'J' || c == 'D') {
696 num_64++;
697 } else {
698 num_32++;
699 }
700 }
701 }
702
703 // start with generic class data
704 size_t size = sizeof(Class);
705 // follow with reference fields which must be contiguous at start
706 size += (num_ref * sizeof(uint32_t));
707 // if there are 64-bit fields to add, make sure they are aligned
708 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
709 if (num_32 != 0) {
710 // use an available 32-bit field for padding
711 num_32--;
712 }
713 size += sizeof(uint32_t); // either way, we are adding a word
714 DCHECK_EQ(size, RoundUp(size, 8));
715 }
716 // tack on any 64-bit fields now that alignment is assured
717 size += (num_64 * sizeof(uint64_t));
718 // tack on any remaining 32-bit fields
719 size += (num_32 * sizeof(uint32_t));
720 return size;
721}
722
Brian Carlstromf615a612011-07-23 12:50:34 -0700723void ClassLinker::LoadClass(const DexFile& dex_file,
724 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700725 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700726 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700727 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700728 CHECK(klass->GetDexCache() != NULL);
729 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700730 const byte* class_data = dex_file.GetClassData(dex_class_def);
731 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700732
Brian Carlstromf615a612011-07-23 12:50:34 -0700733 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700734 CHECK(descriptor != NULL);
735
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700736 klass->SetClass(GetClassRoot(kJavaLangClass));
737 if (klass->GetDescriptor() != NULL) {
738 DCHECK(klass->GetDescriptor()->Equals(descriptor));
739 } else {
740 klass->SetDescriptor(String::AllocFromModifiedUtf8(descriptor));
741 }
742 uint32_t access_flags = dex_class_def.access_flags_;
743 // Make sure there aren't any "bonus" flags set, since we use them for runtime
744 // state.
745 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
746 klass->SetAccessFlags(access_flags);
747 klass->SetClassLoader(class_loader);
748 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
749 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700750
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700751 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700752
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700753 size_t num_static_fields = header.static_fields_size_;
754 size_t num_instance_fields = header.instance_fields_size_;
755 size_t num_direct_methods = header.direct_methods_size_;
756 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700757
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700758 klass->SetSourceFile(dex_file.dexGetSourceFile(dex_class_def));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700759
760 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700761 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700762
763 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700764 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700765 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700766 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700767 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700768 DexFile::Field dex_field;
769 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400770 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700771 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700772 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700773 }
774 }
775
776 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700777 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700778 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700779 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700780 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700781 DexFile::Field dex_field;
782 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400783 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700784 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700785 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700786 }
787 }
788
789 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700790 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700791 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700792 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700793 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700794 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700795 DexFile::Method dex_method;
796 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700797 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700798 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700799 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700800 // TODO: register maps
801 }
802 }
803
804 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700805 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700806 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700807 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700808 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700809 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700810 DexFile::Method dex_method;
811 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700812 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700813 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700814 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700815 // TODO: register maps
816 }
817 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700818}
819
Brian Carlstromf615a612011-07-23 12:50:34 -0700820void ClassLinker::LoadInterfaces(const DexFile& dex_file,
821 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700822 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700823 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700824 if (list != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700825 klass->SetInterfaces(AllocObjectArray<Class>(list->Size()));
826 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
827 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700828 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700829 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700830 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700831 }
832 }
833}
834
Brian Carlstromf615a612011-07-23 12:50:34 -0700835void ClassLinker::LoadField(const DexFile& dex_file,
836 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700837 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700838 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700839 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700840 dst->SetDeclaringClass(klass);
841 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
842 dst->SetTypeIdx(field_id.type_idx_);
843 dst->SetAccessFlags(src.access_flags_);
844
845 // In order to access primitive types using GetTypeDuringLinking we need to
846 // ensure they are resolved into the dex cache
847 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
848 if (descriptor[1] == '\0') {
849 // only the descriptors of primitive types should be 1 character long
850 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
851 DCHECK(resolved->IsPrimitive());
852 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700853}
854
Brian Carlstromf615a612011-07-23 12:50:34 -0700855void ClassLinker::LoadMethod(const DexFile& dex_file,
856 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700857 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700858 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700859 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700860 dst->SetDeclaringClass(klass);
861 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700862 {
863 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700864 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700865 dst->SetSignature(String::AllocFromModifiedUtf8(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700866 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700867 dst->SetProtoIdx(method_id.proto_idx_);
868 dst->SetCodeItemOffset(src.code_off_);
869 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
870 dst->SetShorty(shorty);
871 dst->SetAccessFlags(src.access_flags_);
872 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700873
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700874 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
875 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
876 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
877 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
878 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
879 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700880
Brian Carlstrom934486c2011-07-12 23:42:50 -0700881 // TODO: check for finalize method
882
Brian Carlstromf615a612011-07-23 12:50:34 -0700883 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700884 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700885 dst->SetNumRegisters(code_item->registers_size_);
886 dst->SetNumIns(code_item->ins_size_);
887 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700888 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700889 uint16_t num_args = Method::NumArgRegisters(shorty);
890 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700891 ++num_args;
892 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700893 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700894 // TODO: native methods
895 }
896}
897
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700898void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700899 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
900}
901
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700902void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700903 CHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700904 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700905 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700906}
907
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700908void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700909 RegisterDexFile(dex_file, AllocDexCache(dex_file));
910}
911
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700912void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700913 CHECK(dex_cache != NULL);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700914 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700915 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700916}
917
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700918const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700919 for (size_t i = 0; i != dex_caches_.size(); ++i) {
920 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700921 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700922 }
923 }
Brian Carlstromf615a612011-07-23 12:50:34 -0700924 CHECK(false) << "Could not find DexFile";
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700925 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700926}
927
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700928DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstromf615a612011-07-23 12:50:34 -0700929 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700930 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700931 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700932 }
933 }
Brian Carlstrom7e49dca2011-07-22 18:07:34 -0700934 CHECK(false) << "Could not find DexCache";
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700935 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700936}
937
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700938Class* ClassLinker::CreatePrimitiveClass(const char* descriptor,
939 Class::PrimitiveType type) {
940 // TODO: deduce one argument from the other
Brian Carlstrom4873d462011-08-21 15:23:39 -0700941 Class* klass = AllocClass(sizeof(Class));
Carl Shapiro565f5072011-07-10 13:39:43 -0700942 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700943 klass->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
944 klass->SetDescriptor(String::AllocFromModifiedUtf8(descriptor));
945 klass->SetPrimitiveType(type);
946 klass->SetStatus(Class::kStatusInitialized);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700947 bool success = InsertClass(descriptor, klass);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700948 CHECK(success) << "CreatePrimitiveClass(" << descriptor << ") failed";
Carl Shapiro565f5072011-07-10 13:39:43 -0700949 return klass;
950}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700951
Brian Carlstrombe977852011-07-19 14:54:54 -0700952// Create an array class (i.e. the class object for the array, not the
953// array itself). "descriptor" looks like "[C" or "[[[[B" or
954// "[Ljava/lang/String;".
955//
956// If "descriptor" refers to an array of primitives, look up the
957// primitive type's internally-generated class object.
958//
959// "loader" is the class loader of the class that's referring to us. It's
960// used to ensure that we're looking for the element type in the right
961// context. It does NOT become the class loader for the array class; that
962// always comes from the base element class.
963//
964// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700965Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700966 const ClassLoader* class_loader) {
967 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700968
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700969 // Identify the underlying element class and the array dimension depth.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700970 Class* component_type = NULL;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700971 int array_rank;
972 if (descriptor[1] == '[') {
973 // array of arrays; keep descriptor and grab stuff from parent
974 Class* outer = FindClass(descriptor.substr(1), class_loader);
975 if (outer != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700976 // want the base class, not "outer", in our component_type
977 component_type = outer->GetComponentType();
978 array_rank = outer->GetArrayRank() + 1;
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700979 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700980 DCHECK(component_type == NULL); // make sure we fail
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700981 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700982 } else {
983 array_rank = 1;
984 if (descriptor[1] == 'L') {
985 // array of objects; strip off "[" and look up descriptor.
986 const StringPiece subDescriptor = descriptor.substr(1);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700987 component_type = FindClass(subDescriptor, class_loader);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700988 } else {
989 // array of a primitive type
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700990 component_type = FindPrimitiveClass(descriptor[1]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700991 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700992 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700993
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700994 if (component_type == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700995 // failed
996 // DCHECK(Thread::Current()->IsExceptionPending()); // TODO
997 return NULL;
998 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700999
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001000 // See if the component type is already loaded. Array classes are
1001 // always associated with the class loader of their underlying
1002 // element type -- an array of Strings goes with the loader for
1003 // java/lang/String -- so we need to look for it there. (The
1004 // caller should have checked for the existence of the class
1005 // before calling here, but they did so with *their* class loader,
1006 // not the component type's loader.)
1007 //
1008 // If we find it, the caller adds "loader" to the class' initiating
1009 // loader list, which should prevent us from going through this again.
1010 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001011 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001012 // are the same, because our caller (FindClass) just did the
1013 // lookup. (Even if we get this wrong we still have correct behavior,
1014 // because we effectively do this lookup again when we add the new
1015 // class to the hash table --- necessary because of possible races with
1016 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001017 if (class_loader != component_type->GetClassLoader()) {
1018 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001019 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001020 return new_class;
1021 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001022 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001023
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001024 // Fill out the fields in the Class.
1025 //
1026 // It is possible to execute some methods against arrays, because
1027 // all arrays are subclasses of java_lang_Object_, so we need to set
1028 // up a vtable. We can just point at the one in java_lang_Object_.
1029 //
1030 // Array classes are simple enough that we don't need to do a full
1031 // link step.
1032
1033 Class* new_class = NULL;
1034 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001035 // Classes that were hand created, ie not by FindSystemClass
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001036 if (descriptor == "[Ljava/lang/Object;") {
1037 new_class = GetClassRoot(kObjectArrayClass);
1038 } else if (descriptor == "[C") {
1039 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001040 } else if (descriptor == "[I") {
1041 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001042 }
1043 }
1044 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001045 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001046 if (new_class == NULL) {
1047 return NULL;
1048 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001049 new_class->SetArrayRank(array_rank);
1050 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001051 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001052 DCHECK_LE(1, new_class->GetArrayRank());
1053 DCHECK(new_class->GetComponentType() != NULL);
1054 new_class->SetDescriptor(String::AllocFromModifiedUtf8(descriptor.ToString().c_str()));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001055 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001056 new_class->SetSuperClass(java_lang_Object);
1057 new_class->SetVTable(java_lang_Object->GetVTable());
1058 new_class->SetPrimitiveType(Class::kPrimNot);
1059 new_class->SetClassLoader(component_type->GetClassLoader());
1060 new_class->SetStatus(Class::kStatusInitialized);
1061 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001062 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001063
1064
1065 // All arrays have java/lang/Cloneable and java/io/Serializable as
1066 // interfaces. We need to set that up here, so that stuff like
1067 // "instanceof" works right.
1068 //
1069 // Note: The GC could run during the call to FindSystemClass,
1070 // so we need to make sure the class object is GC-valid while we're in
1071 // there. Do this by clearing the interface list so the GC will just
1072 // think that the entries are null.
1073
1074
1075 // Use the single, global copies of "interfaces" and "iftable"
1076 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001077 new_class->SetInterfaces(array_interfaces_);
1078 new_class->SetIFTableCount(2);
1079 new_class->SetIFTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001080
1081 // Inherit access flags from the component type. Arrays can't be
1082 // used as a superclass or interface, so we want to add "final"
1083 // and remove "interface".
1084 //
1085 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001086 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001087 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001088 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1089 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001090
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001091 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001092 return new_class;
1093 }
1094 // Another thread must have loaded the class after we
1095 // started but before we finished. Abandon what we've
1096 // done.
1097 //
1098 // (Yes, this happens.)
1099
1100 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001101 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001102 DCHECK(other_class != NULL);
1103 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001104}
1105
1106Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001107 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001108 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001109 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001110 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001111 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001112 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001113 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001114 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001115 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001116 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001117 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001118 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001119 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001120 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001121 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001122 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001123 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001124 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001125 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001126 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001127 std::string printable_type(PrintableChar(type));
1128 Thread::Current()->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1129 "Not a primitive type: %s", printable_type.c_str());
1130 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001131}
1132
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001133bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1134 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001135 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001136 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001137 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001138}
1139
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001140Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001141 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom7e93b502011-08-04 14:16:22 -07001142 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001143 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001144 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001145 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001146 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001147 return klass;
1148 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001149 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001150 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001151}
1152
1153bool ClassLinker::InitializeClass(Class* klass) {
1154 CHECK(klass->GetStatus() == Class::kStatusResolved ||
1155 klass->GetStatus() == Class::kStatusError);
1156
Carl Shapirob5573532011-07-12 18:22:59 -07001157 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001158
1159 {
1160 ObjectLock lock(klass);
1161
1162 if (klass->GetStatus() < Class::kStatusVerified) {
1163 if (klass->IsErroneous()) {
1164 LG << "re-initializing failed class"; // TODO: throw
1165 return false;
1166 }
1167
1168 CHECK(klass->GetStatus() == Class::kStatusResolved);
1169
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001170 klass->SetStatus(Class::kStatusVerifying);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001171 if (!DexVerify::VerifyClass(klass)) {
1172 LG << "Verification failed"; // TODO: ThrowVerifyError
1173 Object* exception = self->GetException();
Brian Carlstromf7ed11a2011-08-09 17:55:51 -07001174 klass->SetVerifyErrorClass(exception->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001175 klass->SetStatus(Class::kStatusError);
1176 return false;
1177 }
1178
1179 klass->SetStatus(Class::kStatusVerified);
1180 }
1181
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001182 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001183 return true;
1184 }
1185
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001186 while (klass->GetStatus() == Class::kStatusInitializing) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001187 // we caught somebody else in the act; was it us?
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001188 if (klass->GetClinitThreadId() == self->GetId()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001189 LG << "recursive <clinit>";
1190 return true;
1191 }
1192
1193 CHECK(!self->IsExceptionPending());
1194
1195 lock.Wait(); // TODO: check for interruption
1196
1197 // When we wake up, repeat the test for init-in-progress. If
1198 // there's an exception pending (only possible if
1199 // "interruptShouldThrow" was set), bail out.
1200 if (self->IsExceptionPending()) {
1201 CHECK(false);
1202 LG << "Exception in initialization."; // TODO: ExceptionInInitializerError
1203 klass->SetStatus(Class::kStatusError);
1204 return false;
1205 }
1206 if (klass->GetStatus() == Class::kStatusInitializing) {
1207 continue;
1208 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001209 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001210 klass->GetStatus() == Class::kStatusError);
1211 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001212 // The caller wants an exception, but it was thrown in a
1213 // different thread. Synthesize one here.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001214 LG << "<clinit> failed"; // TODO: throw UnsatisfiedLinkError
1215 return false;
1216 }
1217 return true; // otherwise, initialized
1218 }
1219
1220 // see if we failed previously
1221 if (klass->IsErroneous()) {
1222 // might be wise to unlock before throwing; depends on which class
1223 // it is that we have locked
1224
1225 // TODO: throwEarlierClassFailure(klass);
1226 return false;
1227 }
1228
1229 if (!ValidateSuperClassDescriptors(klass)) {
1230 klass->SetStatus(Class::kStatusError);
1231 return false;
1232 }
1233
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001234 DCHECK(klass->GetStatus() < Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001235
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001236 klass->SetClinitThreadId(self->GetId());
1237 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001238 }
1239
1240 if (!InitializeSuperClass(klass)) {
1241 return false;
1242 }
1243
1244 InitializeStaticFields(klass);
1245
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001246 Method* clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001247 if (clinit != NULL) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001248 // JValue unused;
1249 // TODO: dvmCallMethod(self, method, NULL, &unused);
Elliott Hughes53b61312011-08-12 18:28:20 -07001250 // UNIMPLEMENTED(FATAL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001251 }
1252
1253 {
1254 ObjectLock lock(klass);
1255
1256 if (self->IsExceptionPending()) {
1257 klass->SetStatus(Class::kStatusError);
1258 } else {
1259 klass->SetStatus(Class::kStatusInitialized);
1260 }
1261 lock.NotifyAll();
1262 }
1263
1264 return true;
1265}
1266
1267bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1268 if (klass->IsInterface()) {
1269 return true;
1270 }
1271 // begin with the methods local to the superclass
1272 if (klass->HasSuperClass() &&
1273 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1274 const Class* super = klass->GetSuperClass();
1275 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001276 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001277 if (method != super->GetVirtualMethod(i) &&
1278 !HasSameMethodDescriptorClasses(method, super, klass)) {
1279 LG << "Classes resolve differently in superclass";
1280 return false;
1281 }
1282 }
1283 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001284 for (size_t i = 0; i < klass->GetIFTableCount(); ++i) {
1285 const InterfaceEntry* iftable = &klass->GetIFTable()[i];
Brian Carlstrom30b94452011-08-25 21:35:26 -07001286 Class* interface = iftable->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001287 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1288 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001289 uint32_t vtable_index = iftable->GetMethodIndexArray()[j];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001290 const Method* method = klass->GetVirtualMethod(vtable_index);
1291 if (!HasSameMethodDescriptorClasses(method, interface,
1292 method->GetClass())) {
1293 LG << "Classes resolve differently in interface"; // TODO: LinkageError
1294 return false;
1295 }
1296 }
1297 }
1298 }
1299 return true;
1300}
1301
1302bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001303 const Class* klass1,
1304 const Class* klass2) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001305 const DexFile& dex_file = FindDexFile(method->GetClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001306 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001307 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001308 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001309 const char* descriptor = it->GetDescriptor();
1310 if (descriptor == NULL) {
1311 break;
1312 }
1313 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1314 // Found a non-primitive type.
1315 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1316 return false;
1317 }
1318 }
1319 }
1320 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001321 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001322 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1323 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1324 return false;
1325 }
1326 }
1327 return true;
1328}
1329
1330// Returns true if classes referenced by the descriptor are the
1331// same classes in klass1 as they are in klass2.
1332bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001333 const Class* klass1,
1334 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001335 CHECK(descriptor != NULL);
1336 CHECK(klass1 != NULL);
1337 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001338 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001339 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001340 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001341 // TODO: found2 == NULL
1342 // TODO: lookup found1 in initiating loader list
1343 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001344 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001345 if (found1 == found2) {
1346 return true;
1347 } else {
1348 return false;
1349 }
1350 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001351 return true;
1352}
1353
1354bool ClassLinker::InitializeSuperClass(Class* klass) {
1355 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001356 if (!klass->IsInterface() && klass->HasSuperClass()) {
1357 Class* super_class = klass->GetSuperClass();
1358 if (super_class->GetStatus() != Class::kStatusInitialized) {
1359 CHECK(!super_class->IsInterface());
1360 klass->MonitorExit();
1361 bool super_initialized = InitializeClass(super_class);
1362 klass->MonitorEnter();
1363 // TODO: check for a pending exception
1364 if (!super_initialized) {
1365 klass->SetStatus(Class::kStatusError);
1366 klass->NotifyAll();
1367 return false;
1368 }
1369 }
1370 }
1371 return true;
1372}
1373
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001374bool ClassLinker::EnsureInitialized(Class* c) {
1375 CHECK(c != NULL);
1376 if (c->IsInitialized()) {
1377 return true;
1378 }
1379
1380 c->MonitorExit();
1381 InitializeClass(c);
1382 c->MonitorEnter();
1383 return !Thread::Current()->IsExceptionPending();
1384}
1385
Brian Carlstromb9edb842011-08-28 16:31:06 -07001386StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1387 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001388 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1389 Class* klass = class_linker->ResolveType(type_idx, referrer);
1390 if (klass == NULL) {
1391 UNIMPLEMENTED(FATAL) << "throw exception due to unresolved class";
1392 }
1393 if (!class_linker->EnsureInitialized(klass)) {
1394 CHECK(Thread::Current()->IsExceptionPending());
1395 UNIMPLEMENTED(FATAL) << "throw exception due to class initializtion problem";
1396 }
1397 return klass;
1398}
1399
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001400void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001401 size_t num_static_fields = klass->NumStaticFields();
1402 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001403 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001404 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001405 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001406 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001407 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001408 return;
1409 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001410 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001411 const DexFile& dex_file = FindDexFile(dex_cache);
1412 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001413 CHECK(dex_class_def != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001414 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001415 if (addr == NULL) {
1416 // All this class' static fields have default values.
1417 return;
1418 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001419 size_t array_size = DecodeUnsignedLeb128(&addr);
1420 for (size_t i = 0; i < array_size; ++i) {
Jesse Wilson35baaab2011-08-10 16:18:03 -04001421 Field* field = klass->GetStaticField(i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001422 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001423 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001424 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001425 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001426 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001427 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001428 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001429 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001430 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001431 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001432 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001433 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001434 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001435 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001436 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001437 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001438 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001439 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001440 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001441 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001442 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001443 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001444 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001445 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001446 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001447 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001448 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001449 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001450 break;
1451 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001452 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001453 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001454 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001455 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001456 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001457 break;
1458 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001459 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001460 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001461 }
1462}
1463
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001464bool ClassLinker::LinkClass(Class* klass) {
1465 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001466 if (!LinkSuperClass(klass)) {
1467 return false;
1468 }
1469 if (!LinkMethods(klass)) {
1470 return false;
1471 }
1472 if (!LinkInstanceFields(klass)) {
1473 return false;
1474 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001475 if (!LinkStaticFields(klass)) {
1476 return false;
1477 }
1478 CreateReferenceInstanceOffsets(klass);
1479 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001480 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1481 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001482 return true;
1483}
1484
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001485bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001486 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1487 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1488 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001489 if (super_class == NULL) {
1490 LG << "Failed to resolve superclass";
1491 return false;
1492 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001493 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001494 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001495 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1496 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1497 Class *interface = ResolveType(dex_file, idx, klass);
1498 klass->SetInterface(i, interface);
1499 if (interface == NULL) {
1500 LG << "Failed to resolve interface";
1501 return false;
1502 }
1503 // Verify
1504 if (!klass->CanAccess(interface)) {
1505 LG << "Inaccessible interface";
1506 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001507 }
1508 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001509 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001510 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001511 return true;
1512}
1513
1514bool ClassLinker::LinkSuperClass(Class* klass) {
1515 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001516 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001517 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001518 if (super != NULL) {
1519 LG << "Superclass must not be defined"; // TODO: ClassFormatError
1520 return false;
1521 }
1522 // TODO: clear finalize attribute
1523 return true;
1524 }
1525 if (super == NULL) {
1526 LG << "No superclass defined"; // TODO: LinkageError
1527 return false;
1528 }
1529 // Verify
1530 if (super->IsFinal()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001531 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is declared final"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001532 return false;
1533 }
1534 if (super->IsInterface()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001535 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is an interface"; // TODO: IncompatibleClassChangeError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001536 return false;
1537 }
1538 if (!klass->CanAccess(super)) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001539 LG << "Superclass " << super->GetDescriptor()->ToModifiedUtf8() << " is inaccessible"; // TODO: IllegalAccessError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001540 return false;
1541 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001542#ifndef NDEBUG
1543 // Ensure super classes are fully resolved prior to resolving fields..
1544 while (super != NULL) {
1545 CHECK(super->IsLinked());
1546 super = super->GetSuperClass();
1547 }
1548#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001549 return true;
1550}
1551
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001552// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001553bool ClassLinker::LinkMethods(Class* klass) {
1554 if (klass->IsInterface()) {
1555 // No vtable.
1556 size_t count = klass->NumVirtualMethods();
1557 if (!IsUint(16, count)) {
1558 LG << "Too many methods on interface"; // TODO: VirtualMachineError
1559 return false;
1560 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001561 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001562 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001563 }
1564 } else {
1565 // Link virtual method tables
1566 LinkVirtualMethods(klass);
1567
1568 // Link interface method tables
1569 LinkInterfaceMethods(klass);
1570
1571 // Insert stubs.
1572 LinkAbstractMethods(klass);
1573 }
1574 return true;
1575}
1576
1577bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001578 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001579 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1580 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001581 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001582 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001583 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001584 // See if any of our virtual methods override the superclass.
1585 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001586 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001587 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001588 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001589 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001590 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001591 // Verify
1592 if (super_method->IsFinal()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001593 LG << "Method overrides final method"; // TODO: VirtualMachineError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001594 return false;
1595 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001596 vtable->Set(j, local_method);
1597 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001598 break;
1599 }
1600 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001601 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001602 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001603 vtable->Set(actual_count, local_method);
1604 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001605 actual_count += 1;
1606 }
1607 }
1608 if (!IsUint(16, actual_count)) {
1609 LG << "Too many methods defined on class"; // TODO: VirtualMachineError
1610 return false;
1611 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001612 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001613 CHECK_LE(actual_count, max_count);
1614 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001615 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001616 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001617 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001618 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001619 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001620 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001621 if (!IsUint(16, num_virtual_methods)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001622 LG << "Too many methods"; // TODO: VirtualMachineError
1623 return false;
1624 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001625 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001626 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001627 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1628 vtable->Set(i, virtual_method);
1629 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001630 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001631 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001632 }
1633 return true;
1634}
1635
1636bool ClassLinker::LinkInterfaceMethods(Class* klass) {
1637 int pool_offset = 0;
1638 int pool_size = 0;
1639 int miranda_count = 0;
1640 int miranda_alloc = 0;
1641 size_t super_ifcount;
1642 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001643 super_ifcount = klass->GetSuperClass()->GetIFTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001644 } else {
1645 super_ifcount = 0;
1646 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001647 size_t ifcount = super_ifcount;
1648 ifcount += klass->NumInterfaces();
1649 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001650 ifcount += klass->GetInterface(i)->GetIFTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001651 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001652 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001653 // TODO: enable these asserts with klass status validation
1654 // DCHECK(klass->GetIFTableCount() == 0);
1655 // DCHECK(klass->GetIFTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001656 return true;
1657 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001658 InterfaceEntry* iftable = new InterfaceEntry[ifcount];
1659 memset(iftable, 0x00, sizeof(InterfaceEntry) * ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001660 if (super_ifcount != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001661 memcpy(iftable, klass->GetSuperClass()->GetIFTable(),
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001662 sizeof(InterfaceEntry) * super_ifcount);
1663 }
1664 // Flatten the interface inheritance hierarchy.
1665 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001666 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
1667 Class* interf = klass->GetInterface(i);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001668 DCHECK(interf != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001669 if (!interf->IsInterface()) {
1670 LG << "Class implements non-interface class"; // TODO: IncompatibleClassChangeError
1671 return false;
1672 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001673 iftable[idx++].SetInterface(interf);
1674 for (size_t j = 0; j < interf->GetIFTableCount(); j++) {
1675 iftable[idx++].SetInterface(interf->GetIFTable()[j].GetInterface());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001676 }
1677 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001678 klass->SetIFTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001679 CHECK_EQ(idx, ifcount);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001680 klass->SetIFTableCount(ifcount);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001681 if (klass->IsInterface() || super_ifcount == ifcount) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001682 return true;
1683 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001684 for (size_t i = super_ifcount; i < ifcount; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001685 pool_size += iftable[i].GetInterface()->NumVirtualMethods();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001686 }
1687 if (pool_size == 0) {
1688 return true;
1689 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001690 klass->SetIfviPoolCount(pool_size);
1691 uint32_t* ifvi_pool = new uint32_t[pool_size];
1692 klass->SetIfviPool(ifvi_pool);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001693 std::vector<Method*> miranda_list;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001694 for (size_t i = super_ifcount; i < ifcount; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001695 iftable[i].SetMethodIndexArray(ifvi_pool + pool_offset);
1696 Class* interface = iftable[i].GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001697 pool_offset += interface->NumVirtualMethods(); // end here
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001698 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001699 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1700 Method* interface_method = interface->GetVirtualMethod(j);
1701 int k; // must be signed
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001702 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1703 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001704 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1705 if (!vtable_method->IsPublic()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001706 LG << "Implementation not public";
1707 return false;
1708 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001709 iftable[i].GetMethodIndexArray()[j] = k;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710 break;
1711 }
1712 }
1713 if (k < 0) {
1714 if (miranda_count == miranda_alloc) {
1715 miranda_alloc += 8;
1716 if (miranda_list.empty()) {
1717 miranda_list.resize(miranda_alloc);
1718 } else {
1719 miranda_list.resize(miranda_alloc);
1720 }
1721 }
1722 int mir;
1723 for (mir = 0; mir < miranda_count; mir++) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001724 Method* miranda_method = miranda_list[mir];
1725 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001726 break;
1727 }
1728 }
1729 // point the interface table at a phantom slot index
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001730 iftable[i].GetMethodIndexArray()[j] =
1731 vtable->GetLength() + mir;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001732 if (mir == miranda_count) {
1733 miranda_list[miranda_count++] = interface_method;
1734 }
1735 }
1736 }
1737 }
1738 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001739 int old_method_count = klass->NumVirtualMethods();
1740 int new_method_count = old_method_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001741 klass->SetVirtualMethods(
1742 klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001743
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001744 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1745 CHECK(vtable != NULL);
1746 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001747 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001748 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001749 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001750 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001751 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001752 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001753 meth->SetDeclaringClass(klass);
1754 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1755 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001756 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001757 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001758 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001759 // TODO: do not assign to the vtable field until it is fully constructed.
1760 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001761 }
1762 return true;
1763}
1764
1765void ClassLinker::LinkAbstractMethods(Class* klass) {
1766 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001767 Method* method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001768 if (method->IsAbstract()) {
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001769 LG << "AbstractMethodError";
Shih-wei Liao2fb97532011-08-11 16:17:23 -07001770 // TODO: throw AbstractMethodError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001771 }
1772 }
1773}
1774
1775bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001776 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001777 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001778}
1779
1780bool ClassLinker::LinkStaticFields(Class* klass) {
1781 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001782 size_t allocated_class_size = klass->GetClassSize();
1783 bool success = LinkFields(klass, false);
1784 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001785 return success;
1786}
1787
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001788bool ClassLinker::LinkFields(Class *klass, bool instance) {
1789 size_t num_fields =
1790 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1791
1792 ObjectArray<Field>* fields =
1793 instance ? klass->GetIFields() : klass->GetSFields();
1794 // Fields updated at end of LinkFields
1795 size_t num_reference_fields;
1796 size_t size;
1797
1798 // Initialize size and field_offset
1799 MemberOffset field_offset = Class::FieldsOffset();
1800 if (instance) {
1801 Class* super_class = klass->GetSuperClass();
1802 if (super_class != NULL) {
1803 CHECK(super_class->IsLinked());
1804 field_offset = MemberOffset(super_class->GetObjectSize());
1805 if (field_offset.Uint32Value() == 0u) {
1806 field_offset = OFFSET_OF_OBJECT_MEMBER(DataObject, fields_);
1807 }
1808 } else {
1809 field_offset = OFFSET_OF_OBJECT_MEMBER(DataObject, fields_);
1810 }
1811 size = field_offset.Uint32Value();
1812 } else {
1813 size = klass->GetClassSize();
1814 }
1815 DCHECK_LE(CLASS_SMALLEST_OFFSET, size);
1816
Brian Carlstrom4873d462011-08-21 15:23:39 -07001817 CHECK((num_fields == 0) == (fields == NULL));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001818
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001819 // Move references to the front.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001820 size_t i = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001821 num_reference_fields = 0;
1822 for (; i < num_fields; i++) {
1823 Field* field = fields->Get(i);
1824 const Class* field_type = field->GetTypeDuringLinking();
1825 // if a field's type at this point is NULL it isn't primitive
1826 if (field_type != NULL && field_type->IsPrimitive()) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001827 for (size_t j = num_fields - 1; j > i; j--) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001828 Field* ref_field = fields->Get(j);
1829 const Class* ref_field_type = ref_field->GetTypeDuringLinking();
1830 if (ref_field_type == NULL || !ref_field_type->IsPrimitive()) {
1831 fields->Set(i, ref_field);
1832 fields->Set(j, field);
1833 field = ref_field;
1834 field_type = ref_field_type;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001835 num_reference_fields++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001836 break;
1837 }
1838 }
1839 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001840 num_reference_fields++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001841 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001842 if (field_type != NULL && field_type->IsPrimitive()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001843 break;
1844 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001845 field->SetOffset(field_offset);
1846 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001847 }
1848
1849 // Now we want to pack all of the double-wide fields together. If
1850 // we're not aligned, though, we want to shuffle one 32-bit field
1851 // into place. If we can't find one, we'll have to pad it.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001852 if (i != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
1853 Field* field = fields->Get(i);
1854 const Class* c = field->GetTypeDuringLinking();
1855 CHECK(c != NULL); // should only be working on primitive types
1856 if (!c->IsPrimitiveLong() && !c->IsPrimitiveDouble()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001857 // The field that comes next is 32-bit, so just advance past it.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001858 DCHECK(c->IsPrimitive());
1859 field->SetOffset(field_offset);
1860 field_offset = MemberOffset(field_offset.Uint32Value() +
1861 sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001862 i++;
1863 } else {
1864 // Next field is 64-bit, so search for a 32-bit field we can
1865 // swap into it.
1866 bool found = false;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001867 for (size_t j = num_fields - 1; j > i; j--) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001868 Field* single_field = fields->Get(j);
1869 const Class* rc = single_field->GetTypeDuringLinking();
1870 CHECK(rc != NULL); // should only be working on primitive types
1871 if (!rc->IsPrimitiveLong() && !rc->IsPrimitiveDouble()) {
1872 fields->Set(i, single_field);
1873 fields->Set(j, field);
1874 field = single_field;
1875 field->SetOffset(field_offset);
1876 field_offset = MemberOffset(field_offset.Uint32Value() +
1877 sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001878 found = true;
1879 i++;
1880 break;
1881 }
1882 }
1883 if (!found) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001884 field_offset = MemberOffset(field_offset.Uint32Value() +
1885 sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001886 }
1887 }
1888 }
1889
1890 // Alignment is good, shuffle any double-wide fields forward, and
1891 // finish assigning field offsets to all fields.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001892 DCHECK(i == num_fields || IsAligned(field_offset.Uint32Value(), 4));
Brian Carlstrom4873d462011-08-21 15:23:39 -07001893 for ( ; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001894 Field* field = fields->Get(i);
1895 const Class* c = field->GetTypeDuringLinking();
1896 CHECK(c != NULL); // should only be working on primitive types
1897 if (!c->IsPrimitiveDouble() && !c->IsPrimitiveLong()) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001898 for (size_t j = num_fields - 1; j > i; j--) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001899 Field* double_field = fields->Get(j);
1900 const Class* rc = double_field->GetTypeDuringLinking();
1901 CHECK(rc != NULL); // should only be working on primitive types
1902 if (rc->IsPrimitiveDouble() || rc->IsPrimitiveLong()) {
1903 fields->Set(i, double_field);
1904 fields->Set(j, field);
1905 field = double_field;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001906 c = rc;
1907 break;
1908 }
1909 }
1910 } else {
1911 // This is a double-wide field, leave it be.
1912 }
1913
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001914 field->SetOffset(field_offset);
1915 if (c->IsPrimitiveLong() || c->IsPrimitiveDouble()) {
1916 field_offset = MemberOffset(field_offset.Uint32Value() +
1917 sizeof(uint64_t));
1918 } else {
1919 field_offset = MemberOffset(field_offset.Uint32Value() +
1920 sizeof(uint32_t));
Brian Carlstrom4873d462011-08-21 15:23:39 -07001921 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001922 }
1923
1924#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07001925 // Make sure that all reference fields appear before
1926 // non-reference fields, and all double-wide fields are aligned.
1927 bool seen_non_ref = false;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001928 for (i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001929 Field* field = fields->Get(i);
1930 const Class* c = field->GetTypeDuringLinking();
1931 if (c != NULL && c->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001932 if (!seen_non_ref) {
1933 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07001934 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001935 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001936 } else {
1937 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001938 }
1939 }
Brian Carlstrombe977852011-07-19 14:54:54 -07001940 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001941 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001942 }
1943#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001944 size = field_offset.Uint32Value();
1945 DCHECK_LE(CLASS_SMALLEST_OFFSET, size);
1946 // Update klass
1947 if(instance) {
1948 klass->SetNumReferenceInstanceFields(num_reference_fields);
1949 if(!klass->IsVariableSize()) {
1950 klass->SetObjectSize(size);
1951 }
1952 } else {
1953 klass->SetNumReferenceStaticFields(num_reference_fields);
1954 klass->SetClassSize(size);
1955 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001956 return true;
1957}
1958
1959// Set the bitmap of reference offsets, refOffsets, from the ifields
1960// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07001961void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001962 uint32_t reference_offsets = 0;
1963 Class* super_class = klass->GetSuperClass();
1964 if (super_class != NULL) {
1965 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001966 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001967 if (reference_offsets == CLASS_WALK_SUPER) {
1968 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001969 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001970 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001971 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001972 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001973}
1974
1975void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001976 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001977}
1978
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001979void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
1980 uint32_t reference_offsets) {
1981 size_t num_reference_fields =
1982 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
1983 : klass->NumReferenceStaticFieldsDuringLinking();
1984 const ObjectArray<Field>* fields =
1985 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001986 // All of the fields that contain object references are guaranteed
1987 // to be at the beginning of the fields list.
1988 for (size_t i = 0; i < num_reference_fields; ++i) {
1989 // Note that byte_offset is the offset from the beginning of
1990 // object, not the offset into instance data
1991 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001992 MemberOffset byte_offset = field->GetOffsetDuringLinking();
1993 CHECK_GE(byte_offset.Uint32Value(), CLASS_SMALLEST_OFFSET);
1994 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
1995 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
1996 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001997 CHECK_NE(new_bit, 0U);
1998 reference_offsets |= new_bit;
1999 } else {
2000 reference_offsets = CLASS_WALK_SUPER;
2001 break;
2002 }
2003 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002004 // Update fields in klass
2005 if (instance) {
2006 klass->SetReferenceInstanceOffsets(reference_offsets);
2007 } else {
2008 klass->SetReferenceStaticOffsets(reference_offsets);
2009 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002010}
2011
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002012String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002013 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002014 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002015 if (resolved != NULL) {
2016 return resolved;
2017 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002018 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2019 int32_t utf16_length = dex_file.GetStringLength(string_id);
2020 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002021 // TODO: remote the const_cast below
2022 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002023 dex_cache->SetResolvedString(string_idx, string);
2024 return string;
2025}
2026
2027Class* ClassLinker::ResolveType(const DexFile& dex_file,
2028 uint32_t type_idx,
2029 DexCache* dex_cache,
2030 const ClassLoader* class_loader) {
2031 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002032 if (resolved == NULL) {
2033 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2034 if (descriptor[1] == '\0') {
2035 // only the descriptors of primitive types should be 1 character long
2036 resolved = FindPrimitiveClass(descriptor[0]);
2037 } else {
2038 resolved = FindClass(descriptor, class_loader);
2039 }
2040 if (resolved != NULL) {
2041 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2042 if (dex_cache != check->GetDexCache()) {
2043 if (check->GetClassLoader() != NULL) {
2044 LG << "Class resolved by unexpected DEX"; // TODO: IllegalAccessError
2045 resolved = NULL;
2046 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002047 }
2048 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002049 if (resolved != NULL) {
2050 dex_cache->SetResolvedType(type_idx, resolved);
2051 } else {
2052 DCHECK(Thread::Current()->IsExceptionPending());
2053 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002054 }
2055 return resolved;
2056}
2057
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002058Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2059 uint32_t method_idx,
2060 DexCache* dex_cache,
2061 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002062 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002063 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2064 if (resolved != NULL) {
2065 return resolved;
2066 }
2067 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2068 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2069 if (klass == NULL) {
2070 return NULL;
2071 }
2072
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002073 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002074 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002075 if (is_direct) {
2076 resolved = klass->FindDirectMethod(name, signature);
2077 } else {
2078 resolved = klass->FindVirtualMethod(name, signature);
2079 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002080 if (resolved != NULL) {
2081 dex_cache->SetResolvedMethod(method_idx, resolved);
2082 } else {
2083 // DCHECK(Thread::Current()->IsExceptionPending());
2084 }
2085 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002086}
2087
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002088Field* ClassLinker::ResolveField(const DexFile& dex_file,
2089 uint32_t field_idx,
2090 DexCache* dex_cache,
2091 const ClassLoader* class_loader,
2092 bool is_static) {
2093 Field* resolved = dex_cache->GetResolvedField(field_idx);
2094 if (resolved != NULL) {
2095 return resolved;
2096 }
2097 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2098 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2099 if (klass == NULL) {
2100 return NULL;
2101 }
2102
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002103 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002104 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2105 // TODO: LinkageError?
2106 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002107 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002108 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002109 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002110 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002111 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002112 if (resolved != NULL) {
2113 dex_cache->SetResolvedfield(field_idx, resolved);
2114 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002115 // TODO: DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002116 }
2117 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002118}
2119
Elliott Hughese27955c2011-08-26 15:21:24 -07002120size_t ClassLinker::NumLoadedClasses() const {
2121 MutexLock mu(classes_lock_);
2122 return classes_.size();
2123}
2124
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002125} // namespace art