blob: 6daa27ae75ed724a38f971ff70de49ab25e70016 [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004
Brian Carlstromdbc05252011-09-09 01:59:59 -07005#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009
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"
Elliott Hughes54e7df12011-09-16 11:47:04 -070018#include "monitor.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070019#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"
Elliott Hughes54e7df12011-09-16 11:47:04 -070023#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070024#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070025
26namespace art {
27
Elliott Hughes4a2b4172011-09-20 17:08:25 -070028namespace {
29
30void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
31void ThrowNoClassDefFoundError(const char* fmt, ...) {
32 va_list args;
33 va_start(args, fmt);
34 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
35 va_end(args);
36}
37
38void ThrowVirtualMachineError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
39void ThrowVirtualMachineError(const char* fmt, ...) {
40 va_list args;
41 va_start(args, fmt);
42 Thread::Current()->ThrowNewExceptionV("Ljava/lang/VirtualMachineError;", fmt, args);
43 va_end(args);
44}
45
46void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
47void ThrowLinkageError(const char* fmt, ...) {
48 va_list args;
49 va_start(args, fmt);
50 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
51 va_end(args);
52}
53
54void ThrowEarlierClassFailure(Class* c) {
55 /*
56 * The class failed to initialize on a previous attempt, so we want to throw
57 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
58 * failed in verification, in which case v2 5.4.1 says we need to re-throw
59 * the previous error.
60 */
61 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
62
63 if (c->GetVerifyErrorClass() != NULL) {
64 // TODO: change the verifier to store an _instance_, with a useful detail message?
65 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
66 Thread::Current()->ThrowNewException(error_descriptor.c_str(), "%s",
67 PrettyDescriptor(c->GetDescriptor()).c_str());
68 } else {
69 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
70 }
71}
72
73}
74
Elliott Hughes418d20f2011-09-22 14:00:39 -070075const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -070076 "Ljava/lang/Class;",
77 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -070078 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070079 "[Ljava/lang/Object;",
80 "Ljava/lang/String;",
81 "Ljava/lang/reflect/Field;",
82 "Ljava/lang/reflect/Method;",
83 "Ljava/lang/ClassLoader;",
84 "Ldalvik/system/BaseDexClassLoader;",
85 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070086 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070087 "Z",
88 "B",
89 "C",
90 "D",
91 "F",
92 "I",
93 "J",
94 "S",
95 "V",
96 "[Z",
97 "[B",
98 "[C",
99 "[D",
100 "[F",
101 "[I",
102 "[J",
103 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700104 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700105};
106
Elliott Hughes5f791332011-09-15 17:45:30 -0700107class ObjectLock {
108 public:
109 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
110 CHECK(object != NULL);
111 obj_->MonitorEnter(self_);
112 }
113
114 ~ObjectLock() {
115 obj_->MonitorExit(self_);
116 }
117
118 void Wait() {
119 return Monitor::Wait(self_, obj_, 0, 0, false);
120 }
121
122 void Notify() {
123 obj_->Notify();
124 }
125
126 void NotifyAll() {
127 obj_->NotifyAll();
128 }
129
130 private:
131 Thread* self_;
132 Object* obj_;
133 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
134};
135
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700136ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path,
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700137 const std::vector<const DexFile*>& class_path,
Brian Carlstromc74255f2011-09-11 22:47:39 -0700138 InternTable* intern_table, bool image) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700139 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700140 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700141 if (image) {
142 class_linker->InitFromImage(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700143 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700144 class_linker->Init(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700145 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700146 // TODO: check for failure during initialization
147 return class_linker.release();
148}
149
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700150ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700151 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700152 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700153 array_interfaces_(NULL),
154 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700155 init_done_(false),
156 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700157 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700158}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700159
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700160void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
161 const std::vector<const DexFile*>& class_path) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700162 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700163
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700164 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700165 Class* java_lang_Class = down_cast<Class*>(
166 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700167 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700168 java_lang_Class->SetClass(java_lang_Class);
169 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700170 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700171
Elliott Hughes418d20f2011-09-22 14:00:39 -0700172 // Class[] is used for reflection support.
173 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
174 class_array_class->SetComponentType(java_lang_Class);
175
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700176 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700177 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700178 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700179 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700180 java_lang_Class->SetSuperClass(java_lang_Object);
181 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700182
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700183 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700184 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700185 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700186
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700187 // Setup the char class to be used for char[]
188 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
189
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700190 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700191 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700192 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700193 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700194
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700195 // Setup String
196 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
197 String::SetClass(java_lang_String);
198 java_lang_String->SetObjectSize(sizeof(String));
199 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400200
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700201 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700202 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
203 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700204 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700205 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
206 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
207 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700208
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700209 // Create storage for root classes, save away our work so far (requires
210 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700211 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700212 SetClassRoot(kJavaLangClass, java_lang_Class);
213 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700214 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700215 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700216 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700217 SetClassRoot(kJavaLangString, java_lang_String);
218
219 // Setup the primitive type classes.
220 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
221 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700222 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
223 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
224 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
225 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
226 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
227 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
228
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700229 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700230 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700231 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700232
233 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
234 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700235 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700236 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
237 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700238 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700239
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700240 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700241
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700242 // setup boot_class_path_ and register class_path now that we can
243 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700244 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700245 const DexFile* dex_file = boot_class_path[i];
246 CHECK(dex_file != NULL);
247 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700248 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700249 for (size_t i = 0; i != class_path.size(); ++i) {
250 const DexFile* dex_file = class_path[i];
251 CHECK(dex_file != NULL);
252 RegisterDexFile(*dex_file);
253 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254
255 // Field and Method are necessary so that FindClass can link members
256 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
257 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700258 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700259 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
260 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
261 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
262 Field::SetClass(java_lang_reflect_Field);
263
264 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700265 java_lang_reflect_Method->SetDescriptor(
266 intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700267 CHECK(java_lang_reflect_Method != NULL);
268 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
269 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
270 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
271 Method::SetClass(java_lang_reflect_Method);
272
273 // now we can use FindSystemClass
274
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700275 // run char class through InitializePrimitiveClass to finish init
276 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
277 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
278
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700279 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700280 java_lang_Object->SetStatus(Class::kStatusNotReady);
281 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
282 CHECK_EQ(java_lang_Object, Object_class);
283 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
284 java_lang_String->SetStatus(Class::kStatusNotReady);
285 Class* String_class = FindSystemClass("Ljava/lang/String;");
286 CHECK_EQ(java_lang_String, String_class);
287 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
288
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700289 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700290 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
291 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
292
293 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
294 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
295
296 Class* found_char_array_class = FindSystemClass("[C");
297 CHECK_EQ(char_array_class, found_char_array_class);
298
299 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
300 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
301
302 Class* found_int_array_class = FindSystemClass("[I");
303 CHECK_EQ(int_array_class, found_int_array_class);
304
305 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
306 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
307
308 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
309 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
310
311 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
312 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
313
Elliott Hughes418d20f2011-09-22 14:00:39 -0700314 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
315 CHECK_EQ(class_array_class, found_class_array_class);
316
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700317 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
318 CHECK_EQ(object_array_class, found_object_array_class);
319
320 // Setup the single, global copies of "interfaces" and "iftable"
321 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
322 CHECK(java_lang_Cloneable != NULL);
323 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
324 CHECK(java_io_Serializable != NULL);
325 CHECK(array_interfaces_ != NULL);
326 array_interfaces_->Set(0, java_lang_Cloneable);
327 array_interfaces_->Set(1, java_io_Serializable);
328 // We assume that Cloneable/Serializable don't have superinterfaces --
329 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700330 // supers as well.
331 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
332 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700333
Elliott Hughes418d20f2011-09-22 14:00:39 -0700334 // Sanity check Class[] and Object[]'s interfaces
335 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
336 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
338 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700339
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700340 // run Class, Field, and Method through FindSystemClass.
341 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700342 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700343 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344
345 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700346 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700347 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348
349 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700350 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700351 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700352
353 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
354 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 java_lang_ref_FinalizerReference->SetAccessFlags(
356 java_lang_ref_FinalizerReference->GetAccessFlags() |
357 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700358 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359 java_lang_ref_PhantomReference->SetAccessFlags(
360 java_lang_ref_PhantomReference->GetAccessFlags() |
361 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700362 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363 java_lang_ref_SoftReference->SetAccessFlags(
364 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700365 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366 java_lang_ref_WeakReference->SetAccessFlags(
367 java_lang_ref_WeakReference->GetAccessFlags() |
368 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700369
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700370 // Setup the ClassLoaders, adjusting the object_size_ as necessary
371 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
372 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
373 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
374 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
375
376 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
377 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
378 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
379
380 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
381 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
382 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
383 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
384
385 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700386 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
387 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700388 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700389
Brian Carlstroma663ea52011-08-19 23:33:41 -0700390 FinishInit();
391}
392
393void ClassLinker::FinishInit() {
Brian Carlstrom16192862011-09-12 17:50:06 -0700394
395 // Let the heap know some key offsets into java.lang.ref instances
396 // NB we hard code the field indexes here rather than using FindInstanceField
397 // as the types of the field can't be resolved prior to the runtime being
398 // fully initialized
399 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
400 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
401
402 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
403 CHECK(pendingNext->GetName()->Equals("pendingNext"));
404 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
405
406 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
407 CHECK(queue->GetName()->Equals("queue"));
408 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
409 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
410
411 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
412 CHECK(queueNext->GetName()->Equals("queueNext"));
413 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
414
415 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
416 CHECK(referent->GetName()->Equals("referent"));
417 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
418
419 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
420 CHECK(zombie->GetName()->Equals("zombie"));
421 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
422
423 Heap::SetReferenceOffsets(referent->GetOffset(),
424 queue->GetOffset(),
425 queueNext->GetOffset(),
426 pendingNext->GetOffset(),
427 zombie->GetOffset());
428
Brian Carlstroma663ea52011-08-19 23:33:41 -0700429 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700430 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700431 ClassRoot class_root = static_cast<ClassRoot>(i);
432 Class* klass = GetClassRoot(class_root);
433 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700434 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700435 // note SetClassRoot does additional validation.
436 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700437 }
438
439 // disable the slow paths in FindClass and CreatePrimitiveClass now
440 // that Object, Class, and Object[] are setup
441 init_done_ = true;
442}
443
Brian Carlstromc74255f2011-09-11 22:47:39 -0700444struct ClassLinker::InitFromImageCallbackState {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700445 ClassLinker* class_linker;
446
447 Class* class_roots[kClassRootsMax];
448
449 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
450 Table descriptor_to_class_root;
451
Brian Carlstroma663ea52011-08-19 23:33:41 -0700452 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
453 Set dex_caches;
454};
455
Brian Carlstromc74255f2011-09-11 22:47:39 -0700456void ClassLinker::InitFromImage(const std::vector<const DexFile*>& boot_class_path,
457 const std::vector<const DexFile*>& class_path) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700458 CHECK(!init_done_);
459
460 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
461 DCHECK(heap_bitmap != NULL);
462
Brian Carlstromc74255f2011-09-11 22:47:39 -0700463 InitFromImageCallbackState state;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700464 state.class_linker = this;
465 for (size_t i = 0; i < kClassRootsMax; i++) {
466 ClassRoot class_root = static_cast<ClassRoot>(i);
467 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
468 }
469
470 // reinit clases_ table
Brian Carlstromc74255f2011-09-11 22:47:39 -0700471 heap_bitmap->Walk(InitFromImageCallback, &state);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700472
473 // reinit class_roots_
474 Class* object_array_class = state.class_roots[kObjectArrayClass];
475 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
476 for (size_t i = 0; i < kClassRootsMax; i++) {
477 ClassRoot class_root = static_cast<ClassRoot>(i);
478 SetClassRoot(class_root, state.class_roots[class_root]);
479 }
480
Brian Carlstroma663ea52011-08-19 23:33:41 -0700481 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700482 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
483 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700484
485 // build a map from location to DexCache to match up with DexFile::GetLocation
486 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Brian Carlstromc74255f2011-09-11 22:47:39 -0700487 typedef InitFromImageCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700488 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
489 DexCache* dex_cache = *it;
490 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
491 location_to_dex_cache[location] = dex_cache;
492 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700493 CHECK_EQ(boot_class_path.size() + class_path.size(),
494 location_to_dex_cache.size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700495
496 // reinit boot_class_path with DexFile arguments and found DexCaches
497 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700498 const DexFile* dex_file = boot_class_path[i];
499 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700500 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700501 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700502 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700503 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700504
505 // register class_path with DexFile arguments and found DexCaches
506 for (size_t i = 0; i != class_path.size(); ++i) {
507 const DexFile* dex_file = class_path[i];
508 CHECK(dex_file != NULL);
509 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
510 CHECK(dex_cache != NULL) << dex_file->GetLocation();
511 RegisterDexFile(*dex_file, dex_cache);
512 }
513
Brian Carlstroma663ea52011-08-19 23:33:41 -0700514 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515 Field::SetClass(GetClassRoot(kJavaLangReflectField));
516 Method::SetClass(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700517 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
518 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
519 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
520 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
521 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
522 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
523 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
524 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700525 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700526 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700527
528 FinishInit();
529}
530
Brian Carlstrom78128a62011-09-15 17:21:19 -0700531void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700532 DCHECK(obj != NULL);
533 DCHECK(arg != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700534 InitFromImageCallbackState* state = reinterpret_cast<InitFromImageCallbackState*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700535
Brian Carlstromc74255f2011-09-11 22:47:39 -0700536 if (obj->IsString()) {
537 state->class_linker->intern_table_->RegisterStrong(obj->AsString());
538 return;
539 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700540 if (!obj->IsClass()) {
541 return;
542 }
543 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700544 // TODO: restore ClassLoader's list of DexFiles after image load
545 // CHECK(klass->GetClassLoader() == NULL);
546 const ClassLoader* class_loader = klass->GetClassLoader();
547 if (class_loader != NULL) {
548 // TODO: replace this hack with something based on command line arguments
549 Thread::Current()->SetClassLoaderOverride(class_loader);
550 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700551
552 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700553 // restore class to ClassLinker::classes_ table
554 state->class_linker->InsertClass(descriptor, klass);
555
556 // note DexCache to match with DexFile later
557 DexCache* dex_cache = klass->GetDexCache();
558 if (dex_cache != NULL) {
559 state->dex_caches.insert(dex_cache);
560 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700561 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700562 }
563
564 // check if this is a root, if so, register it
Brian Carlstromc74255f2011-09-11 22:47:39 -0700565 typedef InitFromImageCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700566 It it = state->descriptor_to_class_root.find(descriptor);
567 if (it != state->descriptor_to_class_root.end()) {
568 ClassRoot class_root = it->second;
569 state->class_roots[class_root] = klass;
570 }
571}
572
573// Keep in sync with InitCallback. Anything we visit, we need to
574// reinit references to when reinitializing a ClassLinker from a
575// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700576void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
577 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700578
579 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700580 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700581 }
582
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700583 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700584 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700585 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700586 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700587 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700588 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700589 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700590
Elliott Hughes410c0c82011-09-01 17:58:25 -0700591 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700592}
593
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700594ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700595 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700596 Field::ResetClass();
597 Method::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700598 BooleanArray::ResetArrayClass();
599 ByteArray::ResetArrayClass();
600 CharArray::ResetArrayClass();
601 DoubleArray::ResetArrayClass();
602 FloatArray::ResetArrayClass();
603 IntArray::ResetArrayClass();
604 LongArray::ResetArrayClass();
605 ShortArray::ResetArrayClass();
606 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700607 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700608}
609
610DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700611 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700612 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700613 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700614 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700615 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700616 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700617 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
618 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700619 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700620}
621
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700622CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
623 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700624}
625
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700626InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
627 DCHECK(interface->IsInterface());
628 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
629 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
630 interface_entry->SetInterface(interface);
631 return interface_entry;
632}
633
Brian Carlstrom4873d462011-08-21 15:23:39 -0700634Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
635 DCHECK_GE(class_size, sizeof(Class));
636 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700637 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
638 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700639 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700640}
641
Brian Carlstrom4873d462011-08-21 15:23:39 -0700642Class* ClassLinker::AllocClass(size_t class_size) {
643 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700644}
645
Jesse Wilson35baaab2011-08-10 16:18:03 -0400646Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700647 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700648}
649
650Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700651 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700652}
653
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700654ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
655 return ObjectArray<StackTraceElement>::Alloc(
656 GetClassRoot(kJavaLangStackTraceElementArrayClass),
657 length);
658}
659
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700660Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700661 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700662 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700663 if (class_loader != NULL) {
664 Class* klass = FindClass(descriptor, NULL);
665 if (klass != NULL) {
666 return klass;
667 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700668 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700669 }
670
Carl Shapirob5573532011-07-12 18:22:59 -0700671 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700672 DCHECK(self != NULL);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700673 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700674 // Find the class in the loaded classes table.
675 Class* klass = LookupClass(descriptor, class_loader);
676 if (klass == NULL) {
677 // Class is not yet loaded.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700678 if (descriptor[0] == '[' && descriptor[1] != '\0') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700679 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700680 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700681 const DexFile::ClassPath& class_path = ((class_loader != NULL)
682 ? ClassLoader::GetClassPath(class_loader)
683 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700684 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700685 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700686 std::string name(PrintableString(descriptor));
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700687 ThrowNoClassDefFoundError("Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700688 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700689 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700690 const DexFile& dex_file = *pair.first;
691 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700692 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700693 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700694 if (!init_done_) {
695 // finish up init of hand crafted class_roots_
696 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700697 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700698 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700699 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400700 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700701 klass = GetClassRoot(kJavaLangString);
702 } else if (descriptor == "Ljava/lang/reflect/Field;") {
703 klass = GetClassRoot(kJavaLangReflectField);
704 } else if (descriptor == "Ljava/lang/reflect/Method;") {
705 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700706 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700707 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700708 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700709 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700710 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700711 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700712 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700713 klass->SetDexCache(dex_cache);
714 LoadClass(dex_file, dex_class_def, klass, class_loader);
715 // Check for a pending exception during load
716 if (self->IsExceptionPending()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700717 return NULL;
718 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700719 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700720 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700721 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700722 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700723 if (!success) {
724 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700725 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700726 klass = LookupClass(descriptor, class_loader);
727 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700728 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700729 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700730 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700731 CHECK(!klass->IsLoaded());
732 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700733 // Loading failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700734 CHECK(self->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700735 lock.NotifyAll();
736 return NULL;
737 }
738 CHECK(klass->IsLoaded());
739 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700740 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700741 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700742 // Linking failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700743 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700744 lock.NotifyAll();
745 return NULL;
746 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700747 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700748 }
749 }
750 }
751 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700752 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700753 ObjectLock lock(klass);
754 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700755 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700756 self->ThrowNewException("Ljava/lang/ClassCircularityError;", "%s",
757 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700758 return NULL;
759 }
760 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700761 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700762 lock.Wait();
763 }
764 }
765 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700766 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700767 return NULL;
768 }
769 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700770 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700771 CHECK(!self->IsExceptionPending());
772 return klass;
773}
774
Brian Carlstrom4873d462011-08-21 15:23:39 -0700775// Precomputes size that will be needed for Class, matching LinkStaticFields
776size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
777 const DexFile::ClassDef& dex_class_def) {
778 const byte* class_data = dex_file.GetClassData(dex_class_def);
779 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
780 size_t num_static_fields = header.static_fields_size_;
781 size_t num_ref = 0;
782 size_t num_32 = 0;
783 size_t num_64 = 0;
784 if (num_static_fields != 0) {
785 uint32_t last_idx = 0;
786 for (size_t i = 0; i < num_static_fields; ++i) {
787 DexFile::Field dex_field;
788 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
789 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
790 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
791 char c = descriptor[0];
792 if (c == 'L' || c == '[') {
793 num_ref++;
794 } else if (c == 'J' || c == 'D') {
795 num_64++;
796 } else {
797 num_32++;
798 }
799 }
800 }
801
802 // start with generic class data
803 size_t size = sizeof(Class);
804 // follow with reference fields which must be contiguous at start
805 size += (num_ref * sizeof(uint32_t));
806 // if there are 64-bit fields to add, make sure they are aligned
807 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
808 if (num_32 != 0) {
809 // use an available 32-bit field for padding
810 num_32--;
811 }
812 size += sizeof(uint32_t); // either way, we are adding a word
813 DCHECK_EQ(size, RoundUp(size, 8));
814 }
815 // tack on any 64-bit fields now that alignment is assured
816 size += (num_64 * sizeof(uint64_t));
817 // tack on any remaining 32-bit fields
818 size += (num_32 * sizeof(uint32_t));
819 return size;
820}
821
Brian Carlstromf615a612011-07-23 12:50:34 -0700822void ClassLinker::LoadClass(const DexFile& dex_file,
823 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700824 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700825 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700826 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700827 CHECK(klass->GetDexCache() != NULL);
828 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700829 const byte* class_data = dex_file.GetClassData(dex_class_def);
830 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700831
Brian Carlstromf615a612011-07-23 12:50:34 -0700832 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700833 CHECK(descriptor != NULL);
834
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700835 klass->SetClass(GetClassRoot(kJavaLangClass));
836 if (klass->GetDescriptor() != NULL) {
837 DCHECK(klass->GetDescriptor()->Equals(descriptor));
838 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700839 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700840 }
841 uint32_t access_flags = dex_class_def.access_flags_;
842 // Make sure there aren't any "bonus" flags set, since we use them for runtime
843 // state.
844 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
845 klass->SetAccessFlags(access_flags);
846 klass->SetClassLoader(class_loader);
847 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
848 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700849
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700850 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700851
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700852 size_t num_static_fields = header.static_fields_size_;
853 size_t num_instance_fields = header.instance_fields_size_;
854 size_t num_direct_methods = header.direct_methods_size_;
855 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700856
Brian Carlstromc74255f2011-09-11 22:47:39 -0700857 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700858
859 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700860 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700861
862 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700863 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700864 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700865 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700866 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700867 DexFile::Field dex_field;
868 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400869 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700870 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700871 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700872 }
873 }
874
875 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700876 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700877 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700878 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700879 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700880 DexFile::Field dex_field;
881 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400882 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700883 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700884 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700885 }
886 }
887
888 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700889 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700890 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700891 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700892 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700893 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700894 DexFile::Method dex_method;
895 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700896 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700897 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700898 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700899 // TODO: register maps
900 }
901 }
902
903 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700904 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700905 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700906 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700907 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700908 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700909 DexFile::Method dex_method;
910 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700911 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700912 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700913 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700914 // TODO: register maps
915 }
916 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700917}
918
Brian Carlstromf615a612011-07-23 12:50:34 -0700919void ClassLinker::LoadInterfaces(const DexFile& dex_file,
920 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700921 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700922 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700923 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700924 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700925 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
926 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700927 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700928 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700929 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700930 }
931 }
932}
933
Brian Carlstromf615a612011-07-23 12:50:34 -0700934void ClassLinker::LoadField(const DexFile& dex_file,
935 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700936 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700937 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700938 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700939 dst->SetDeclaringClass(klass);
940 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
941 dst->SetTypeIdx(field_id.type_idx_);
942 dst->SetAccessFlags(src.access_flags_);
943
944 // In order to access primitive types using GetTypeDuringLinking we need to
945 // ensure they are resolved into the dex cache
946 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
947 if (descriptor[1] == '\0') {
948 // only the descriptors of primitive types should be 1 character long
949 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
950 DCHECK(resolved->IsPrimitive());
951 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700952}
953
Brian Carlstromf615a612011-07-23 12:50:34 -0700954void ClassLinker::LoadMethod(const DexFile& dex_file,
955 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700956 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -0700957 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700958 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700959 dst->SetDeclaringClass(klass);
960 dst->SetName(ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700961 {
962 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -0700963 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700964 dst->SetSignature(intern_table_->InternStrong(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -0700965 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700966 dst->SetProtoIdx(method_id.proto_idx_);
967 dst->SetCodeItemOffset(src.code_off_);
968 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700969 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700970 dst->SetAccessFlags(src.access_flags_);
971 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700972
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700973 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
974 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
975 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
976 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
977 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
978 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700979
Brian Carlstrom934486c2011-07-12 23:42:50 -0700980 // TODO: check for finalize method
981
Brian Carlstromf615a612011-07-23 12:50:34 -0700982 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700983 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700984 dst->SetNumRegisters(code_item->registers_size_);
985 dst->SetNumIns(code_item->ins_size_);
986 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700987 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700988 uint16_t num_args = Method::NumArgRegisters(shorty);
989 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700990 ++num_args;
991 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700992 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700993 // TODO: native methods
994 }
995}
996
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700997void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700998 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
999}
1000
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001001void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001002 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001003 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001004 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001005}
1006
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001007void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001008 RegisterDexFile(dex_file, AllocDexCache(dex_file));
1009}
1010
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001011void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -07001012 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001013 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1014 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001015 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001016 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001017}
1018
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001019const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001020 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001021 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1022 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001023 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001024 }
1025 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001026 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001027 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001028}
1029
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001030DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001031 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001032 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001033 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001034 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001035 }
1036 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001037 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001038 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001039}
1040
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001041Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1042 const char* descriptor,
1043 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001044 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001045 CHECK(primitive_class != NULL);
1046 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1047 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
1048 primitive_class->SetPrimitiveType(type);
1049 primitive_class->SetStatus(Class::kStatusInitialized);
1050 bool success = InsertClass(descriptor, primitive_class);
1051 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1052 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001053}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001054
Brian Carlstrombe977852011-07-19 14:54:54 -07001055// Create an array class (i.e. the class object for the array, not the
1056// array itself). "descriptor" looks like "[C" or "[[[[B" or
1057// "[Ljava/lang/String;".
1058//
1059// If "descriptor" refers to an array of primitives, look up the
1060// primitive type's internally-generated class object.
1061//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001062// "class_loader" is the class loader of the class that's referring to
1063// us. It's used to ensure that we're looking for the element type in
1064// the right context. It does NOT become the class loader for the
1065// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001066//
1067// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001068Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001069 const ClassLoader* class_loader) {
1070 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001071
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001072 // Identify the underlying component type
1073 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001074 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001075 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001076 return NULL;
1077 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001078
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001079 // See if the component type is already loaded. Array classes are
1080 // always associated with the class loader of their underlying
1081 // element type -- an array of Strings goes with the loader for
1082 // java/lang/String -- so we need to look for it there. (The
1083 // caller should have checked for the existence of the class
1084 // before calling here, but they did so with *their* class loader,
1085 // not the component type's loader.)
1086 //
1087 // If we find it, the caller adds "loader" to the class' initiating
1088 // loader list, which should prevent us from going through this again.
1089 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001090 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001091 // are the same, because our caller (FindClass) just did the
1092 // lookup. (Even if we get this wrong we still have correct behavior,
1093 // because we effectively do this lookup again when we add the new
1094 // class to the hash table --- necessary because of possible races with
1095 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001096 if (class_loader != component_type->GetClassLoader()) {
1097 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001098 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001099 return new_class;
1100 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001101 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001102
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001103 // Fill out the fields in the Class.
1104 //
1105 // It is possible to execute some methods against arrays, because
1106 // all arrays are subclasses of java_lang_Object_, so we need to set
1107 // up a vtable. We can just point at the one in java_lang_Object_.
1108 //
1109 // Array classes are simple enough that we don't need to do a full
1110 // link step.
1111
1112 Class* new_class = NULL;
1113 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001114 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001115 if (descriptor == "[Ljava/lang/Class;") {
1116 new_class = GetClassRoot(kClassArrayClass);
1117 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001118 new_class = GetClassRoot(kObjectArrayClass);
1119 } else if (descriptor == "[C") {
1120 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001121 } else if (descriptor == "[I") {
1122 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001123 }
1124 }
1125 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001126 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001127 if (new_class == NULL) {
1128 return NULL;
1129 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001130 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001131 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001132 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001133 if (new_class->GetDescriptor() != NULL) {
1134 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1135 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001136 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001137 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001138 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001139 new_class->SetSuperClass(java_lang_Object);
1140 new_class->SetVTable(java_lang_Object->GetVTable());
1141 new_class->SetPrimitiveType(Class::kPrimNot);
1142 new_class->SetClassLoader(component_type->GetClassLoader());
1143 new_class->SetStatus(Class::kStatusInitialized);
1144 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001145 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001146
1147
1148 // All arrays have java/lang/Cloneable and java/io/Serializable as
1149 // interfaces. We need to set that up here, so that stuff like
1150 // "instanceof" works right.
1151 //
1152 // Note: The GC could run during the call to FindSystemClass,
1153 // so we need to make sure the class object is GC-valid while we're in
1154 // there. Do this by clearing the interface list so the GC will just
1155 // think that the entries are null.
1156
1157
1158 // Use the single, global copies of "interfaces" and "iftable"
1159 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001160 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001161 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001162
1163 // Inherit access flags from the component type. Arrays can't be
1164 // used as a superclass or interface, so we want to add "final"
1165 // and remove "interface".
1166 //
1167 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001168 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001169 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001170 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1171 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001172
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001173 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001174 return new_class;
1175 }
1176 // Another thread must have loaded the class after we
1177 // started but before we finished. Abandon what we've
1178 // done.
1179 //
1180 // (Yes, this happens.)
1181
1182 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001183 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001184 DCHECK(other_class != NULL);
1185 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001186}
1187
1188Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001189 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001190 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001191 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001192 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001193 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001194 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001195 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001196 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001197 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001198 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001199 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001200 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001201 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001202 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001203 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001204 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001205 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001206 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001207 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001208 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001209 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001210 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001211 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001212}
1213
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001214bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1215 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001216 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001217 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001218 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001219}
1220
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001221Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001222 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001223 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001224 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001225 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001226 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001227 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001228 return klass;
1229 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001230 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001231 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001232}
1233
jeffhao98eacac2011-09-14 16:11:53 -07001234void ClassLinker::VerifyClass(Class* klass) {
1235 if (klass->IsVerified()) {
1236 return;
1237 }
1238
1239 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
1240
1241 klass->SetStatus(Class::kStatusVerifying);
1242 if (!DexVerifier::VerifyClass(klass)) {
1243 LOG(ERROR) << "Verification failed on class "
1244 << klass->GetDescriptor()->ToModifiedUtf8();
1245 Object* exception = Thread::Current()->GetException();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001246 // CHECK(exception != NULL) << PrettyClass(klass);
1247 if (exception == NULL) {
1248 UNIMPLEMENTED(ERROR) << "null verification exception for " << PrettyClass(klass);
1249 } else {
1250 klass->SetVerifyErrorClass(exception->GetClass());
1251 }
jeffhao98eacac2011-09-14 16:11:53 -07001252 klass->SetStatus(Class::kStatusError);
1253 return;
1254 }
1255
1256 klass->SetStatus(Class::kStatusVerified);
1257}
1258
Brian Carlstrom25c33252011-09-18 15:58:35 -07001259bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001260 CHECK(klass->GetStatus() == Class::kStatusResolved ||
jeffhao98eacac2011-09-14 16:11:53 -07001261 klass->GetStatus() == Class::kStatusVerified ||
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001262 klass->GetStatus() == Class::kStatusInitializing ||
1263 klass->GetStatus() == Class::kStatusError)
Elliott Hughes54e7df12011-09-16 11:47:04 -07001264 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001265
Carl Shapirob5573532011-07-12 18:22:59 -07001266 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001267
Brian Carlstrom25c33252011-09-18 15:58:35 -07001268 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001269 {
1270 ObjectLock lock(klass);
1271
1272 if (klass->GetStatus() < Class::kStatusVerified) {
1273 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001274 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001275 return false;
1276 }
1277
jeffhao98eacac2011-09-14 16:11:53 -07001278 VerifyClass(klass);
1279 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001280 return false;
1281 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001282 }
1283
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001284 if (klass->GetStatus() == Class::kStatusInitialized) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001285 return true;
1286 }
1287
Brian Carlstrom25c33252011-09-18 15:58:35 -07001288 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1289 if (clinit != NULL && !can_run_clinit) {
1290 // if the class has a <clinit>, don't bother going to initializing
1291 return false;
1292 }
1293
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001294 while (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001295 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001296 if (klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001297 // Yes. That's fine.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001298 return true;
1299 }
1300
1301 CHECK(!self->IsExceptionPending());
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001302 lock.Wait();
1303 CHECK(!self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001304
1305 // When we wake up, repeat the test for init-in-progress. If
1306 // there's an exception pending (only possible if
1307 // "interruptShouldThrow" was set), bail out.
1308 if (self->IsExceptionPending()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001309 self->ThrowNewException("Ljava/lang/ExceptionInInitializerError;",
1310 "Exception %s thrown while initializing class %s",
1311 PrettyTypeOf(self->GetException()).c_str(),
1312 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001313 klass->SetStatus(Class::kStatusError);
1314 return false;
1315 }
1316 if (klass->GetStatus() == Class::kStatusInitializing) {
1317 continue;
1318 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001319 DCHECK(klass->GetStatus() == Class::kStatusInitialized ||
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001320 klass->GetStatus() == Class::kStatusError);
1321 if (klass->IsErroneous()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07001322 // The caller wants an exception, but it was thrown in a
1323 // different thread. Synthesize one here.
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001324 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;",
1325 "<clinit> failed for class %s; see exception in other thread",
1326 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001327 return false;
1328 }
1329 return true; // otherwise, initialized
1330 }
1331
1332 // see if we failed previously
1333 if (klass->IsErroneous()) {
1334 // might be wise to unlock before throwing; depends on which class
1335 // it is that we have locked
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001336 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001337 return false;
1338 }
1339
1340 if (!ValidateSuperClassDescriptors(klass)) {
1341 klass->SetStatus(Class::kStatusError);
1342 return false;
1343 }
1344
Brian Carlstrom25c33252011-09-18 15:58:35 -07001345 DCHECK_LT(klass->GetStatus(), Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001346
Elliott Hughesdcc24742011-09-07 14:02:44 -07001347 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001348 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001349 }
1350
Brian Carlstrom25c33252011-09-18 15:58:35 -07001351 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001352 return false;
1353 }
1354
1355 InitializeStaticFields(klass);
1356
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001357 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001358 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001359 }
1360
1361 {
1362 ObjectLock lock(klass);
1363
1364 if (self->IsExceptionPending()) {
1365 klass->SetStatus(Class::kStatusError);
1366 } else {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001367 ++Runtime::Current()->GetStats()->class_init_count;
1368 ++self->GetStats()->class_init_count;
1369 // TODO: class_init_time_ns
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001370 klass->SetStatus(Class::kStatusInitialized);
1371 }
1372 lock.NotifyAll();
1373 }
1374
1375 return true;
1376}
1377
1378bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1379 if (klass->IsInterface()) {
1380 return true;
1381 }
1382 // begin with the methods local to the superclass
1383 if (klass->HasSuperClass() &&
1384 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1385 const Class* super = klass->GetSuperClass();
1386 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001387 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001388 if (method != super->GetVirtualMethod(i) &&
1389 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001390 ThrowLinkageError("Classes resolve differently in superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001391 return false;
1392 }
1393 }
1394 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001395 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1396 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1397 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001398 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1399 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001400 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001401 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001402 method->GetDeclaringClass())) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001403 ThrowLinkageError("Classes resolve differently in interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001404 return false;
1405 }
1406 }
1407 }
1408 }
1409 return true;
1410}
1411
1412bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001413 const Class* klass1,
1414 const Class* klass2) {
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001415 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001416 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001417 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001418 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001419 const char* descriptor = it->GetDescriptor();
1420 if (descriptor == NULL) {
1421 break;
1422 }
1423 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1424 // Found a non-primitive type.
1425 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1426 return false;
1427 }
1428 }
1429 }
1430 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001431 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001432 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1433 if (HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1434 return false;
1435 }
1436 }
1437 return true;
1438}
1439
1440// Returns true if classes referenced by the descriptor are the
1441// same classes in klass1 as they are in klass2.
1442bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001443 const Class* klass1,
1444 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001445 CHECK(descriptor != NULL);
1446 CHECK(klass1 != NULL);
1447 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001448 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001449 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001450 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001451 // TODO: found2 == NULL
1452 // TODO: lookup found1 in initiating loader list
1453 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001454 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001455 if (found1 == found2) {
1456 return true;
1457 } else {
1458 return false;
1459 }
1460 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001461 return true;
1462}
1463
Brian Carlstrom25c33252011-09-18 15:58:35 -07001464bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001465 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001466 if (!klass->IsInterface() && klass->HasSuperClass()) {
1467 Class* super_class = klass->GetSuperClass();
1468 if (super_class->GetStatus() != Class::kStatusInitialized) {
1469 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001470 Thread* self = Thread::Current();
1471 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001472 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001473 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001474 // TODO: check for a pending exception
1475 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001476 if (!can_run_clinit) {
1477 // Don't set status to error when we can't run <clinit>.
1478 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1479 klass->SetStatus(Class::kStatusVerified);
1480 return false;
1481 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001482 klass->SetStatus(Class::kStatusError);
1483 klass->NotifyAll();
1484 return false;
1485 }
1486 }
1487 }
1488 return true;
1489}
1490
Brian Carlstrom25c33252011-09-18 15:58:35 -07001491bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001492 CHECK(c != NULL);
1493 if (c->IsInitialized()) {
1494 return true;
1495 }
1496
Elliott Hughes5f791332011-09-15 17:45:30 -07001497 Thread* self = Thread::Current();
1498 c->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001499 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001500 c->MonitorExit(self);
1501 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001502}
1503
Brian Carlstromb9edb842011-08-28 16:31:06 -07001504StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1505 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001506 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1507 Class* klass = class_linker->ResolveType(type_idx, referrer);
1508 if (klass == NULL) {
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001509 CHECK(Thread::Current()->IsExceptionPending());
1510 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001511 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001512 // If we are the <clinit> of this class, just return our storage.
1513 //
1514 // Do not set the DexCache InitializedStaticStorage, since that
1515 // implies <clinit> has finished running.
1516 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1517 return klass;
1518 }
Brian Carlstrom25c33252011-09-18 15:58:35 -07001519 if (!class_linker->EnsureInitialized(klass, true)) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001520 CHECK(Thread::Current()->IsExceptionPending());
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001521 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001522 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001523 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001524 return klass;
1525}
1526
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001527void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1528 Class* c, std::map<int, Field*>& field_map) {
1529 const ClassLoader* cl = c->GetClassLoader();
1530 const byte* class_data = dex_file.GetClassData(dex_class_def);
1531 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1532 uint32_t last_idx = 0;
1533 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1534 DexFile::Field dex_field;
1535 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1536 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1537 }
1538}
1539
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001540void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001541 size_t num_static_fields = klass->NumStaticFields();
1542 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001543 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001544 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001545 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001546 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001547 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001548 return;
1549 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001550 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001551 const DexFile& dex_file = FindDexFile(dex_cache);
1552 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001553 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001554
1555 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1556 std::map<int, Field*> field_map;
1557 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1558
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001559 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001560 if (addr == NULL) {
1561 // All this class' static fields have default values.
1562 return;
1563 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001564 size_t array_size = DecodeUnsignedLeb128(&addr);
1565 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001566 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001567 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001568 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001569 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001570 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001571 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001572 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001573 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001574 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001575 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001576 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001577 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001578 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001579 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001580 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001581 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001582 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001583 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001584 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001585 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001586 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001587 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001588 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001589 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001590 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001591 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001592 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001593 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001594 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001595 break;
1596 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001597 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001598 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001599 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001600 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001601 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001602 break;
1603 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001604 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001605 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001606 }
1607}
1608
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001609bool ClassLinker::LinkClass(Class* klass) {
1610 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001611 if (!LinkSuperClass(klass)) {
1612 return false;
1613 }
1614 if (!LinkMethods(klass)) {
1615 return false;
1616 }
1617 if (!LinkInstanceFields(klass)) {
1618 return false;
1619 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001620 if (!LinkStaticFields(klass)) {
1621 return false;
1622 }
1623 CreateReferenceInstanceOffsets(klass);
1624 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001625 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1626 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001627 return true;
1628}
1629
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001630bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001631 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1632 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1633 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001634 if (super_class == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001635 ThrowVirtualMachineError("Failed to resolve superclass with type index %d for class %s",
1636 klass->GetSuperClassTypeIdx(), PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001637 return false;
1638 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001639 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001641 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1642 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
1643 Class *interface = ResolveType(dex_file, idx, klass);
1644 klass->SetInterface(i, interface);
1645 if (interface == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001646 ThrowVirtualMachineError("Failed to resolve interface with type index %d for class %s",
1647 idx, PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001648 return false;
1649 }
1650 // Verify
1651 if (!klass->CanAccess(interface)) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001652 ThrowVirtualMachineError("Inaccessible interface %s implemented by class %s",
1653 PrettyDescriptor(interface->GetDescriptor()).c_str(),
1654 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001655 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001656 }
1657 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001658 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001659 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001660 return true;
1661}
1662
1663bool ClassLinker::LinkSuperClass(Class* klass) {
1664 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001665 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001666 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001667 if (super != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001668 Thread::Current()->ThrowNewException("Ljava/lang/ClassFormatError;",
1669 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001670 return false;
1671 }
1672 // TODO: clear finalize attribute
1673 return true;
1674 }
1675 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001676 ThrowLinkageError("No superclass defined for class %s",
1677 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001678 return false;
1679 }
1680 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001681 if (super->IsFinal() || super->IsInterface()) {
1682 Thread::Current()->ThrowNewException("Ljava/lang/IncompatibleClassChangeError;",
1683 "Superclass %s is %s", PrettyDescriptor(super->GetDescriptor()).c_str(),
1684 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001685 return false;
1686 }
1687 if (!klass->CanAccess(super)) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001688 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessError;",
1689 "Superclass %s is inaccessible", PrettyDescriptor(super->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001690 return false;
1691 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001692#ifndef NDEBUG
1693 // Ensure super classes are fully resolved prior to resolving fields..
1694 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001695 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001696 super = super->GetSuperClass();
1697 }
1698#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001699 return true;
1700}
1701
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001702// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001703bool ClassLinker::LinkMethods(Class* klass) {
1704 if (klass->IsInterface()) {
1705 // No vtable.
1706 size_t count = klass->NumVirtualMethods();
1707 if (!IsUint(16, count)) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001708 ThrowVirtualMachineError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001709 return false;
1710 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001711 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001712 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001713 }
jeffhaobdb76512011-09-07 11:43:16 -07001714 // Link interface method tables
1715 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001716 } else {
1717 // Link virtual method tables
1718 LinkVirtualMethods(klass);
1719
1720 // Link interface method tables
1721 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001722 }
1723 return true;
1724}
1725
1726bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001727 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001728 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1729 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001730 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001731 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001732 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001733 // See if any of our virtual methods override the superclass.
1734 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001735 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001736 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001737 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001738 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001739 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001740 // Verify
1741 if (super_method->IsFinal()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001742 ThrowVirtualMachineError("Method %s.%s overrides final method in class %s",
1743 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1744 local_method->GetName()->ToModifiedUtf8().c_str(),
1745 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001746 return false;
1747 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001748 vtable->Set(j, local_method);
1749 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001750 break;
1751 }
1752 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001753 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001754 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001755 vtable->Set(actual_count, local_method);
1756 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001757 actual_count += 1;
1758 }
1759 }
1760 if (!IsUint(16, actual_count)) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001761 ThrowVirtualMachineError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001762 return false;
1763 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001764 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001765 CHECK_LE(actual_count, max_count);
1766 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001767 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001768 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001769 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001770 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001771 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001772 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001773 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001774 ThrowVirtualMachineError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001775 return false;
1776 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001777 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001778 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001779 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1780 vtable->Set(i, virtual_method);
1781 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001782 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001783 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001784 }
1785 return true;
1786}
1787
1788bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001789 int miranda_count = 0;
1790 int miranda_alloc = 0;
1791 size_t super_ifcount;
1792 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001793 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001794 } else {
1795 super_ifcount = 0;
1796 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001797 size_t ifcount = super_ifcount;
1798 ifcount += klass->NumInterfaces();
1799 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001800 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001801 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001802 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001803 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001804 // DCHECK(klass->GetIfTableCount() == 0);
1805 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001806 return true;
1807 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001808 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001809 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001810 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1811 for (size_t i = 0; i < super_ifcount; i++) {
1812 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1813 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001814 }
1815 // Flatten the interface inheritance hierarchy.
1816 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001817 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001818 Class* interface = klass->GetInterface(i);
1819 DCHECK(interface != NULL);
1820 if (!interface->IsInterface()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001821 Thread::Current()->ThrowNewException("Ljava/lang/IncompatibleClassChangeError;",
1822 "Class %s implements non-interface class %s",
1823 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1824 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001825 return false;
1826 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001827 iftable->Set(idx++, AllocInterfaceEntry(interface));
1828 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1829 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001830 }
1831 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001832 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001833 CHECK_EQ(idx, ifcount);
Brian Carlstrom86927212011-09-15 11:31:11 -07001834 if (klass->IsInterface()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001835 return true;
1836 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001837 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001838 for (size_t i = 0; i < ifcount; ++i) {
1839 InterfaceEntry* interface_entry = iftable->Get(i);
1840 Class* interface = interface_entry->GetInterface();
1841 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1842 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001843 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001844 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1845 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001846 int32_t k;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001847 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1848 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001849 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1850 if (!vtable_method->IsPublic()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001851 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessError;",
1852 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001853 return false;
1854 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001855 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001856 break;
1857 }
1858 }
1859 if (k < 0) {
1860 if (miranda_count == miranda_alloc) {
1861 miranda_alloc += 8;
1862 if (miranda_list.empty()) {
1863 miranda_list.resize(miranda_alloc);
1864 } else {
1865 miranda_list.resize(miranda_alloc);
1866 }
1867 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001868 Method* miranda_method = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001869 int mir;
1870 for (mir = 0; mir < miranda_count; mir++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001871 miranda_method = miranda_list[mir];
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001872 if (miranda_method->HasSameNameAndDescriptor(interface_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001873 break;
1874 }
1875 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001876 // point the interface table at a phantom slot
1877 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001878 if (mir == miranda_count) {
1879 miranda_list[miranda_count++] = interface_method;
1880 }
1881 }
1882 }
1883 }
1884 if (miranda_count != 0) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001885 int old_method_count = klass->NumVirtualMethods();
1886 int new_method_count = old_method_count + miranda_count;
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001887 klass->SetVirtualMethods((old_method_count == 0)
1888 ? AllocObjectArray<Method>(new_method_count)
1889 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001890
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001891 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1892 CHECK(vtable != NULL);
1893 int old_vtable_count = vtable->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001894 int new_vtable_count = old_vtable_count + miranda_count;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001895 vtable = vtable->CopyOf(new_vtable_count);
Brian Carlstroma7f4f482011-07-17 17:01:34 -07001896 for (int i = 0; i < miranda_count; i++) {
Brian Carlstroma0808032011-07-18 00:39:23 -07001897 Method* meth = AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001898 // TODO: this shouldn't be a memcpy
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001899 memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001900 meth->SetDeclaringClass(klass);
1901 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1902 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001903 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001904 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001905 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001906 // TODO: do not assign to the vtable field until it is fully constructed.
1907 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001908 }
1909 return true;
1910}
1911
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001912bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001913 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001914 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001915}
1916
1917bool ClassLinker::LinkStaticFields(Class* klass) {
1918 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001919 size_t allocated_class_size = klass->GetClassSize();
1920 bool success = LinkFields(klass, false);
1921 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001922 return success;
1923}
1924
Brian Carlstromdbc05252011-09-09 01:59:59 -07001925struct LinkFieldsComparator {
1926 bool operator()(const Field* field1, const Field* field2){
1927
1928 // First come reference fields, then 64-bit, and finally 32-bit
1929 const Class* type1 = field1->GetTypeDuringLinking();
1930 const Class* type2 = field2->GetTypeDuringLinking();
1931 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
1932 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
1933 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
1934 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
1935 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
1936 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
1937 if (order1 != order2) {
1938 return order1 < order2;
1939 }
1940
1941 // same basic group? then sort by string.
1942 std::string name1 = field1->GetName()->ToModifiedUtf8();
1943 std::string name2 = field2->GetName()->ToModifiedUtf8();
1944 return name1 < name2;
1945 }
1946};
1947
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001948bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001949 size_t num_fields =
1950 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
1951
1952 ObjectArray<Field>* fields =
1953 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001954
1955 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07001956 size_t size;
1957 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001958 if (instance) {
1959 Class* super_class = klass->GetSuperClass();
1960 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001961 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001962 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001963 }
1964 size = field_offset.Uint32Value();
1965 } else {
1966 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07001967 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001968 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001969
Brian Carlstromdbc05252011-09-09 01:59:59 -07001970 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001971
Brian Carlstromdbc05252011-09-09 01:59:59 -07001972 // we want a relatively stable order so that adding new fields
1973 // minimizes distruption of C++ version such as Class and Method.
1974 std::deque<Field*> grouped_and_sorted_fields;
1975 for (size_t i = 0; i < num_fields; i++) {
1976 grouped_and_sorted_fields.push_back(fields->Get(i));
1977 }
1978 std::sort(grouped_and_sorted_fields.begin(),
1979 grouped_and_sorted_fields.end(),
1980 LinkFieldsComparator());
1981
1982 // References should be at the front.
1983 size_t current_field = 0;
1984 size_t num_reference_fields = 0;
1985 for (; current_field < num_fields; current_field++) {
1986 Field* field = grouped_and_sorted_fields.front();
1987 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001988 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07001989 bool isPrimitive = type != NULL && type->IsPrimitive();
1990 if (isPrimitive) {
1991 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001992 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07001993 grouped_and_sorted_fields.pop_front();
1994 num_reference_fields++;
1995 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001996 field->SetOffset(field_offset);
1997 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001998 }
1999
2000 // Now we want to pack all of the double-wide fields together. If
2001 // we're not aligned, though, we want to shuffle one 32-bit field
2002 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002003 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2004 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2005 Field* field = grouped_and_sorted_fields[i];
2006 const Class* type = field->GetTypeDuringLinking();
2007 CHECK(type != NULL); // should only be working on primitive types
2008 DCHECK(type->IsPrimitive());
2009 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2010 continue;
2011 }
2012 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002013 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002014 // drop the consumed field
2015 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2016 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002017 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002018 // whether we found a 32-bit field for padding or not, we advance
2019 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 }
2021
2022 // Alignment is good, shuffle any double-wide fields forward, and
2023 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002024 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2025 while (!grouped_and_sorted_fields.empty()) {
2026 Field* field = grouped_and_sorted_fields.front();
2027 grouped_and_sorted_fields.pop_front();
2028 const Class* type = field->GetTypeDuringLinking();
2029 CHECK(type != NULL); // should only be working on primitive types
2030 DCHECK(type->IsPrimitive());
2031 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002032 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002033 field_offset = MemberOffset(field_offset.Uint32Value() +
2034 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2035 ? sizeof(uint64_t)
2036 : sizeof(uint32_t)));
2037 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002038 }
2039
2040#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002041 // Make sure that all reference fields appear before
2042 // non-reference fields, and all double-wide fields are aligned.
2043 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002044 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002045 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002046 if (false) { // enable to debug field layout
Brian Carlstrom845490b2011-09-19 15:56:53 -07002047 LOG(INFO) << "LinkFields: " << (instance ? "instance" : "static")
Brian Carlstromdbc05252011-09-09 01:59:59 -07002048 << " class=" << klass->GetDescriptor()->ToModifiedUtf8()
2049 << " field=" << field->GetName()->ToModifiedUtf8()
2050 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2051 }
2052 const Class* type = field->GetTypeDuringLinking();
2053 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002054 if (!seen_non_ref) {
2055 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002056 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002057 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002058 } else {
2059 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002060 }
2061 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002062 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002063 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002064 }
2065#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002066 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002067 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07002068 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002069 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002070 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002071 klass->SetObjectSize(size);
2072 }
2073 } else {
2074 klass->SetNumReferenceStaticFields(num_reference_fields);
2075 klass->SetClassSize(size);
2076 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002077 return true;
2078}
2079
2080// Set the bitmap of reference offsets, refOffsets, from the ifields
2081// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002082void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002083 uint32_t reference_offsets = 0;
2084 Class* super_class = klass->GetSuperClass();
2085 if (super_class != NULL) {
2086 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002087 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002088 if (reference_offsets == CLASS_WALK_SUPER) {
2089 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002090 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002091 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002092 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002093 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002094}
2095
2096void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002097 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002098}
2099
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002100void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2101 uint32_t reference_offsets) {
2102 size_t num_reference_fields =
2103 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2104 : klass->NumReferenceStaticFieldsDuringLinking();
2105 const ObjectArray<Field>* fields =
2106 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002107 // All of the fields that contain object references are guaranteed
2108 // to be at the beginning of the fields list.
2109 for (size_t i = 0; i < num_reference_fields; ++i) {
2110 // Note that byte_offset is the offset from the beginning of
2111 // object, not the offset into instance data
2112 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002113 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002114 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2115 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2116 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002117 CHECK_NE(new_bit, 0U);
2118 reference_offsets |= new_bit;
2119 } else {
2120 reference_offsets = CLASS_WALK_SUPER;
2121 break;
2122 }
2123 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002124 // Update fields in klass
2125 if (instance) {
2126 klass->SetReferenceInstanceOffsets(reference_offsets);
2127 } else {
2128 klass->SetReferenceStaticOffsets(reference_offsets);
2129 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002130}
2131
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002132String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002133 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002134 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002135 if (resolved != NULL) {
2136 return resolved;
2137 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002138 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2139 int32_t utf16_length = dex_file.GetStringLength(string_id);
2140 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002141 // TODO: remote the const_cast below
2142 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002143 dex_cache->SetResolvedString(string_idx, string);
2144 return string;
2145}
2146
2147Class* ClassLinker::ResolveType(const DexFile& dex_file,
2148 uint32_t type_idx,
2149 DexCache* dex_cache,
2150 const ClassLoader* class_loader) {
2151 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002152 if (resolved == NULL) {
2153 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2154 if (descriptor[1] == '\0') {
2155 // only the descriptors of primitive types should be 1 character long
2156 resolved = FindPrimitiveClass(descriptor[0]);
2157 } else {
2158 resolved = FindClass(descriptor, class_loader);
2159 }
2160 if (resolved != NULL) {
2161 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2162 if (dex_cache != check->GetDexCache()) {
2163 if (check->GetClassLoader() != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002164 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessError;",
2165 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002166 resolved = NULL;
2167 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002168 }
2169 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002170 if (resolved != NULL) {
2171 dex_cache->SetResolvedType(type_idx, resolved);
2172 } else {
2173 DCHECK(Thread::Current()->IsExceptionPending());
2174 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002175 }
2176 return resolved;
2177}
2178
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002179Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2180 uint32_t method_idx,
2181 DexCache* dex_cache,
2182 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002183 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002184 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2185 if (resolved != NULL) {
2186 return resolved;
2187 }
2188 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2189 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2190 if (klass == NULL) {
2191 return NULL;
2192 }
2193
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002194 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002195 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002196 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002197 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002198 } else if (klass->IsInterface()) {
2199 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002200 } else {
2201 resolved = klass->FindVirtualMethod(name, signature);
2202 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002203 if (resolved != NULL) {
2204 dex_cache->SetResolvedMethod(method_idx, resolved);
2205 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002206 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002207 }
2208 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002209}
2210
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002211Field* ClassLinker::ResolveField(const DexFile& dex_file,
2212 uint32_t field_idx,
2213 DexCache* dex_cache,
2214 const ClassLoader* class_loader,
2215 bool is_static) {
2216 Field* resolved = dex_cache->GetResolvedField(field_idx);
2217 if (resolved != NULL) {
2218 return resolved;
2219 }
2220 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2221 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2222 if (klass == NULL) {
2223 return NULL;
2224 }
2225
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002226 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002227 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
2228 // TODO: LinkageError?
2229 CHECK(field_type != NULL);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002230 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002231 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002232 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002233 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002234 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002235 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002236 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002237 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002238 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002239 }
2240 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002241}
2242
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002243void ClassLinker::DumpAllClasses(int flags) const {
2244 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2245 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2246 std::vector<Class*> all_classes;
2247 {
2248 MutexLock mu(lock_);
2249 typedef Table::const_iterator It; // TODO: C++0x auto
2250 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2251 all_classes.push_back(it->second);
2252 }
2253 }
2254
2255 for (size_t i = 0; i < all_classes.size(); ++i) {
2256 all_classes[i]->DumpClass(std::cerr, flags);
2257 }
2258}
2259
Elliott Hughese27955c2011-08-26 15:21:24 -07002260size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002261 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002262 return classes_.size();
2263}
2264
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265} // namespace art