blob: a8703dab91f76512a4d1b552316a715bf2d25418 [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
Elliott Hughese555dc02011-09-25 10:46:35 -070038void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
39void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070040 va_list args;
41 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070042 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070043 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
Elliott Hughescc5f9a92011-09-28 19:17:29 -070054void ThrowNoSuchMethodError(const char* kind,
55 Class* c, const StringPiece& name, const StringPiece& signature) {
56 DexCache* dex_cache = c->GetDexCache();
57 std::stringstream msg;
58 msg << "no " << kind << " method " << name << "." << signature
59 << " in class " << c->GetDescriptor()->ToModifiedUtf8()
60 << " or its superclasses";
61 if (dex_cache) {
62 msg << " (defined in " << dex_cache->GetLocation()->ToModifiedUtf8() << ")";
63 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070064 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070065}
66
Elliott Hughes4a2b4172011-09-20 17:08:25 -070067void ThrowEarlierClassFailure(Class* c) {
68 /*
69 * The class failed to initialize on a previous attempt, so we want to throw
70 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
71 * failed in verification, in which case v2 5.4.1 says we need to re-throw
72 * the previous error.
73 */
74 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
75
76 if (c->GetVerifyErrorClass() != NULL) {
77 // TODO: change the verifier to store an _instance_, with a useful detail message?
78 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070079 Thread::Current()->ThrowNewException(error_descriptor.c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -070080 PrettyDescriptor(c->GetDescriptor()).c_str());
81 } else {
82 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
83 }
84}
85
86}
87
Elliott Hughes418d20f2011-09-22 14:00:39 -070088const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -070089 "Ljava/lang/Class;",
90 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -070091 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070092 "[Ljava/lang/Object;",
93 "Ljava/lang/String;",
Elliott Hughes80609252011-09-23 17:24:51 -070094 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070095 "Ljava/lang/reflect/Field;",
96 "Ljava/lang/reflect/Method;",
97 "Ljava/lang/ClassLoader;",
98 "Ldalvik/system/BaseDexClassLoader;",
99 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700100 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700101 "Z",
102 "B",
103 "C",
104 "D",
105 "F",
106 "I",
107 "J",
108 "S",
109 "V",
110 "[Z",
111 "[B",
112 "[C",
113 "[D",
114 "[F",
115 "[I",
116 "[J",
117 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700118 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700119};
120
Elliott Hughes5f791332011-09-15 17:45:30 -0700121class ObjectLock {
122 public:
123 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
124 CHECK(object != NULL);
125 obj_->MonitorEnter(self_);
126 }
127
128 ~ObjectLock() {
129 obj_->MonitorExit(self_);
130 }
131
132 void Wait() {
133 return Monitor::Wait(self_, obj_, 0, 0, false);
134 }
135
136 void Notify() {
137 obj_->Notify();
138 }
139
140 void NotifyAll() {
141 obj_->NotifyAll();
142 }
143
144 private:
145 Thread* self_;
146 Object* obj_;
147 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
148};
149
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700150ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path,
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700151 const std::vector<const DexFile*>& class_path,
Brian Carlstromc74255f2011-09-11 22:47:39 -0700152 InternTable* intern_table, bool image) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700153 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700154 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700155 if (image) {
156 class_linker->InitFromImage(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700157 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700158 class_linker->Init(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700159 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700160 // TODO: check for failure during initialization
161 return class_linker.release();
162}
163
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700164ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700165 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700166 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700167 array_interfaces_(NULL),
168 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700169 init_done_(false),
170 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700171 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700172}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700173
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700174void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
175 const std::vector<const DexFile*>& class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700176 const Runtime* runtime = Runtime::Current();
177 if (runtime->IsVerboseStartup()) {
178 LOG(INFO) << "ClassLinker::InitFrom entering";
179 }
180
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700181 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700182
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700183 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700184 Class* java_lang_Class = down_cast<Class*>(
185 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700186 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700187 java_lang_Class->SetClass(java_lang_Class);
188 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700189 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700190
Elliott Hughes418d20f2011-09-22 14:00:39 -0700191 // Class[] is used for reflection support.
192 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
193 class_array_class->SetComponentType(java_lang_Class);
194
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700195 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700196 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700197 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700198 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199 java_lang_Class->SetSuperClass(java_lang_Object);
200 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700201
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700202 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700203 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700204 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700205
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700206 // Setup the char class to be used for char[]
207 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
208
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700209 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700210 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700211 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700212 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700213
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700214 // Setup String
215 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
216 String::SetClass(java_lang_String);
217 java_lang_String->SetObjectSize(sizeof(String));
218 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400219
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700220 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700221 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
222 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700223 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700224 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
225 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
226 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700227
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700228 // Create storage for root classes, save away our work so far (requires
229 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700230 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700231 SetClassRoot(kJavaLangClass, java_lang_Class);
232 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700233 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700234 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700235 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700236 SetClassRoot(kJavaLangString, java_lang_String);
237
238 // Setup the primitive type classes.
239 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
240 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700241 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
242 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
243 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
244 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
245 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
246 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
247
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700248 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700249 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700250 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700251
252 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
253 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700254 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700255 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
256 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700257 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700259 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700260
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700261 // setup boot_class_path_ and register class_path now that we can
262 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700263 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700264 const DexFile* dex_file = boot_class_path[i];
265 CHECK(dex_file != NULL);
266 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700267 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700268 for (size_t i = 0; i != class_path.size(); ++i) {
269 const DexFile* dex_file = class_path[i];
270 CHECK(dex_file != NULL);
271 RegisterDexFile(*dex_file);
272 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700273
Elliott Hughes80609252011-09-23 17:24:51 -0700274 // Constructor, Field, and Method are necessary so that FindClass can link members
275 Class* java_lang_reflect_Constructor = AllocClass(java_lang_Class, sizeof(MethodClass));
276 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
277 CHECK(java_lang_reflect_Constructor != NULL);
278 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
279 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor);
280 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
281
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700282 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
283 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700284 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
286 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
287 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
288 Field::SetClass(java_lang_reflect_Field);
289
290 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Elliott Hughes80609252011-09-23 17:24:51 -0700291 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 CHECK(java_lang_reflect_Method != NULL);
293 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
294 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
295 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Elliott Hughes80609252011-09-23 17:24:51 -0700296 Method::SetClasses(java_lang_reflect_Constructor, java_lang_reflect_Method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297
298 // now we can use FindSystemClass
299
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700300 // run char class through InitializePrimitiveClass to finish init
301 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
302 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
303
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700304 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305 java_lang_Object->SetStatus(Class::kStatusNotReady);
306 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
307 CHECK_EQ(java_lang_Object, Object_class);
308 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
309 java_lang_String->SetStatus(Class::kStatusNotReady);
310 Class* String_class = FindSystemClass("Ljava/lang/String;");
311 CHECK_EQ(java_lang_String, String_class);
312 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
313
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700314 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
316 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
317
318 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
319 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
320
321 Class* found_char_array_class = FindSystemClass("[C");
322 CHECK_EQ(char_array_class, found_char_array_class);
323
324 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
325 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
326
327 Class* found_int_array_class = FindSystemClass("[I");
328 CHECK_EQ(int_array_class, found_int_array_class);
329
330 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
331 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
332
333 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
334 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
335
336 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
337 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
338
Elliott Hughes418d20f2011-09-22 14:00:39 -0700339 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
340 CHECK_EQ(class_array_class, found_class_array_class);
341
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
343 CHECK_EQ(object_array_class, found_object_array_class);
344
345 // Setup the single, global copies of "interfaces" and "iftable"
346 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
347 CHECK(java_lang_Cloneable != NULL);
348 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
349 CHECK(java_io_Serializable != NULL);
350 CHECK(array_interfaces_ != NULL);
351 array_interfaces_->Set(0, java_lang_Cloneable);
352 array_interfaces_->Set(1, java_io_Serializable);
353 // We assume that Cloneable/Serializable don't have superinterfaces --
354 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700355 // supers as well.
356 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
357 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358
Elliott Hughes418d20f2011-09-22 14:00:39 -0700359 // Sanity check Class[] and Object[]'s interfaces
360 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
361 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
363 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700364
Elliott Hughes80609252011-09-23 17:24:51 -0700365 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700366 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700367 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700368 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700369
Elliott Hughes80609252011-09-23 17:24:51 -0700370 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
371 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
372 CHECK_EQ(java_lang_reflect_Constructor, Constructor_class);
373
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700375 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700376 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377
378 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700379 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700380 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700381
382 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
383 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384 java_lang_ref_FinalizerReference->SetAccessFlags(
385 java_lang_ref_FinalizerReference->GetAccessFlags() |
386 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700387 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700388 java_lang_ref_PhantomReference->SetAccessFlags(
389 java_lang_ref_PhantomReference->GetAccessFlags() |
390 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700391 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 java_lang_ref_SoftReference->SetAccessFlags(
393 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700394 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700395 java_lang_ref_WeakReference->SetAccessFlags(
396 java_lang_ref_WeakReference->GetAccessFlags() |
397 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700398
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700399 // Setup the ClassLoaders, adjusting the object_size_ as necessary
400 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
401 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
402 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
403 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
404
405 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
406 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
407 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
408
409 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
410 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
411 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
412 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
413
414 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700415 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
416 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700417 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700418
Brian Carlstroma663ea52011-08-19 23:33:41 -0700419 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700420
421 if (runtime->IsVerboseStartup()) {
422 LOG(INFO) << "ClassLinker::InitFrom exiting";
423 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700424}
425
426void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700427 const Runtime* runtime = Runtime::Current();
428 if (runtime->IsVerboseStartup()) {
429 LOG(INFO) << "ClassLinker::FinishInit entering";
430 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700431
432 // Let the heap know some key offsets into java.lang.ref instances
433 // NB we hard code the field indexes here rather than using FindInstanceField
434 // as the types of the field can't be resolved prior to the runtime being
435 // fully initialized
436 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
437 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
438
439 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
440 CHECK(pendingNext->GetName()->Equals("pendingNext"));
441 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
442
443 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
444 CHECK(queue->GetName()->Equals("queue"));
445 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
446 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
447
448 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
449 CHECK(queueNext->GetName()->Equals("queueNext"));
450 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
451
452 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
453 CHECK(referent->GetName()->Equals("referent"));
454 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
455
456 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
457 CHECK(zombie->GetName()->Equals("zombie"));
458 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
459
460 Heap::SetReferenceOffsets(referent->GetOffset(),
461 queue->GetOffset(),
462 queueNext->GetOffset(),
463 pendingNext->GetOffset(),
464 zombie->GetOffset());
465
Brian Carlstroma663ea52011-08-19 23:33:41 -0700466 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700467 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700468 ClassRoot class_root = static_cast<ClassRoot>(i);
469 Class* klass = GetClassRoot(class_root);
470 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700471 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700472 // note SetClassRoot does additional validation.
473 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700474 }
475
476 // disable the slow paths in FindClass and CreatePrimitiveClass now
477 // that Object, Class, and Object[] are setup
478 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700479
480 if (runtime->IsVerboseStartup()) {
481 LOG(INFO) << "ClassLinker::FinishInit exiting";
482 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700483}
484
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700485void ClassLinker::RunRootClinits() {
486 Thread* self = Thread::Current();
487 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
488 Class* c = GetClassRoot(ClassRoot(i));
489 if (!c->IsArrayClass() && !c->IsPrimitive()) {
490 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
491 CHECK(!self->IsExceptionPending());
492 }
493 }
494}
495
Brian Carlstromc74255f2011-09-11 22:47:39 -0700496struct ClassLinker::InitFromImageCallbackState {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700497 ClassLinker* class_linker;
498
499 Class* class_roots[kClassRootsMax];
500
501 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
502 Table descriptor_to_class_root;
503
Brian Carlstroma663ea52011-08-19 23:33:41 -0700504 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
505 Set dex_caches;
506};
507
Brian Carlstromc74255f2011-09-11 22:47:39 -0700508void ClassLinker::InitFromImage(const std::vector<const DexFile*>& boot_class_path,
509 const std::vector<const DexFile*>& class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700510 const Runtime* runtime = Runtime::Current();
511 if (runtime->IsVerboseStartup()) {
512 LOG(INFO) << "ClassLinker::InitFromImage entering";
513 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700514 CHECK(!init_done_);
515
516 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
517 DCHECK(heap_bitmap != NULL);
518
Brian Carlstromc74255f2011-09-11 22:47:39 -0700519 InitFromImageCallbackState state;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700520 state.class_linker = this;
521 for (size_t i = 0; i < kClassRootsMax; i++) {
522 ClassRoot class_root = static_cast<ClassRoot>(i);
523 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
524 }
525
526 // reinit clases_ table
Brian Carlstromc74255f2011-09-11 22:47:39 -0700527 heap_bitmap->Walk(InitFromImageCallback, &state);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700528
529 // reinit class_roots_
530 Class* object_array_class = state.class_roots[kObjectArrayClass];
531 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
532 for (size_t i = 0; i < kClassRootsMax; i++) {
533 ClassRoot class_root = static_cast<ClassRoot>(i);
534 SetClassRoot(class_root, state.class_roots[class_root]);
535 }
536
Brian Carlstroma663ea52011-08-19 23:33:41 -0700537 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700538 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
539 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700540
541 // build a map from location to DexCache to match up with DexFile::GetLocation
542 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Brian Carlstromc74255f2011-09-11 22:47:39 -0700543 typedef InitFromImageCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700544 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
545 DexCache* dex_cache = *it;
546 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
547 location_to_dex_cache[location] = dex_cache;
548 }
Elliott Hughes14134a12011-09-30 16:55:51 -0700549 CHECK(boot_class_path.size() + class_path.size() == location_to_dex_cache.size())
550 << "(" << boot_class_path.size() << " + " << class_path.size()
551 << " != " << location_to_dex_cache.size() << ")";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700552
553 // reinit boot_class_path with DexFile arguments and found DexCaches
554 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700555 const DexFile* dex_file = boot_class_path[i];
556 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700557 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700558 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700559 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700560 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700561
562 // register class_path with DexFile arguments and found DexCaches
563 for (size_t i = 0; i != class_path.size(); ++i) {
564 const DexFile* dex_file = class_path[i];
565 CHECK(dex_file != NULL);
566 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
567 CHECK(dex_cache != NULL) << dex_file->GetLocation();
568 RegisterDexFile(*dex_file, dex_cache);
569 }
570
Brian Carlstroma663ea52011-08-19 23:33:41 -0700571 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700572 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700573 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700574 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
575 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
576 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
577 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
578 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
579 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
580 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
581 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700582 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700583 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700584
585 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700586
587 if (runtime->IsVerboseStartup()) {
588 LOG(INFO) << "ClassLinker::InitFromImage exiting";
589 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700590}
591
Brian Carlstrom78128a62011-09-15 17:21:19 -0700592void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700593 DCHECK(obj != NULL);
594 DCHECK(arg != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700595 InitFromImageCallbackState* state = reinterpret_cast<InitFromImageCallbackState*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700596
Brian Carlstromc74255f2011-09-11 22:47:39 -0700597 if (obj->IsString()) {
598 state->class_linker->intern_table_->RegisterStrong(obj->AsString());
599 return;
600 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700601 if (!obj->IsClass()) {
602 return;
603 }
604 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700605 // TODO: restore ClassLoader's list of DexFiles after image load
606 // CHECK(klass->GetClassLoader() == NULL);
607 const ClassLoader* class_loader = klass->GetClassLoader();
608 if (class_loader != NULL) {
609 // TODO: replace this hack with something based on command line arguments
610 Thread::Current()->SetClassLoaderOverride(class_loader);
611 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700612
613 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700614 // restore class to ClassLinker::classes_ table
615 state->class_linker->InsertClass(descriptor, klass);
616
617 // note DexCache to match with DexFile later
618 DexCache* dex_cache = klass->GetDexCache();
619 if (dex_cache != NULL) {
620 state->dex_caches.insert(dex_cache);
621 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700622 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700623 }
624
625 // check if this is a root, if so, register it
Brian Carlstromc74255f2011-09-11 22:47:39 -0700626 typedef InitFromImageCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700627 It it = state->descriptor_to_class_root.find(descriptor);
628 if (it != state->descriptor_to_class_root.end()) {
629 ClassRoot class_root = it->second;
630 state->class_roots[class_root] = klass;
631 }
632}
633
634// Keep in sync with InitCallback. Anything we visit, we need to
635// reinit references to when reinitializing a ClassLinker from a
636// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700637void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
638 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700639
640 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700641 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700642 }
643
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700644 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700645 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700646 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700647 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700648 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700649 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700650 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700651
Elliott Hughes410c0c82011-09-01 17:58:25 -0700652 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700653}
654
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700655ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700656 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700657 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700658 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700659 BooleanArray::ResetArrayClass();
660 ByteArray::ResetArrayClass();
661 CharArray::ResetArrayClass();
662 DoubleArray::ResetArrayClass();
663 FloatArray::ResetArrayClass();
664 IntArray::ResetArrayClass();
665 LongArray::ResetArrayClass();
666 ShortArray::ResetArrayClass();
667 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700668 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700669}
670
671DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700672 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700673 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700674 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700675 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700676 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700677 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700678 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
679 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700680 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700681}
682
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700683CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
684 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700685}
686
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700687InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
688 DCHECK(interface->IsInterface());
689 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
690 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
691 interface_entry->SetInterface(interface);
692 return interface_entry;
693}
694
Brian Carlstrom4873d462011-08-21 15:23:39 -0700695Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
696 DCHECK_GE(class_size, sizeof(Class));
697 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700698 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
699 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700700 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700701}
702
Brian Carlstrom4873d462011-08-21 15:23:39 -0700703Class* ClassLinker::AllocClass(size_t class_size) {
704 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700705}
706
Jesse Wilson35baaab2011-08-10 16:18:03 -0400707Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700708 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700709}
710
711Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700712 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700713}
714
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700715ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
716 return ObjectArray<StackTraceElement>::Alloc(
717 GetClassRoot(kJavaLangStackTraceElementArrayClass),
718 length);
719}
720
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700721Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700722 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700723 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700724 if (class_loader != NULL) {
725 Class* klass = FindClass(descriptor, NULL);
726 if (klass != NULL) {
727 return klass;
728 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700729 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700730 }
731
Carl Shapirob5573532011-07-12 18:22:59 -0700732 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700733 DCHECK(self != NULL);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700734 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700735 // Find the class in the loaded classes table.
736 Class* klass = LookupClass(descriptor, class_loader);
737 if (klass == NULL) {
738 // Class is not yet loaded.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700739 if (descriptor[0] == '[' && descriptor[1] != '\0') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700740 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700741 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700742 const DexFile::ClassPath& class_path = ((class_loader != NULL)
743 ? ClassLoader::GetClassPath(class_loader)
744 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700745 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700746 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700747 std::string name(PrintableString(descriptor));
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700748 ThrowNoClassDefFoundError("Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700749 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700750 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700751 const DexFile& dex_file = *pair.first;
752 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700753 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700754 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700755 if (!init_done_) {
756 // finish up init of hand crafted class_roots_
757 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700758 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700759 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700760 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400761 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700762 klass = GetClassRoot(kJavaLangString);
Elliott Hughes80609252011-09-23 17:24:51 -0700763 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
764 klass = GetClassRoot(kJavaLangReflectConstructor);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700765 } else if (descriptor == "Ljava/lang/reflect/Field;") {
766 klass = GetClassRoot(kJavaLangReflectField);
767 } else if (descriptor == "Ljava/lang/reflect/Method;") {
768 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700769 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700770 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700771 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700772 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700773 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700774 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700775 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700776 klass->SetDexCache(dex_cache);
777 LoadClass(dex_file, dex_class_def, klass, class_loader);
778 // Check for a pending exception during load
779 if (self->IsExceptionPending()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700780 return NULL;
781 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700782 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700783 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700784 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700785 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700786 if (!success) {
787 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700788 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700789 klass = LookupClass(descriptor, class_loader);
790 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700791 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700792 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700793 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700794 CHECK(!klass->IsLoaded());
795 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700796 // Loading failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700797 CHECK(self->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700798 lock.NotifyAll();
799 return NULL;
800 }
801 CHECK(klass->IsLoaded());
802 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700803 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700804 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700805 // Linking failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700806 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700807 lock.NotifyAll();
808 return NULL;
809 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700810 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700811 }
812 }
813 }
814 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700815 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700816 ObjectLock lock(klass);
817 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700818 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700819 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700820 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700821 return NULL;
822 }
823 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700824 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700825 lock.Wait();
826 }
827 }
828 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700829 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700830 return NULL;
831 }
832 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700833 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700834 CHECK(!self->IsExceptionPending());
835 return klass;
836}
837
Brian Carlstrom4873d462011-08-21 15:23:39 -0700838// Precomputes size that will be needed for Class, matching LinkStaticFields
839size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
840 const DexFile::ClassDef& dex_class_def) {
841 const byte* class_data = dex_file.GetClassData(dex_class_def);
842 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
843 size_t num_static_fields = header.static_fields_size_;
844 size_t num_ref = 0;
845 size_t num_32 = 0;
846 size_t num_64 = 0;
847 if (num_static_fields != 0) {
848 uint32_t last_idx = 0;
849 for (size_t i = 0; i < num_static_fields; ++i) {
850 DexFile::Field dex_field;
851 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
852 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
853 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
854 char c = descriptor[0];
855 if (c == 'L' || c == '[') {
856 num_ref++;
857 } else if (c == 'J' || c == 'D') {
858 num_64++;
859 } else {
860 num_32++;
861 }
862 }
863 }
864
865 // start with generic class data
866 size_t size = sizeof(Class);
867 // follow with reference fields which must be contiguous at start
868 size += (num_ref * sizeof(uint32_t));
869 // if there are 64-bit fields to add, make sure they are aligned
870 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
871 if (num_32 != 0) {
872 // use an available 32-bit field for padding
873 num_32--;
874 }
875 size += sizeof(uint32_t); // either way, we are adding a word
876 DCHECK_EQ(size, RoundUp(size, 8));
877 }
878 // tack on any 64-bit fields now that alignment is assured
879 size += (num_64 * sizeof(uint64_t));
880 // tack on any remaining 32-bit fields
881 size += (num_32 * sizeof(uint32_t));
882 return size;
883}
884
Brian Carlstromf615a612011-07-23 12:50:34 -0700885void ClassLinker::LoadClass(const DexFile& dex_file,
886 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700887 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700888 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700889 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700890 CHECK(klass->GetDexCache() != NULL);
891 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700892 const byte* class_data = dex_file.GetClassData(dex_class_def);
893 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700894
Brian Carlstromf615a612011-07-23 12:50:34 -0700895 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700896 CHECK(descriptor != NULL);
897
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700898 klass->SetClass(GetClassRoot(kJavaLangClass));
899 if (klass->GetDescriptor() != NULL) {
900 DCHECK(klass->GetDescriptor()->Equals(descriptor));
901 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700902 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700903 }
904 uint32_t access_flags = dex_class_def.access_flags_;
905 // Make sure there aren't any "bonus" flags set, since we use them for runtime
906 // state.
907 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
908 klass->SetAccessFlags(access_flags);
909 klass->SetClassLoader(class_loader);
910 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
911 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700912
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700913 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700914
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700915 size_t num_static_fields = header.static_fields_size_;
916 size_t num_instance_fields = header.instance_fields_size_;
917 size_t num_direct_methods = header.direct_methods_size_;
918 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700919
Brian Carlstromc74255f2011-09-11 22:47:39 -0700920 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700921
922 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700923 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700924
925 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700926 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700927 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700928 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700929 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700930 DexFile::Field dex_field;
931 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400932 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700933 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700934 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700935 }
936 }
937
938 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700939 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700940 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700941 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700942 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700943 DexFile::Field dex_field;
944 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400945 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700946 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700947 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700948 }
949 }
950
951 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700952 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700953 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700954 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700955 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700956 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700957 DexFile::Method dex_method;
958 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700959 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700960 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700961 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700962 // TODO: register maps
963 }
964 }
965
966 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700967 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700968 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700969 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700970 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700971 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700972 DexFile::Method dex_method;
973 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700974 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700975 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700976 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700977 // TODO: register maps
978 }
979 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700980}
981
Brian Carlstromf615a612011-07-23 12:50:34 -0700982void ClassLinker::LoadInterfaces(const DexFile& dex_file,
983 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700984 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700985 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700986 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700987 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700988 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
989 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700990 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700991 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700992 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700993 }
994 }
995}
996
Brian Carlstromf615a612011-07-23 12:50:34 -0700997void ClassLinker::LoadField(const DexFile& dex_file,
998 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700999 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001000 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001001 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001002 dst->SetDeclaringClass(klass);
1003 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1004 dst->SetTypeIdx(field_id.type_idx_);
1005 dst->SetAccessFlags(src.access_flags_);
1006
1007 // In order to access primitive types using GetTypeDuringLinking we need to
1008 // ensure they are resolved into the dex cache
1009 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1010 if (descriptor[1] == '\0') {
1011 // only the descriptors of primitive types should be 1 character long
1012 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
1013 DCHECK(resolved->IsPrimitive());
1014 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001015}
1016
Brian Carlstromf615a612011-07-23 12:50:34 -07001017void ClassLinker::LoadMethod(const DexFile& dex_file,
1018 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001019 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001020 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001021 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001022 dst->SetDeclaringClass(klass);
Elliott Hughes80609252011-09-23 17:24:51 -07001023 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
1024 dst->SetName(method_name);
1025 if (method_name->Equals("<init>")) {
1026 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1027 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001028 {
1029 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -07001030 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Brian Carlstromc74255f2011-09-11 22:47:39 -07001031 dst->SetSignature(intern_table_->InternStrong(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001032 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001033 dst->SetProtoIdx(method_id.proto_idx_);
1034 dst->SetCodeItemOffset(src.code_off_);
1035 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -07001036 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001037 dst->SetAccessFlags(src.access_flags_);
1038 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001039
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001040 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1041 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1042 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1043 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1044 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1045 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001046
Brian Carlstrom934486c2011-07-12 23:42:50 -07001047 // TODO: check for finalize method
1048
Brian Carlstromf615a612011-07-23 12:50:34 -07001049 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001050 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001051 dst->SetNumRegisters(code_item->registers_size_);
1052 dst->SetNumIns(code_item->ins_size_);
1053 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001054 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001055 uint16_t num_args = Method::NumArgRegisters(shorty);
1056 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001057 ++num_args;
1058 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001059 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001060 // TODO: native methods
1061 }
1062}
1063
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001064void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001065 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1066}
1067
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001068void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001069 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001070 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001071 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001072}
1073
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001074void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001075 RegisterDexFile(dex_file, AllocDexCache(dex_file));
1076}
1077
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001078void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -07001079 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001080 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1081 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001082 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001083 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001084}
1085
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001086const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001087 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001088 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1089 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001090 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001091 }
1092 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001093 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001094 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001095}
1096
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001097DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001098 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001099 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001100 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001101 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001102 }
1103 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001104 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001105 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001106}
1107
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001108Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1109 const char* descriptor,
1110 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001111 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001112 CHECK(primitive_class != NULL);
1113 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1114 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
1115 primitive_class->SetPrimitiveType(type);
1116 primitive_class->SetStatus(Class::kStatusInitialized);
1117 bool success = InsertClass(descriptor, primitive_class);
1118 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1119 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001120}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001121
Brian Carlstrombe977852011-07-19 14:54:54 -07001122// Create an array class (i.e. the class object for the array, not the
1123// array itself). "descriptor" looks like "[C" or "[[[[B" or
1124// "[Ljava/lang/String;".
1125//
1126// If "descriptor" refers to an array of primitives, look up the
1127// primitive type's internally-generated class object.
1128//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001129// "class_loader" is the class loader of the class that's referring to
1130// us. It's used to ensure that we're looking for the element type in
1131// the right context. It does NOT become the class loader for the
1132// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001133//
1134// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001135Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001136 const ClassLoader* class_loader) {
1137 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001138
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001139 // Identify the underlying component type
1140 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001141 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001142 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001143 return NULL;
1144 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001145
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001146 // See if the component type is already loaded. Array classes are
1147 // always associated with the class loader of their underlying
1148 // element type -- an array of Strings goes with the loader for
1149 // java/lang/String -- so we need to look for it there. (The
1150 // caller should have checked for the existence of the class
1151 // before calling here, but they did so with *their* class loader,
1152 // not the component type's loader.)
1153 //
1154 // If we find it, the caller adds "loader" to the class' initiating
1155 // loader list, which should prevent us from going through this again.
1156 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001157 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001158 // are the same, because our caller (FindClass) just did the
1159 // lookup. (Even if we get this wrong we still have correct behavior,
1160 // because we effectively do this lookup again when we add the new
1161 // class to the hash table --- necessary because of possible races with
1162 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001163 if (class_loader != component_type->GetClassLoader()) {
1164 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001165 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001166 return new_class;
1167 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001168 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001169
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001170 // Fill out the fields in the Class.
1171 //
1172 // It is possible to execute some methods against arrays, because
1173 // all arrays are subclasses of java_lang_Object_, so we need to set
1174 // up a vtable. We can just point at the one in java_lang_Object_.
1175 //
1176 // Array classes are simple enough that we don't need to do a full
1177 // link step.
1178
1179 Class* new_class = NULL;
1180 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001181 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001182 if (descriptor == "[Ljava/lang/Class;") {
1183 new_class = GetClassRoot(kClassArrayClass);
1184 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001185 new_class = GetClassRoot(kObjectArrayClass);
1186 } else if (descriptor == "[C") {
1187 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001188 } else if (descriptor == "[I") {
1189 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001190 }
1191 }
1192 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001193 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001194 if (new_class == NULL) {
1195 return NULL;
1196 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001197 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001198 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001199 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001200 if (new_class->GetDescriptor() != NULL) {
1201 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1202 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001203 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001204 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001205 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001206 new_class->SetSuperClass(java_lang_Object);
1207 new_class->SetVTable(java_lang_Object->GetVTable());
1208 new_class->SetPrimitiveType(Class::kPrimNot);
1209 new_class->SetClassLoader(component_type->GetClassLoader());
1210 new_class->SetStatus(Class::kStatusInitialized);
1211 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001212 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001213
1214
1215 // All arrays have java/lang/Cloneable and java/io/Serializable as
1216 // interfaces. We need to set that up here, so that stuff like
1217 // "instanceof" works right.
1218 //
1219 // Note: The GC could run during the call to FindSystemClass,
1220 // so we need to make sure the class object is GC-valid while we're in
1221 // there. Do this by clearing the interface list so the GC will just
1222 // think that the entries are null.
1223
1224
1225 // Use the single, global copies of "interfaces" and "iftable"
1226 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001227 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001228 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001229
1230 // Inherit access flags from the component type. Arrays can't be
1231 // used as a superclass or interface, so we want to add "final"
1232 // and remove "interface".
1233 //
1234 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001235 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001236 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001237 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1238 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001239
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001240 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001241 return new_class;
1242 }
1243 // Another thread must have loaded the class after we
1244 // started but before we finished. Abandon what we've
1245 // done.
1246 //
1247 // (Yes, this happens.)
1248
1249 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001250 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001251 DCHECK(other_class != NULL);
1252 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001253}
1254
1255Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001256 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001257 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001258 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001259 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001260 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001261 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001262 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001263 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001264 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001265 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001266 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001267 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001268 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001269 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001270 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001271 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001272 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001273 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001274 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001275 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001276 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001277 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001278 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001279}
1280
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001281bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1282 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001283 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001284 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001285 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001286}
1287
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001288Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001289 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001290 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001291 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001292 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001293 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001294 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001295 return klass;
1296 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001297 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001298 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001299}
1300
jeffhao98eacac2011-09-14 16:11:53 -07001301void ClassLinker::VerifyClass(Class* klass) {
1302 if (klass->IsVerified()) {
1303 return;
1304 }
1305
1306 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001307 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001308
jeffhao5cfd6fb2011-09-27 13:54:29 -07001309 if (DexVerifier::VerifyClass(klass)) {
1310 klass->SetStatus(Class::kStatusVerified);
1311 } else {
1312 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
1313 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1314
1315 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
1316 klass->SetStatus(Class::kStatusResolved);
1317 }
jeffhao98eacac2011-09-14 16:11:53 -07001318}
1319
Brian Carlstrom25c33252011-09-18 15:58:35 -07001320bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001321 CHECK(klass->IsResolved() || klass->IsErroneous())
1322 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001323
Carl Shapirob5573532011-07-12 18:22:59 -07001324 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001325
Brian Carlstrom25c33252011-09-18 15:58:35 -07001326 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001327 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001328 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001329 ObjectLock lock(klass);
1330
Brian Carlstromd1422f82011-09-28 11:37:09 -07001331 if (klass->GetStatus() == Class::kStatusInitialized) {
1332 return true;
1333 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001334
Brian Carlstromd1422f82011-09-28 11:37:09 -07001335 if (klass->IsErroneous()) {
1336 ThrowEarlierClassFailure(klass);
1337 return false;
1338 }
1339
1340 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001341 VerifyClass(klass);
1342 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001343 return false;
1344 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001345 }
1346
Brian Carlstrom25c33252011-09-18 15:58:35 -07001347 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1348 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001349 // if the class has a <clinit> but we can't run it during compilation,
1350 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001351 return false;
1352 }
1353
Brian Carlstromd1422f82011-09-28 11:37:09 -07001354 // If the class is kStatusInitializing, either this thread is
1355 // initializing higher up the stack or another thread has beat us
1356 // to initializing and we need to wait. Either way, this
1357 // invocation of InitializeClass will not be responsible for
1358 // running <clinit> and will return.
1359 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001360 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001361 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001362 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001363 return true;
1364 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001365 // No. That's fine. Wait for another thread to finish initializing.
1366 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001367 }
1368
1369 if (!ValidateSuperClassDescriptors(klass)) {
1370 klass->SetStatus(Class::kStatusError);
1371 return false;
1372 }
1373
Brian Carlstromd1422f82011-09-28 11:37:09 -07001374 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001375
Elliott Hughesdcc24742011-09-07 14:02:44 -07001376 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001377 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001378 }
1379
Brian Carlstrom25c33252011-09-18 15:58:35 -07001380 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001381 return false;
1382 }
1383
1384 InitializeStaticFields(klass);
1385
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001386 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001387 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001388 }
1389
1390 {
1391 ObjectLock lock(klass);
1392
1393 if (self->IsExceptionPending()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001394 // TODO: if self->GetException() is not an Error,
1395 // wrap in ExceptionInInitializerError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001396 klass->SetStatus(Class::kStatusError);
1397 } else {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001398 ++Runtime::Current()->GetStats()->class_init_count;
1399 ++self->GetStats()->class_init_count;
1400 // TODO: class_init_time_ns
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001401 klass->SetStatus(Class::kStatusInitialized);
1402 }
1403 lock.NotifyAll();
1404 }
1405
1406 return true;
1407}
1408
Brian Carlstromd1422f82011-09-28 11:37:09 -07001409bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1410 while (true) {
1411 CHECK(!self->IsExceptionPending());
1412 lock.Wait();
1413
1414 // When we wake up, repeat the test for init-in-progress. If
1415 // there's an exception pending (only possible if
1416 // "interruptShouldThrow" was set), bail out.
1417 if (self->IsExceptionPending()) {
1418 // TODO: set cause of ExceptionInInitializerError to self->GetException()
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001419 self->ThrowNewExceptionF("Ljava/lang/ExceptionInInitializerError;",
Brian Carlstromd1422f82011-09-28 11:37:09 -07001420 "Exception %s thrown while initializing class %s",
1421 PrettyTypeOf(self->GetException()).c_str(),
1422 PrettyDescriptor(klass->GetDescriptor()).c_str());
1423 klass->SetStatus(Class::kStatusError);
1424 return false;
1425 }
1426 // Spurious wakeup? Go back to waiting.
1427 if (klass->GetStatus() == Class::kStatusInitializing) {
1428 continue;
1429 }
1430 if (klass->IsErroneous()) {
1431 // The caller wants an exception, but it was thrown in a
1432 // different thread. Synthesize one here.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001433 self->ThrowNewExceptionF("Ljava/lang/NoClassDefFoundError;",
Brian Carlstromd1422f82011-09-28 11:37:09 -07001434 "<clinit> failed for class %s; see exception in other thread",
1435 PrettyDescriptor(klass->GetDescriptor()).c_str());
1436 return false;
1437 }
1438 if (klass->IsInitialized()) {
1439 return true;
1440 }
1441 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1442 }
1443 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1444}
1445
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001446bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1447 if (klass->IsInterface()) {
1448 return true;
1449 }
1450 // begin with the methods local to the superclass
1451 if (klass->HasSuperClass() &&
1452 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1453 const Class* super = klass->GetSuperClass();
1454 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001455 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001456 if (method != super->GetVirtualMethod(i) &&
1457 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001458 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1459
1460 ThrowLinkageError("Class %s method %s resolves differently in superclass %s", PrettyDescriptor(klass->GetDescriptor()).c_str(), PrettyMethod(method).c_str(), PrettyDescriptor(super->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001461 return false;
1462 }
1463 }
1464 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001465 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1466 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1467 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001468 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1469 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001470 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001471 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001472 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001473 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1474
1475 ThrowLinkageError("Class %s method %s resolves differently in interface %s", PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor()).c_str(), PrettyMethod(method).c_str(), PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001476 return false;
1477 }
1478 }
1479 }
1480 }
1481 return true;
1482}
1483
1484bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001485 const Class* klass1,
1486 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001487 if (method->IsMiranda()) {
1488 return true;
1489 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001490 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001491 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001492 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001493 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001494 const char* descriptor = it->GetDescriptor();
1495 if (descriptor == NULL) {
1496 break;
1497 }
1498 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1499 // Found a non-primitive type.
1500 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1501 return false;
1502 }
1503 }
1504 }
1505 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001506 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001507 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001508 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001509 return false;
1510 }
1511 }
1512 return true;
1513}
1514
1515// Returns true if classes referenced by the descriptor are the
1516// same classes in klass1 as they are in klass2.
1517bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001518 const Class* klass1,
1519 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001520 CHECK(descriptor != NULL);
1521 CHECK(klass1 != NULL);
1522 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001523 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001524 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001525 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001526 // TODO: found2 == NULL
1527 // TODO: lookup found1 in initiating loader list
1528 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001529 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001530 if (found1 == found2) {
1531 return true;
1532 } else {
1533 return false;
1534 }
1535 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001536 return true;
1537}
1538
Brian Carlstrom25c33252011-09-18 15:58:35 -07001539bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001540 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001541 if (!klass->IsInterface() && klass->HasSuperClass()) {
1542 Class* super_class = klass->GetSuperClass();
1543 if (super_class->GetStatus() != Class::kStatusInitialized) {
1544 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001545 Thread* self = Thread::Current();
1546 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001547 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001548 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001549 // TODO: check for a pending exception
1550 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001551 if (!can_run_clinit) {
1552 // Don't set status to error when we can't run <clinit>.
1553 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1554 klass->SetStatus(Class::kStatusVerified);
1555 return false;
1556 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001557 klass->SetStatus(Class::kStatusError);
1558 klass->NotifyAll();
1559 return false;
1560 }
1561 }
1562 }
1563 return true;
1564}
1565
Brian Carlstrom25c33252011-09-18 15:58:35 -07001566bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001567 CHECK(c != NULL);
1568 if (c->IsInitialized()) {
1569 return true;
1570 }
1571
Elliott Hughes5f791332011-09-15 17:45:30 -07001572 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001573 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001574 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001575 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001576}
1577
Brian Carlstromb9edb842011-08-28 16:31:06 -07001578StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1579 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001580 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1581 Class* klass = class_linker->ResolveType(type_idx, referrer);
1582 if (klass == NULL) {
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001583 CHECK(Thread::Current()->IsExceptionPending());
1584 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001585 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001586 // If we are the <clinit> of this class, just return our storage.
1587 //
1588 // Do not set the DexCache InitializedStaticStorage, since that
1589 // implies <clinit> has finished running.
1590 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1591 return klass;
1592 }
Brian Carlstrom25c33252011-09-18 15:58:35 -07001593 if (!class_linker->EnsureInitialized(klass, true)) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001594 CHECK(Thread::Current()->IsExceptionPending());
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001595 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001596 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001597 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001598 return klass;
1599}
1600
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001601void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1602 Class* c, std::map<int, Field*>& field_map) {
1603 const ClassLoader* cl = c->GetClassLoader();
1604 const byte* class_data = dex_file.GetClassData(dex_class_def);
1605 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1606 uint32_t last_idx = 0;
1607 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1608 DexFile::Field dex_field;
1609 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1610 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1611 }
1612}
1613
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001614void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001615 size_t num_static_fields = klass->NumStaticFields();
1616 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001617 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001618 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001619 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001620 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001621 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001622 return;
1623 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001624 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001625 const DexFile& dex_file = FindDexFile(dex_cache);
1626 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001627 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001628
1629 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1630 std::map<int, Field*> field_map;
1631 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1632
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001633 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001634 if (addr == NULL) {
1635 // All this class' static fields have default values.
1636 return;
1637 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001638 size_t array_size = DecodeUnsignedLeb128(&addr);
1639 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001640 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001641 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001642 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001643 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001644 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001645 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001646 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001647 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001648 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001649 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001650 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001651 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001652 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001653 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001654 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001655 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001656 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001657 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001658 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001659 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001660 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001661 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001662 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001663 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001664 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001665 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001666 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001667 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001668 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001669 break;
1670 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001671 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001672 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001673 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001674 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001675 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001676 break;
1677 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001678 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001679 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001680 }
1681}
1682
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001683bool ClassLinker::LinkClass(Class* klass) {
1684 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001685 if (!LinkSuperClass(klass)) {
1686 return false;
1687 }
1688 if (!LinkMethods(klass)) {
1689 return false;
1690 }
1691 if (!LinkInstanceFields(klass)) {
1692 return false;
1693 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001694 if (!LinkStaticFields(klass)) {
1695 return false;
1696 }
1697 CreateReferenceInstanceOffsets(klass);
1698 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001699 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1700 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001701 return true;
1702}
1703
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001704bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001705 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1706 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1707 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001708 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001709 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710 return false;
1711 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001712 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001713 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001714 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1715 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07001716 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001717 klass->SetInterface(i, interface);
1718 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001719 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001720 return false;
1721 }
1722 // Verify
1723 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001724 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001725 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001726 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001727 PrettyDescriptor(interface->GetDescriptor()).c_str(),
1728 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001729 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001730 }
1731 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001732 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001733 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001734 return true;
1735}
1736
1737bool ClassLinker::LinkSuperClass(Class* klass) {
1738 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001739 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001740 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001741 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001742 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001743 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001744 return false;
1745 }
1746 // TODO: clear finalize attribute
1747 return true;
1748 }
1749 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001750 ThrowLinkageError("No superclass defined for class %s",
1751 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001752 return false;
1753 }
1754 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001755 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001756 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001757 "Superclass %s of %s is %s",
1758 PrettyDescriptor(super->GetDescriptor()).c_str(),
1759 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001760 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001761 return false;
1762 }
1763 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001764 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001765 "Superclass %s is inaccessible by %s",
1766 PrettyDescriptor(super->GetDescriptor()).c_str(),
1767 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001768 return false;
1769 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001770#ifndef NDEBUG
1771 // Ensure super classes are fully resolved prior to resolving fields..
1772 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001773 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001774 super = super->GetSuperClass();
1775 }
1776#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001777 return true;
1778}
1779
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001780// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001781bool ClassLinker::LinkMethods(Class* klass) {
1782 if (klass->IsInterface()) {
1783 // No vtable.
1784 size_t count = klass->NumVirtualMethods();
1785 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001786 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001787 return false;
1788 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001789 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001790 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001791 }
jeffhaobdb76512011-09-07 11:43:16 -07001792 // Link interface method tables
1793 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001794 } else {
1795 // Link virtual method tables
1796 LinkVirtualMethods(klass);
1797
1798 // Link interface method tables
1799 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001800 }
1801 return true;
1802}
1803
1804bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001805 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001806 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1807 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001808 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001809 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001810 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001811 // See if any of our virtual methods override the superclass.
1812 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001813 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001814 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001815 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001816 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001817 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001818 // Verify
1819 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001820 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001821 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1822 local_method->GetName()->ToModifiedUtf8().c_str(),
1823 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001824 return false;
1825 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001826 vtable->Set(j, local_method);
1827 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001828 break;
1829 }
1830 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001831 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001832 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001833 vtable->Set(actual_count, local_method);
1834 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001835 actual_count += 1;
1836 }
1837 }
1838 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001839 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001840 return false;
1841 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001842 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001843 CHECK_LE(actual_count, max_count);
1844 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001845 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001846 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001847 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001848 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001849 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001850 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001851 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001852 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001853 return false;
1854 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001855 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001856 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001857 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1858 vtable->Set(i, virtual_method);
1859 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001860 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001861 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001862 }
1863 return true;
1864}
1865
1866bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001867 size_t super_ifcount;
1868 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001869 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001870 } else {
1871 super_ifcount = 0;
1872 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001873 size_t ifcount = super_ifcount;
1874 ifcount += klass->NumInterfaces();
1875 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001876 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001877 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001878 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001879 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001880 // DCHECK(klass->GetIfTableCount() == 0);
1881 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001882 return true;
1883 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001884 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001885 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001886 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1887 for (size_t i = 0; i < super_ifcount; i++) {
1888 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1889 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001890 }
1891 // Flatten the interface inheritance hierarchy.
1892 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001893 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001894 Class* interface = klass->GetInterface(i);
1895 DCHECK(interface != NULL);
1896 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001897 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001898 "Class %s implements non-interface class %s",
1899 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1900 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001901 return false;
1902 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001903 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001904 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07001905 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001906 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1907 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001908 }
1909 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001910 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001911 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07001912
1913 // If we're an interface, we don't need the vtable pointers, so we're done.
1914 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001915 return true;
1916 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001917 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001918 for (size_t i = 0; i < ifcount; ++i) {
1919 InterfaceEntry* interface_entry = iftable->Get(i);
1920 Class* interface = interface_entry->GetInterface();
1921 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1922 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001923 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001924 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1925 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001926 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07001927 // For each method listed in the interface's method list, find the
1928 // matching method in our class's method list. We want to favor the
1929 // subclass over the superclass, which just requires walking
1930 // back from the end of the vtable. (This only matters if the
1931 // superclass defines a private method and this class redefines
1932 // it -- otherwise it would use the same vtable slot. In .dex files
1933 // those don't end up in the virtual method table, so it shouldn't
1934 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001935 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1936 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001937 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1938 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001939 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001940 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001941 return false;
1942 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001943 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001944 break;
1945 }
1946 }
1947 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001948 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07001949 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
1950 if (miranda_list[mir]->HasSameNameAndDescriptor(interface_method)) {
1951 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001952 break;
1953 }
1954 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001955 if (miranda_method == NULL) {
1956 // point the interface table at a phantom slot
1957 miranda_method = AllocMethod();
1958 memcpy(miranda_method, interface_method, sizeof(Method));
1959 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001960 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001961 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001962 }
1963 }
1964 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001965 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001966 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07001967 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001968 klass->SetVirtualMethods((old_method_count == 0)
1969 ? AllocObjectArray<Method>(new_method_count)
1970 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001971
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001972 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1973 CHECK(vtable != NULL);
1974 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07001975 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001976 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07001977 for (size_t i = 0; i < miranda_list.size(); ++i) {
1978 Method* meth = miranda_list[i]; //AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001979 // TODO: this shouldn't be a memcpy
Elliott Hughes4681c802011-09-25 18:04:37 -07001980 //memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001981 meth->SetDeclaringClass(klass);
1982 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1983 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001984 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001985 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001986 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001987 // TODO: do not assign to the vtable field until it is fully constructed.
1988 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001989 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001990
1991 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1992 for (int i = 0; i < vtable->GetLength(); ++i) {
1993 CHECK(vtable->Get(i) != NULL);
1994 }
1995
1996// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1997
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001998 return true;
1999}
2000
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002001bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002002 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002003 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002004}
2005
2006bool ClassLinker::LinkStaticFields(Class* klass) {
2007 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002008 size_t allocated_class_size = klass->GetClassSize();
2009 bool success = LinkFields(klass, false);
2010 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002011 return success;
2012}
2013
Brian Carlstromdbc05252011-09-09 01:59:59 -07002014struct LinkFieldsComparator {
2015 bool operator()(const Field* field1, const Field* field2){
2016
2017 // First come reference fields, then 64-bit, and finally 32-bit
2018 const Class* type1 = field1->GetTypeDuringLinking();
2019 const Class* type2 = field2->GetTypeDuringLinking();
2020 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2021 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2022 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2023 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2024 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2025 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2026 if (order1 != order2) {
2027 return order1 < order2;
2028 }
2029
2030 // same basic group? then sort by string.
2031 std::string name1 = field1->GetName()->ToModifiedUtf8();
2032 std::string name2 = field2->GetName()->ToModifiedUtf8();
2033 return name1 < name2;
2034 }
2035};
2036
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002037bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002038 size_t num_fields =
2039 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
2040
2041 ObjectArray<Field>* fields =
2042 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002043
2044 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002045 size_t size;
2046 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002047 if (instance) {
2048 Class* super_class = klass->GetSuperClass();
2049 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002050 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002051 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002052 }
2053 size = field_offset.Uint32Value();
2054 } else {
2055 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07002056 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002057 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002058
Brian Carlstromdbc05252011-09-09 01:59:59 -07002059 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002060
Brian Carlstromdbc05252011-09-09 01:59:59 -07002061 // we want a relatively stable order so that adding new fields
2062 // minimizes distruption of C++ version such as Class and Method.
2063 std::deque<Field*> grouped_and_sorted_fields;
2064 for (size_t i = 0; i < num_fields; i++) {
2065 grouped_and_sorted_fields.push_back(fields->Get(i));
2066 }
2067 std::sort(grouped_and_sorted_fields.begin(),
2068 grouped_and_sorted_fields.end(),
2069 LinkFieldsComparator());
2070
2071 // References should be at the front.
2072 size_t current_field = 0;
2073 size_t num_reference_fields = 0;
2074 for (; current_field < num_fields; current_field++) {
2075 Field* field = grouped_and_sorted_fields.front();
2076 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002077 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002078 bool isPrimitive = type != NULL && type->IsPrimitive();
2079 if (isPrimitive) {
2080 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002081 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002082 grouped_and_sorted_fields.pop_front();
2083 num_reference_fields++;
2084 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002085 field->SetOffset(field_offset);
2086 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002087 }
2088
2089 // Now we want to pack all of the double-wide fields together. If
2090 // we're not aligned, though, we want to shuffle one 32-bit field
2091 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002092 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2093 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2094 Field* field = grouped_and_sorted_fields[i];
2095 const Class* type = field->GetTypeDuringLinking();
2096 CHECK(type != NULL); // should only be working on primitive types
2097 DCHECK(type->IsPrimitive());
2098 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2099 continue;
2100 }
2101 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002102 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002103 // drop the consumed field
2104 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2105 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002106 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002107 // whether we found a 32-bit field for padding or not, we advance
2108 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002109 }
2110
2111 // Alignment is good, shuffle any double-wide fields forward, and
2112 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002113 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2114 while (!grouped_and_sorted_fields.empty()) {
2115 Field* field = grouped_and_sorted_fields.front();
2116 grouped_and_sorted_fields.pop_front();
2117 const Class* type = field->GetTypeDuringLinking();
2118 CHECK(type != NULL); // should only be working on primitive types
2119 DCHECK(type->IsPrimitive());
2120 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002121 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002122 field_offset = MemberOffset(field_offset.Uint32Value() +
2123 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2124 ? sizeof(uint64_t)
2125 : sizeof(uint32_t)));
2126 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002127 }
2128
2129#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002130 // Make sure that all reference fields appear before
2131 // non-reference fields, and all double-wide fields are aligned.
2132 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002133 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002134 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002135 if (false) { // enable to debug field layout
Brian Carlstrom845490b2011-09-19 15:56:53 -07002136 LOG(INFO) << "LinkFields: " << (instance ? "instance" : "static")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002137 << " class=" << PrettyClass(klass)
2138 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002139 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2140 }
2141 const Class* type = field->GetTypeDuringLinking();
2142 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002143 if (!seen_non_ref) {
2144 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002145 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002146 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002147 } else {
2148 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002149 }
2150 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002151 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002152 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002153 }
2154#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002155 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002156 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07002157 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002158 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002159 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002160 klass->SetObjectSize(size);
2161 }
2162 } else {
2163 klass->SetNumReferenceStaticFields(num_reference_fields);
2164 klass->SetClassSize(size);
2165 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002166 return true;
2167}
2168
2169// Set the bitmap of reference offsets, refOffsets, from the ifields
2170// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002171void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002172 uint32_t reference_offsets = 0;
2173 Class* super_class = klass->GetSuperClass();
2174 if (super_class != NULL) {
2175 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002176 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002177 if (reference_offsets == CLASS_WALK_SUPER) {
2178 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002179 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002180 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002181 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002182 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002183}
2184
2185void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002186 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002187}
2188
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002189void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2190 uint32_t reference_offsets) {
2191 size_t num_reference_fields =
2192 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2193 : klass->NumReferenceStaticFieldsDuringLinking();
2194 const ObjectArray<Field>* fields =
2195 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002196 // All of the fields that contain object references are guaranteed
2197 // to be at the beginning of the fields list.
2198 for (size_t i = 0; i < num_reference_fields; ++i) {
2199 // Note that byte_offset is the offset from the beginning of
2200 // object, not the offset into instance data
2201 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002202 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002203 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2204 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2205 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002206 CHECK_NE(new_bit, 0U);
2207 reference_offsets |= new_bit;
2208 } else {
2209 reference_offsets = CLASS_WALK_SUPER;
2210 break;
2211 }
2212 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002213 // Update fields in klass
2214 if (instance) {
2215 klass->SetReferenceInstanceOffsets(reference_offsets);
2216 } else {
2217 klass->SetReferenceStaticOffsets(reference_offsets);
2218 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002219}
2220
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002221String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002222 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002223 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002224 if (resolved != NULL) {
2225 return resolved;
2226 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002227 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2228 int32_t utf16_length = dex_file.GetStringLength(string_id);
2229 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002230 // TODO: remote the const_cast below
2231 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002232 dex_cache->SetResolvedString(string_idx, string);
2233 return string;
2234}
2235
2236Class* ClassLinker::ResolveType(const DexFile& dex_file,
2237 uint32_t type_idx,
2238 DexCache* dex_cache,
2239 const ClassLoader* class_loader) {
2240 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002241 if (resolved == NULL) {
2242 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2243 if (descriptor[1] == '\0') {
2244 // only the descriptors of primitive types should be 1 character long
2245 resolved = FindPrimitiveClass(descriptor[0]);
2246 } else {
2247 resolved = FindClass(descriptor, class_loader);
2248 }
2249 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002250 Class* check = resolved;
2251 while (check->IsArrayClass()) {
2252 check = check->GetComponentType();
2253 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002254 if (dex_cache != check->GetDexCache()) {
2255 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002256 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002257 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002258 resolved = NULL;
2259 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002260 }
2261 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002262 if (resolved != NULL) {
2263 dex_cache->SetResolvedType(type_idx, resolved);
2264 } else {
2265 DCHECK(Thread::Current()->IsExceptionPending());
2266 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002267 }
2268 return resolved;
2269}
2270
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002271Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2272 uint32_t method_idx,
2273 DexCache* dex_cache,
2274 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002275 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002276 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2277 if (resolved != NULL) {
2278 return resolved;
2279 }
2280 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2281 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2282 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002283 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002284 return NULL;
2285 }
2286
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002287 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002288 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002289 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002290 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002291 } else if (klass->IsInterface()) {
2292 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002293 } else {
2294 resolved = klass->FindVirtualMethod(name, signature);
2295 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002296 if (resolved != NULL) {
2297 dex_cache->SetResolvedMethod(method_idx, resolved);
2298 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002299 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002300 }
2301 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002302}
2303
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002304Field* ClassLinker::ResolveField(const DexFile& dex_file,
2305 uint32_t field_idx,
2306 DexCache* dex_cache,
2307 const ClassLoader* class_loader,
2308 bool is_static) {
2309 Field* resolved = dex_cache->GetResolvedField(field_idx);
2310 if (resolved != NULL) {
2311 return resolved;
2312 }
2313 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2314 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2315 if (klass == NULL) {
2316 return NULL;
2317 }
2318
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002319 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002320 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002321 if (field_type == NULL) {
2322 // TODO: LinkageError?
2323 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2324 << " in " << PrettyClass(klass);
2325 return NULL;
2326}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002327 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002328 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002329 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002330 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002331 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002332 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002333 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002334 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002335 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002336 }
2337 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002338}
2339
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002340void ClassLinker::DumpAllClasses(int flags) const {
2341 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2342 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2343 std::vector<Class*> all_classes;
2344 {
2345 MutexLock mu(lock_);
2346 typedef Table::const_iterator It; // TODO: C++0x auto
2347 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2348 all_classes.push_back(it->second);
2349 }
2350 }
2351
2352 for (size_t i = 0; i < all_classes.size(); ++i) {
2353 all_classes[i]->DumpClass(std::cerr, flags);
2354 }
2355}
2356
Elliott Hughese27955c2011-08-26 15:21:24 -07002357size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002358 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002359 return classes_.size();
2360}
2361
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002362} // namespace art