blob: aa69c307ff61e1414a9bad53876ac3f6e4dad9fe [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
54void ThrowEarlierClassFailure(Class* c) {
55 /*
56 * The class failed to initialize on a previous attempt, so we want to throw
57 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
58 * failed in verification, in which case v2 5.4.1 says we need to re-throw
59 * the previous error.
60 */
61 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
62
63 if (c->GetVerifyErrorClass() != NULL) {
64 // TODO: change the verifier to store an _instance_, with a useful detail message?
65 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
66 Thread::Current()->ThrowNewException(error_descriptor.c_str(), "%s",
67 PrettyDescriptor(c->GetDescriptor()).c_str());
68 } else {
69 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
70 }
71}
72
73}
74
Elliott Hughes418d20f2011-09-22 14:00:39 -070075const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -070076 "Ljava/lang/Class;",
77 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -070078 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070079 "[Ljava/lang/Object;",
80 "Ljava/lang/String;",
Elliott Hughes80609252011-09-23 17:24:51 -070081 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070082 "Ljava/lang/reflect/Field;",
83 "Ljava/lang/reflect/Method;",
84 "Ljava/lang/ClassLoader;",
85 "Ldalvik/system/BaseDexClassLoader;",
86 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -070087 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -070088 "Z",
89 "B",
90 "C",
91 "D",
92 "F",
93 "I",
94 "J",
95 "S",
96 "V",
97 "[Z",
98 "[B",
99 "[C",
100 "[D",
101 "[F",
102 "[I",
103 "[J",
104 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700105 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700106};
107
Elliott Hughes5f791332011-09-15 17:45:30 -0700108class ObjectLock {
109 public:
110 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
111 CHECK(object != NULL);
112 obj_->MonitorEnter(self_);
113 }
114
115 ~ObjectLock() {
116 obj_->MonitorExit(self_);
117 }
118
119 void Wait() {
120 return Monitor::Wait(self_, obj_, 0, 0, false);
121 }
122
123 void Notify() {
124 obj_->Notify();
125 }
126
127 void NotifyAll() {
128 obj_->NotifyAll();
129 }
130
131 private:
132 Thread* self_;
133 Object* obj_;
134 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
135};
136
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700137ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path,
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700138 const std::vector<const DexFile*>& class_path,
Brian Carlstromc74255f2011-09-11 22:47:39 -0700139 InternTable* intern_table, bool image) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700140 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700141 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700142 if (image) {
143 class_linker->InitFromImage(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700144 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700145 class_linker->Init(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700146 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700147 // TODO: check for failure during initialization
148 return class_linker.release();
149}
150
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700151ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700152 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700153 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700154 array_interfaces_(NULL),
155 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700156 init_done_(false),
157 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700158 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700159}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700160
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700161void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
162 const std::vector<const DexFile*>& class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700163 const Runtime* runtime = Runtime::Current();
164 if (runtime->IsVerboseStartup()) {
165 LOG(INFO) << "ClassLinker::InitFrom entering";
166 }
167
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700168 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700169
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700170 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700171 Class* java_lang_Class = down_cast<Class*>(
172 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700173 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700174 java_lang_Class->SetClass(java_lang_Class);
175 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700176 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700177
Elliott Hughes418d20f2011-09-22 14:00:39 -0700178 // Class[] is used for reflection support.
179 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
180 class_array_class->SetComponentType(java_lang_Class);
181
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700182 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700183 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700184 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700185 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700186 java_lang_Class->SetSuperClass(java_lang_Object);
187 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700188
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700189 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700190 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700191 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700192
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700193 // Setup the char class to be used for char[]
194 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
195
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700196 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700197 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700198 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700199 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700200
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700201 // Setup String
202 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
203 String::SetClass(java_lang_String);
204 java_lang_String->SetObjectSize(sizeof(String));
205 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400206
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700207 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700208 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
209 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700210 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700211 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
212 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
213 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700214
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700215 // Create storage for root classes, save away our work so far (requires
216 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700217 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700218 SetClassRoot(kJavaLangClass, java_lang_Class);
219 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700220 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700221 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700222 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700223 SetClassRoot(kJavaLangString, java_lang_String);
224
225 // Setup the primitive type classes.
226 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
227 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700228 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
229 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
230 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
231 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
232 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
233 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
234
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700235 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700236 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700237 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700238
239 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
240 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700241 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
243 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700244 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700245
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700246 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700247
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700248 // setup boot_class_path_ and register class_path now that we can
249 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700250 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700251 const DexFile* dex_file = boot_class_path[i];
252 CHECK(dex_file != NULL);
253 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700254 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700255 for (size_t i = 0; i != class_path.size(); ++i) {
256 const DexFile* dex_file = class_path[i];
257 CHECK(dex_file != NULL);
258 RegisterDexFile(*dex_file);
259 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700260
Elliott Hughes80609252011-09-23 17:24:51 -0700261 // Constructor, Field, and Method are necessary so that FindClass can link members
262 Class* java_lang_reflect_Constructor = AllocClass(java_lang_Class, sizeof(MethodClass));
263 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
264 CHECK(java_lang_reflect_Constructor != NULL);
265 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
266 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor);
267 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
268
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700269 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
270 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700271 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700272 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
273 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
274 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
275 Field::SetClass(java_lang_reflect_Field);
276
277 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Elliott Hughes80609252011-09-23 17:24:51 -0700278 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700279 CHECK(java_lang_reflect_Method != NULL);
280 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
281 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
282 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Elliott Hughes80609252011-09-23 17:24:51 -0700283 Method::SetClasses(java_lang_reflect_Constructor, java_lang_reflect_Method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284
285 // now we can use FindSystemClass
286
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700287 // run char class through InitializePrimitiveClass to finish init
288 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
289 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
290
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700291 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 java_lang_Object->SetStatus(Class::kStatusNotReady);
293 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
294 CHECK_EQ(java_lang_Object, Object_class);
295 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
296 java_lang_String->SetStatus(Class::kStatusNotReady);
297 Class* String_class = FindSystemClass("Ljava/lang/String;");
298 CHECK_EQ(java_lang_String, String_class);
299 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
300
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700301 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
303 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
304
305 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
306 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
307
308 Class* found_char_array_class = FindSystemClass("[C");
309 CHECK_EQ(char_array_class, found_char_array_class);
310
311 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
312 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
313
314 Class* found_int_array_class = FindSystemClass("[I");
315 CHECK_EQ(int_array_class, found_int_array_class);
316
317 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
318 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
319
320 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
321 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
322
323 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
324 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
325
Elliott Hughes418d20f2011-09-22 14:00:39 -0700326 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
327 CHECK_EQ(class_array_class, found_class_array_class);
328
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700329 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
330 CHECK_EQ(object_array_class, found_object_array_class);
331
332 // Setup the single, global copies of "interfaces" and "iftable"
333 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
334 CHECK(java_lang_Cloneable != NULL);
335 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
336 CHECK(java_io_Serializable != NULL);
337 CHECK(array_interfaces_ != NULL);
338 array_interfaces_->Set(0, java_lang_Cloneable);
339 array_interfaces_->Set(1, java_io_Serializable);
340 // We assume that Cloneable/Serializable don't have superinterfaces --
341 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700342 // supers as well.
343 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
344 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345
Elliott Hughes418d20f2011-09-22 14:00:39 -0700346 // Sanity check Class[] and Object[]'s interfaces
347 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
348 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
350 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700351
Elliott Hughes80609252011-09-23 17:24:51 -0700352 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700353 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700354 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700355 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356
Elliott Hughes80609252011-09-23 17:24:51 -0700357 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
358 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
359 CHECK_EQ(java_lang_reflect_Constructor, Constructor_class);
360
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700362 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700363 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364
365 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700366 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700367 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700368
369 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
370 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371 java_lang_ref_FinalizerReference->SetAccessFlags(
372 java_lang_ref_FinalizerReference->GetAccessFlags() |
373 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700374 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700375 java_lang_ref_PhantomReference->SetAccessFlags(
376 java_lang_ref_PhantomReference->GetAccessFlags() |
377 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700378 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700379 java_lang_ref_SoftReference->SetAccessFlags(
380 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700381 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382 java_lang_ref_WeakReference->SetAccessFlags(
383 java_lang_ref_WeakReference->GetAccessFlags() |
384 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700385
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386 // Setup the ClassLoaders, adjusting the object_size_ as necessary
387 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
388 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
389 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
390 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
391
392 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
393 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
394 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
395
396 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
397 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
398 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
399 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
400
401 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700402 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
403 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700404 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700405
Brian Carlstroma663ea52011-08-19 23:33:41 -0700406 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700407
408 if (runtime->IsVerboseStartup()) {
409 LOG(INFO) << "ClassLinker::InitFrom exiting";
410 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700411}
412
413void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700414 const Runtime* runtime = Runtime::Current();
415 if (runtime->IsVerboseStartup()) {
416 LOG(INFO) << "ClassLinker::FinishInit entering";
417 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700418
419 // Let the heap know some key offsets into java.lang.ref instances
420 // NB we hard code the field indexes here rather than using FindInstanceField
421 // as the types of the field can't be resolved prior to the runtime being
422 // fully initialized
423 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
424 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
425
426 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
427 CHECK(pendingNext->GetName()->Equals("pendingNext"));
428 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
429
430 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
431 CHECK(queue->GetName()->Equals("queue"));
432 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
433 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
434
435 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
436 CHECK(queueNext->GetName()->Equals("queueNext"));
437 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
438
439 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
440 CHECK(referent->GetName()->Equals("referent"));
441 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
442
443 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
444 CHECK(zombie->GetName()->Equals("zombie"));
445 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
446
447 Heap::SetReferenceOffsets(referent->GetOffset(),
448 queue->GetOffset(),
449 queueNext->GetOffset(),
450 pendingNext->GetOffset(),
451 zombie->GetOffset());
452
Brian Carlstroma663ea52011-08-19 23:33:41 -0700453 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700454 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700455 ClassRoot class_root = static_cast<ClassRoot>(i);
456 Class* klass = GetClassRoot(class_root);
457 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700459 // note SetClassRoot does additional validation.
460 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700461 }
462
463 // disable the slow paths in FindClass and CreatePrimitiveClass now
464 // that Object, Class, and Object[] are setup
465 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700466
467 if (runtime->IsVerboseStartup()) {
468 LOG(INFO) << "ClassLinker::FinishInit exiting";
469 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700470}
471
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700472void ClassLinker::RunRootClinits() {
473 Thread* self = Thread::Current();
474 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
475 Class* c = GetClassRoot(ClassRoot(i));
476 if (!c->IsArrayClass() && !c->IsPrimitive()) {
477 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
478 CHECK(!self->IsExceptionPending());
479 }
480 }
481}
482
Brian Carlstromc74255f2011-09-11 22:47:39 -0700483struct ClassLinker::InitFromImageCallbackState {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700484 ClassLinker* class_linker;
485
486 Class* class_roots[kClassRootsMax];
487
488 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
489 Table descriptor_to_class_root;
490
Brian Carlstroma663ea52011-08-19 23:33:41 -0700491 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
492 Set dex_caches;
493};
494
Brian Carlstromc74255f2011-09-11 22:47:39 -0700495void ClassLinker::InitFromImage(const std::vector<const DexFile*>& boot_class_path,
496 const std::vector<const DexFile*>& class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700497 const Runtime* runtime = Runtime::Current();
498 if (runtime->IsVerboseStartup()) {
499 LOG(INFO) << "ClassLinker::InitFromImage entering";
500 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700501 CHECK(!init_done_);
502
503 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
504 DCHECK(heap_bitmap != NULL);
505
Brian Carlstromc74255f2011-09-11 22:47:39 -0700506 InitFromImageCallbackState state;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700507 state.class_linker = this;
508 for (size_t i = 0; i < kClassRootsMax; i++) {
509 ClassRoot class_root = static_cast<ClassRoot>(i);
510 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
511 }
512
513 // reinit clases_ table
Brian Carlstromc74255f2011-09-11 22:47:39 -0700514 heap_bitmap->Walk(InitFromImageCallback, &state);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700515
516 // reinit class_roots_
517 Class* object_array_class = state.class_roots[kObjectArrayClass];
518 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
519 for (size_t i = 0; i < kClassRootsMax; i++) {
520 ClassRoot class_root = static_cast<ClassRoot>(i);
521 SetClassRoot(class_root, state.class_roots[class_root]);
522 }
523
Brian Carlstroma663ea52011-08-19 23:33:41 -0700524 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
526 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700527
528 // build a map from location to DexCache to match up with DexFile::GetLocation
529 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Brian Carlstromc74255f2011-09-11 22:47:39 -0700530 typedef InitFromImageCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700531 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
532 DexCache* dex_cache = *it;
533 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
534 location_to_dex_cache[location] = dex_cache;
535 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700536 CHECK_EQ(boot_class_path.size() + class_path.size(),
537 location_to_dex_cache.size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700538
539 // reinit boot_class_path with DexFile arguments and found DexCaches
540 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700541 const DexFile* dex_file = boot_class_path[i];
542 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700543 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700544 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700545 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700546 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700547
548 // register class_path with DexFile arguments and found DexCaches
549 for (size_t i = 0; i != class_path.size(); ++i) {
550 const DexFile* dex_file = class_path[i];
551 CHECK(dex_file != NULL);
552 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
553 CHECK(dex_cache != NULL) << dex_file->GetLocation();
554 RegisterDexFile(*dex_file, dex_cache);
555 }
556
Brian Carlstroma663ea52011-08-19 23:33:41 -0700557 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700558 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700559 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700560 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
561 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
562 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
563 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
564 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
565 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
566 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
567 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700568 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700569 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700570
571 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700572
573 if (runtime->IsVerboseStartup()) {
574 LOG(INFO) << "ClassLinker::InitFromImage exiting";
575 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700576}
577
Brian Carlstrom78128a62011-09-15 17:21:19 -0700578void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700579 DCHECK(obj != NULL);
580 DCHECK(arg != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700581 InitFromImageCallbackState* state = reinterpret_cast<InitFromImageCallbackState*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700582
Brian Carlstromc74255f2011-09-11 22:47:39 -0700583 if (obj->IsString()) {
584 state->class_linker->intern_table_->RegisterStrong(obj->AsString());
585 return;
586 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700587 if (!obj->IsClass()) {
588 return;
589 }
590 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700591 // TODO: restore ClassLoader's list of DexFiles after image load
592 // CHECK(klass->GetClassLoader() == NULL);
593 const ClassLoader* class_loader = klass->GetClassLoader();
594 if (class_loader != NULL) {
595 // TODO: replace this hack with something based on command line arguments
596 Thread::Current()->SetClassLoaderOverride(class_loader);
597 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700598
599 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700600 // restore class to ClassLinker::classes_ table
601 state->class_linker->InsertClass(descriptor, klass);
602
603 // note DexCache to match with DexFile later
604 DexCache* dex_cache = klass->GetDexCache();
605 if (dex_cache != NULL) {
606 state->dex_caches.insert(dex_cache);
607 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700608 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700609 }
610
611 // check if this is a root, if so, register it
Brian Carlstromc74255f2011-09-11 22:47:39 -0700612 typedef InitFromImageCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700613 It it = state->descriptor_to_class_root.find(descriptor);
614 if (it != state->descriptor_to_class_root.end()) {
615 ClassRoot class_root = it->second;
616 state->class_roots[class_root] = klass;
617 }
618}
619
620// Keep in sync with InitCallback. Anything we visit, we need to
621// reinit references to when reinitializing a ClassLinker from a
622// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700623void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
624 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700625
626 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700627 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700628 }
629
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700630 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700631 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700632 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700633 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700634 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700635 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700636 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700637
Elliott Hughes410c0c82011-09-01 17:58:25 -0700638 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700639}
640
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700641ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700642 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700643 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700644 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700645 BooleanArray::ResetArrayClass();
646 ByteArray::ResetArrayClass();
647 CharArray::ResetArrayClass();
648 DoubleArray::ResetArrayClass();
649 FloatArray::ResetArrayClass();
650 IntArray::ResetArrayClass();
651 LongArray::ResetArrayClass();
652 ShortArray::ResetArrayClass();
653 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700654 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700655}
656
657DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700658 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700659 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700660 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700661 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700662 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700663 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700664 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
665 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700666 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700667}
668
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700669CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
670 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700671}
672
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700673InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
674 DCHECK(interface->IsInterface());
675 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
676 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
677 interface_entry->SetInterface(interface);
678 return interface_entry;
679}
680
Brian Carlstrom4873d462011-08-21 15:23:39 -0700681Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
682 DCHECK_GE(class_size, sizeof(Class));
683 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700684 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
685 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700686 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700687}
688
Brian Carlstrom4873d462011-08-21 15:23:39 -0700689Class* ClassLinker::AllocClass(size_t class_size) {
690 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700691}
692
Jesse Wilson35baaab2011-08-10 16:18:03 -0400693Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700694 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700695}
696
697Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700698 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700699}
700
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700701ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
702 return ObjectArray<StackTraceElement>::Alloc(
703 GetClassRoot(kJavaLangStackTraceElementArrayClass),
704 length);
705}
706
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700707Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700708 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700709 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700710 if (class_loader != NULL) {
711 Class* klass = FindClass(descriptor, NULL);
712 if (klass != NULL) {
713 return klass;
714 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700715 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700716 }
717
Carl Shapirob5573532011-07-12 18:22:59 -0700718 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700719 DCHECK(self != NULL);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700720 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700721 // Find the class in the loaded classes table.
722 Class* klass = LookupClass(descriptor, class_loader);
723 if (klass == NULL) {
724 // Class is not yet loaded.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700725 if (descriptor[0] == '[' && descriptor[1] != '\0') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700726 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700727 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700728 const DexFile::ClassPath& class_path = ((class_loader != NULL)
729 ? ClassLoader::GetClassPath(class_loader)
730 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700731 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700732 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700733 std::string name(PrintableString(descriptor));
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700734 ThrowNoClassDefFoundError("Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700735 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700736 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700737 const DexFile& dex_file = *pair.first;
738 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700739 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700740 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700741 if (!init_done_) {
742 // finish up init of hand crafted class_roots_
743 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700744 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700745 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700746 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400747 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700748 klass = GetClassRoot(kJavaLangString);
Elliott Hughes80609252011-09-23 17:24:51 -0700749 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
750 klass = GetClassRoot(kJavaLangReflectConstructor);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700751 } else if (descriptor == "Ljava/lang/reflect/Field;") {
752 klass = GetClassRoot(kJavaLangReflectField);
753 } else if (descriptor == "Ljava/lang/reflect/Method;") {
754 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700755 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700756 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700757 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700758 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700759 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700760 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700761 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700762 klass->SetDexCache(dex_cache);
763 LoadClass(dex_file, dex_class_def, klass, class_loader);
764 // Check for a pending exception during load
765 if (self->IsExceptionPending()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700766 return NULL;
767 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700768 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700769 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700770 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700771 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700772 if (!success) {
773 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700774 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700775 klass = LookupClass(descriptor, class_loader);
776 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700777 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700778 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700779 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700780 CHECK(!klass->IsLoaded());
781 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700782 // Loading failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700783 CHECK(self->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700784 lock.NotifyAll();
785 return NULL;
786 }
787 CHECK(klass->IsLoaded());
788 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700789 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700790 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700791 // Linking failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700792 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700793 lock.NotifyAll();
794 return NULL;
795 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700796 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700797 }
798 }
799 }
800 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700801 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700802 ObjectLock lock(klass);
803 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700804 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700805 self->ThrowNewException("Ljava/lang/ClassCircularityError;", "%s",
806 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700807 return NULL;
808 }
809 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700810 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700811 lock.Wait();
812 }
813 }
814 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700815 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700816 return NULL;
817 }
818 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700819 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700820 CHECK(!self->IsExceptionPending());
821 return klass;
822}
823
Brian Carlstrom4873d462011-08-21 15:23:39 -0700824// Precomputes size that will be needed for Class, matching LinkStaticFields
825size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
826 const DexFile::ClassDef& dex_class_def) {
827 const byte* class_data = dex_file.GetClassData(dex_class_def);
828 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
829 size_t num_static_fields = header.static_fields_size_;
830 size_t num_ref = 0;
831 size_t num_32 = 0;
832 size_t num_64 = 0;
833 if (num_static_fields != 0) {
834 uint32_t last_idx = 0;
835 for (size_t i = 0; i < num_static_fields; ++i) {
836 DexFile::Field dex_field;
837 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
838 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
839 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
840 char c = descriptor[0];
841 if (c == 'L' || c == '[') {
842 num_ref++;
843 } else if (c == 'J' || c == 'D') {
844 num_64++;
845 } else {
846 num_32++;
847 }
848 }
849 }
850
851 // start with generic class data
852 size_t size = sizeof(Class);
853 // follow with reference fields which must be contiguous at start
854 size += (num_ref * sizeof(uint32_t));
855 // if there are 64-bit fields to add, make sure they are aligned
856 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
857 if (num_32 != 0) {
858 // use an available 32-bit field for padding
859 num_32--;
860 }
861 size += sizeof(uint32_t); // either way, we are adding a word
862 DCHECK_EQ(size, RoundUp(size, 8));
863 }
864 // tack on any 64-bit fields now that alignment is assured
865 size += (num_64 * sizeof(uint64_t));
866 // tack on any remaining 32-bit fields
867 size += (num_32 * sizeof(uint32_t));
868 return size;
869}
870
Brian Carlstromf615a612011-07-23 12:50:34 -0700871void ClassLinker::LoadClass(const DexFile& dex_file,
872 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700873 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700874 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700875 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700876 CHECK(klass->GetDexCache() != NULL);
877 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700878 const byte* class_data = dex_file.GetClassData(dex_class_def);
879 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700880
Brian Carlstromf615a612011-07-23 12:50:34 -0700881 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700882 CHECK(descriptor != NULL);
883
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700884 klass->SetClass(GetClassRoot(kJavaLangClass));
885 if (klass->GetDescriptor() != NULL) {
886 DCHECK(klass->GetDescriptor()->Equals(descriptor));
887 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700888 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700889 }
890 uint32_t access_flags = dex_class_def.access_flags_;
891 // Make sure there aren't any "bonus" flags set, since we use them for runtime
892 // state.
893 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
894 klass->SetAccessFlags(access_flags);
895 klass->SetClassLoader(class_loader);
896 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
897 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700898
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700899 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700900
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700901 size_t num_static_fields = header.static_fields_size_;
902 size_t num_instance_fields = header.instance_fields_size_;
903 size_t num_direct_methods = header.direct_methods_size_;
904 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700905
Brian Carlstromc74255f2011-09-11 22:47:39 -0700906 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700907
908 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700909 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700910
911 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700912 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700913 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700914 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700915 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700916 DexFile::Field dex_field;
917 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400918 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700919 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700920 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700921 }
922 }
923
924 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700925 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700926 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700927 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700928 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700929 DexFile::Field dex_field;
930 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400931 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700932 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700933 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700934 }
935 }
936
937 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700938 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700939 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700940 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
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_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700943 DexFile::Method dex_method;
944 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700945 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700946 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700947 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700948 // TODO: register maps
949 }
950 }
951
952 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700953 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700954 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700955 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700956 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700957 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700958 DexFile::Method dex_method;
959 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700960 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700961 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700962 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700963 // TODO: register maps
964 }
965 }
Brian Carlstrom934486c2011-07-12 23:42:50 -0700966}
967
Brian Carlstromf615a612011-07-23 12:50:34 -0700968void ClassLinker::LoadInterfaces(const DexFile& dex_file,
969 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700970 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700971 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700972 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700973 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700974 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
975 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700976 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700977 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700978 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700979 }
980 }
981}
982
Brian Carlstromf615a612011-07-23 12:50:34 -0700983void ClassLinker::LoadField(const DexFile& dex_file,
984 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700985 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -0700986 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700987 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700988 dst->SetDeclaringClass(klass);
989 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
990 dst->SetTypeIdx(field_id.type_idx_);
991 dst->SetAccessFlags(src.access_flags_);
992
993 // In order to access primitive types using GetTypeDuringLinking we need to
994 // ensure they are resolved into the dex cache
995 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
996 if (descriptor[1] == '\0') {
997 // only the descriptors of primitive types should be 1 character long
998 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
999 DCHECK(resolved->IsPrimitive());
1000 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001001}
1002
Brian Carlstromf615a612011-07-23 12:50:34 -07001003void ClassLinker::LoadMethod(const DexFile& dex_file,
1004 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001005 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001006 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001007 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001008 dst->SetDeclaringClass(klass);
Elliott Hughes80609252011-09-23 17:24:51 -07001009 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
1010 dst->SetName(method_name);
1011 if (method_name->Equals("<init>")) {
1012 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1013 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001014 {
1015 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -07001016 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Brian Carlstromc74255f2011-09-11 22:47:39 -07001017 dst->SetSignature(intern_table_->InternStrong(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001018 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001019 dst->SetProtoIdx(method_id.proto_idx_);
1020 dst->SetCodeItemOffset(src.code_off_);
1021 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -07001022 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001023 dst->SetAccessFlags(src.access_flags_);
1024 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001025
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001026 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1027 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1028 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1029 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1030 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1031 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001032
Brian Carlstrom934486c2011-07-12 23:42:50 -07001033 // TODO: check for finalize method
1034
Brian Carlstromf615a612011-07-23 12:50:34 -07001035 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001036 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001037 dst->SetNumRegisters(code_item->registers_size_);
1038 dst->SetNumIns(code_item->ins_size_);
1039 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001040 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001041 uint16_t num_args = Method::NumArgRegisters(shorty);
1042 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001043 ++num_args;
1044 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001045 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001046 // TODO: native methods
1047 }
1048}
1049
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001050void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001051 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1052}
1053
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001054void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001055 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001056 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001057 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001058}
1059
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001060void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001061 RegisterDexFile(dex_file, AllocDexCache(dex_file));
1062}
1063
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001064void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -07001065 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001066 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1067 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001068 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001069 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001070}
1071
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001072const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001073 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001074 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1075 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001076 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001077 }
1078 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001079 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001080 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001081}
1082
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001083DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001084 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001085 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001086 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001087 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001088 }
1089 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001090 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001091 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001092}
1093
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001094Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1095 const char* descriptor,
1096 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001097 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001098 CHECK(primitive_class != NULL);
1099 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1100 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
1101 primitive_class->SetPrimitiveType(type);
1102 primitive_class->SetStatus(Class::kStatusInitialized);
1103 bool success = InsertClass(descriptor, primitive_class);
1104 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1105 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001106}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001107
Brian Carlstrombe977852011-07-19 14:54:54 -07001108// Create an array class (i.e. the class object for the array, not the
1109// array itself). "descriptor" looks like "[C" or "[[[[B" or
1110// "[Ljava/lang/String;".
1111//
1112// If "descriptor" refers to an array of primitives, look up the
1113// primitive type's internally-generated class object.
1114//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001115// "class_loader" is the class loader of the class that's referring to
1116// us. It's used to ensure that we're looking for the element type in
1117// the right context. It does NOT become the class loader for the
1118// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001119//
1120// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001121Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001122 const ClassLoader* class_loader) {
1123 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001124
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001125 // Identify the underlying component type
1126 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001127 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001128 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001129 return NULL;
1130 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001131
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001132 // See if the component type is already loaded. Array classes are
1133 // always associated with the class loader of their underlying
1134 // element type -- an array of Strings goes with the loader for
1135 // java/lang/String -- so we need to look for it there. (The
1136 // caller should have checked for the existence of the class
1137 // before calling here, but they did so with *their* class loader,
1138 // not the component type's loader.)
1139 //
1140 // If we find it, the caller adds "loader" to the class' initiating
1141 // loader list, which should prevent us from going through this again.
1142 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001143 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001144 // are the same, because our caller (FindClass) just did the
1145 // lookup. (Even if we get this wrong we still have correct behavior,
1146 // because we effectively do this lookup again when we add the new
1147 // class to the hash table --- necessary because of possible races with
1148 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001149 if (class_loader != component_type->GetClassLoader()) {
1150 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001151 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001152 return new_class;
1153 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001154 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001155
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001156 // Fill out the fields in the Class.
1157 //
1158 // It is possible to execute some methods against arrays, because
1159 // all arrays are subclasses of java_lang_Object_, so we need to set
1160 // up a vtable. We can just point at the one in java_lang_Object_.
1161 //
1162 // Array classes are simple enough that we don't need to do a full
1163 // link step.
1164
1165 Class* new_class = NULL;
1166 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001167 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001168 if (descriptor == "[Ljava/lang/Class;") {
1169 new_class = GetClassRoot(kClassArrayClass);
1170 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001171 new_class = GetClassRoot(kObjectArrayClass);
1172 } else if (descriptor == "[C") {
1173 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001174 } else if (descriptor == "[I") {
1175 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001176 }
1177 }
1178 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001179 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001180 if (new_class == NULL) {
1181 return NULL;
1182 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001183 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001184 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001185 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001186 if (new_class->GetDescriptor() != NULL) {
1187 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1188 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001189 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001190 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001191 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001192 new_class->SetSuperClass(java_lang_Object);
1193 new_class->SetVTable(java_lang_Object->GetVTable());
1194 new_class->SetPrimitiveType(Class::kPrimNot);
1195 new_class->SetClassLoader(component_type->GetClassLoader());
1196 new_class->SetStatus(Class::kStatusInitialized);
1197 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001198 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001199
1200
1201 // All arrays have java/lang/Cloneable and java/io/Serializable as
1202 // interfaces. We need to set that up here, so that stuff like
1203 // "instanceof" works right.
1204 //
1205 // Note: The GC could run during the call to FindSystemClass,
1206 // so we need to make sure the class object is GC-valid while we're in
1207 // there. Do this by clearing the interface list so the GC will just
1208 // think that the entries are null.
1209
1210
1211 // Use the single, global copies of "interfaces" and "iftable"
1212 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001213 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001214 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001215
1216 // Inherit access flags from the component type. Arrays can't be
1217 // used as a superclass or interface, so we want to add "final"
1218 // and remove "interface".
1219 //
1220 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001221 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001222 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001223 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1224 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001225
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001226 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001227 return new_class;
1228 }
1229 // Another thread must have loaded the class after we
1230 // started but before we finished. Abandon what we've
1231 // done.
1232 //
1233 // (Yes, this happens.)
1234
1235 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001236 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001237 DCHECK(other_class != NULL);
1238 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001239}
1240
1241Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001242 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001243 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001244 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001245 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001246 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001247 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001248 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001249 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001250 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001251 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001252 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001253 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001254 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001255 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001256 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001257 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001258 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001259 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001260 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001261 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001262 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001263 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001264 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001265}
1266
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001267bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1268 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001269 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001270 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001271 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001272}
1273
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001274Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001275 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001276 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001277 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001278 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001279 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001280 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001281 return klass;
1282 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001283 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001284 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001285}
1286
jeffhao98eacac2011-09-14 16:11:53 -07001287void ClassLinker::VerifyClass(Class* klass) {
1288 if (klass->IsVerified()) {
1289 return;
1290 }
1291
1292 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001293 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001294
jeffhao5cfd6fb2011-09-27 13:54:29 -07001295 if (DexVerifier::VerifyClass(klass)) {
1296 klass->SetStatus(Class::kStatusVerified);
1297 } else {
1298 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
1299 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1300
1301 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
1302 klass->SetStatus(Class::kStatusResolved);
1303 }
jeffhao98eacac2011-09-14 16:11:53 -07001304}
1305
Brian Carlstrom25c33252011-09-18 15:58:35 -07001306bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001307 CHECK(klass->IsResolved() || klass->IsErroneous())
1308 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001309
Carl Shapirob5573532011-07-12 18:22:59 -07001310 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001311
Brian Carlstrom25c33252011-09-18 15:58:35 -07001312 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001313 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001314 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001315 ObjectLock lock(klass);
1316
Brian Carlstromd1422f82011-09-28 11:37:09 -07001317 if (klass->GetStatus() == Class::kStatusInitialized) {
1318 return true;
1319 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001320
Brian Carlstromd1422f82011-09-28 11:37:09 -07001321 if (klass->IsErroneous()) {
1322 ThrowEarlierClassFailure(klass);
1323 return false;
1324 }
1325
1326 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001327 VerifyClass(klass);
1328 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001329 return false;
1330 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001331 }
1332
Brian Carlstrom25c33252011-09-18 15:58:35 -07001333 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1334 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001335 // if the class has a <clinit> but we can't run it during compilation,
1336 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001337 return false;
1338 }
1339
Brian Carlstromd1422f82011-09-28 11:37:09 -07001340 // If the class is kStatusInitializing, either this thread is
1341 // initializing higher up the stack or another thread has beat us
1342 // to initializing and we need to wait. Either way, this
1343 // invocation of InitializeClass will not be responsible for
1344 // running <clinit> and will return.
1345 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001346 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001347 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001348 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001349 return true;
1350 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001351 // No. That's fine. Wait for another thread to finish initializing.
1352 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001353 }
1354
1355 if (!ValidateSuperClassDescriptors(klass)) {
1356 klass->SetStatus(Class::kStatusError);
1357 return false;
1358 }
1359
Brian Carlstromd1422f82011-09-28 11:37:09 -07001360 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001361
Elliott Hughesdcc24742011-09-07 14:02:44 -07001362 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001363 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001364 }
1365
Brian Carlstrom25c33252011-09-18 15:58:35 -07001366 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001367 return false;
1368 }
1369
1370 InitializeStaticFields(klass);
1371
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001372 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001373 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001374 }
1375
1376 {
1377 ObjectLock lock(klass);
1378
1379 if (self->IsExceptionPending()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001380 // TODO: if self->GetException() is not an Error,
1381 // wrap in ExceptionInInitializerError
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001382 klass->SetStatus(Class::kStatusError);
1383 } else {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001384 ++Runtime::Current()->GetStats()->class_init_count;
1385 ++self->GetStats()->class_init_count;
1386 // TODO: class_init_time_ns
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001387 klass->SetStatus(Class::kStatusInitialized);
1388 }
1389 lock.NotifyAll();
1390 }
1391
1392 return true;
1393}
1394
Brian Carlstromd1422f82011-09-28 11:37:09 -07001395bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1396 while (true) {
1397 CHECK(!self->IsExceptionPending());
1398 lock.Wait();
1399
1400 // When we wake up, repeat the test for init-in-progress. If
1401 // there's an exception pending (only possible if
1402 // "interruptShouldThrow" was set), bail out.
1403 if (self->IsExceptionPending()) {
1404 // TODO: set cause of ExceptionInInitializerError to self->GetException()
1405 self->ThrowNewException("Ljava/lang/ExceptionInInitializerError;",
1406 "Exception %s thrown while initializing class %s",
1407 PrettyTypeOf(self->GetException()).c_str(),
1408 PrettyDescriptor(klass->GetDescriptor()).c_str());
1409 klass->SetStatus(Class::kStatusError);
1410 return false;
1411 }
1412 // Spurious wakeup? Go back to waiting.
1413 if (klass->GetStatus() == Class::kStatusInitializing) {
1414 continue;
1415 }
1416 if (klass->IsErroneous()) {
1417 // The caller wants an exception, but it was thrown in a
1418 // different thread. Synthesize one here.
1419 self->ThrowNewException("Ljava/lang/NoClassDefFoundError;",
1420 "<clinit> failed for class %s; see exception in other thread",
1421 PrettyDescriptor(klass->GetDescriptor()).c_str());
1422 return false;
1423 }
1424 if (klass->IsInitialized()) {
1425 return true;
1426 }
1427 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1428 }
1429 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1430}
1431
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001432bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1433 if (klass->IsInterface()) {
1434 return true;
1435 }
1436 // begin with the methods local to the superclass
1437 if (klass->HasSuperClass() &&
1438 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1439 const Class* super = klass->GetSuperClass();
1440 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001441 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001442 if (method != super->GetVirtualMethod(i) &&
1443 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001444 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1445
1446 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 -07001447 return false;
1448 }
1449 }
1450 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001451 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1452 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1453 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001454 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1455 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001456 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001457 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001458 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001459 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1460
1461 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 -07001462 return false;
1463 }
1464 }
1465 }
1466 }
1467 return true;
1468}
1469
1470bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001471 const Class* klass1,
1472 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001473 if (method->IsMiranda()) {
1474 return true;
1475 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001476 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001477 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001478 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001479 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001480 const char* descriptor = it->GetDescriptor();
1481 if (descriptor == NULL) {
1482 break;
1483 }
1484 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1485 // Found a non-primitive type.
1486 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1487 return false;
1488 }
1489 }
1490 }
1491 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001492 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001493 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001494 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001495 return false;
1496 }
1497 }
1498 return true;
1499}
1500
1501// Returns true if classes referenced by the descriptor are the
1502// same classes in klass1 as they are in klass2.
1503bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001504 const Class* klass1,
1505 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001506 CHECK(descriptor != NULL);
1507 CHECK(klass1 != NULL);
1508 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001509 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001510 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001511 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001512 // TODO: found2 == NULL
1513 // TODO: lookup found1 in initiating loader list
1514 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001515 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001516 if (found1 == found2) {
1517 return true;
1518 } else {
1519 return false;
1520 }
1521 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001522 return true;
1523}
1524
Brian Carlstrom25c33252011-09-18 15:58:35 -07001525bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001526 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001527 if (!klass->IsInterface() && klass->HasSuperClass()) {
1528 Class* super_class = klass->GetSuperClass();
1529 if (super_class->GetStatus() != Class::kStatusInitialized) {
1530 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001531 Thread* self = Thread::Current();
1532 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001533 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001534 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001535 // TODO: check for a pending exception
1536 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001537 if (!can_run_clinit) {
1538 // Don't set status to error when we can't run <clinit>.
1539 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1540 klass->SetStatus(Class::kStatusVerified);
1541 return false;
1542 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001543 klass->SetStatus(Class::kStatusError);
1544 klass->NotifyAll();
1545 return false;
1546 }
1547 }
1548 }
1549 return true;
1550}
1551
Brian Carlstrom25c33252011-09-18 15:58:35 -07001552bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001553 CHECK(c != NULL);
1554 if (c->IsInitialized()) {
1555 return true;
1556 }
1557
Elliott Hughes5f791332011-09-15 17:45:30 -07001558 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001559 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001560 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001561 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001562}
1563
Brian Carlstromb9edb842011-08-28 16:31:06 -07001564StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1565 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001566 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1567 Class* klass = class_linker->ResolveType(type_idx, referrer);
1568 if (klass == NULL) {
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001569 CHECK(Thread::Current()->IsExceptionPending());
1570 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001571 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001572 // If we are the <clinit> of this class, just return our storage.
1573 //
1574 // Do not set the DexCache InitializedStaticStorage, since that
1575 // implies <clinit> has finished running.
1576 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1577 return klass;
1578 }
Brian Carlstrom25c33252011-09-18 15:58:35 -07001579 if (!class_linker->EnsureInitialized(klass, true)) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001580 CHECK(Thread::Current()->IsExceptionPending());
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001581 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001582 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001583 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001584 return klass;
1585}
1586
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001587void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1588 Class* c, std::map<int, Field*>& field_map) {
1589 const ClassLoader* cl = c->GetClassLoader();
1590 const byte* class_data = dex_file.GetClassData(dex_class_def);
1591 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1592 uint32_t last_idx = 0;
1593 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1594 DexFile::Field dex_field;
1595 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1596 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1597 }
1598}
1599
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001600void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001601 size_t num_static_fields = klass->NumStaticFields();
1602 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001603 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001604 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001605 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001606 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001607 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001608 return;
1609 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001610 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001611 const DexFile& dex_file = FindDexFile(dex_cache);
1612 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001613 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001614
1615 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1616 std::map<int, Field*> field_map;
1617 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1618
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001619 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001620 if (addr == NULL) {
1621 // All this class' static fields have default values.
1622 return;
1623 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001624 size_t array_size = DecodeUnsignedLeb128(&addr);
1625 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001626 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001627 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001628 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001629 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001630 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001631 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001632 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001633 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001634 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001635 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001636 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001637 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001638 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001639 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001640 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001641 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001642 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001643 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001644 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001645 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001646 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001647 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001648 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001649 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001650 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001651 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001652 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001653 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001654 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001655 break;
1656 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001657 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001658 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001659 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001660 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001661 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001662 break;
1663 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001664 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001665 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001666 }
1667}
1668
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001669bool ClassLinker::LinkClass(Class* klass) {
1670 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001671 if (!LinkSuperClass(klass)) {
1672 return false;
1673 }
1674 if (!LinkMethods(klass)) {
1675 return false;
1676 }
1677 if (!LinkInstanceFields(klass)) {
1678 return false;
1679 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001680 if (!LinkStaticFields(klass)) {
1681 return false;
1682 }
1683 CreateReferenceInstanceOffsets(klass);
1684 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001685 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1686 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001687 return true;
1688}
1689
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001690bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001691 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1692 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1693 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001694 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001695 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001696 return false;
1697 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001698 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001699 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001700 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1701 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07001702 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001703 klass->SetInterface(i, interface);
1704 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001705 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001706 return false;
1707 }
1708 // Verify
1709 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001710 // TODO: the RI seemed to ignore this in my testing.
1711 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessError;",
1712 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001713 PrettyDescriptor(interface->GetDescriptor()).c_str(),
1714 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001715 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001716 }
1717 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001718 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001719 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001720 return true;
1721}
1722
1723bool ClassLinker::LinkSuperClass(Class* klass) {
1724 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001725 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001726 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001727 if (super != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001728 Thread::Current()->ThrowNewException("Ljava/lang/ClassFormatError;",
1729 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001730 return false;
1731 }
1732 // TODO: clear finalize attribute
1733 return true;
1734 }
1735 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001736 ThrowLinkageError("No superclass defined for class %s",
1737 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001738 return false;
1739 }
1740 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001741 if (super->IsFinal() || super->IsInterface()) {
1742 Thread::Current()->ThrowNewException("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001743 "Superclass %s of %s is %s",
1744 PrettyDescriptor(super->GetDescriptor()).c_str(),
1745 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001746 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001747 return false;
1748 }
1749 if (!klass->CanAccess(super)) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001750 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001751 "Superclass %s is inaccessible by %s",
1752 PrettyDescriptor(super->GetDescriptor()).c_str(),
1753 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001754 return false;
1755 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001756#ifndef NDEBUG
1757 // Ensure super classes are fully resolved prior to resolving fields..
1758 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001759 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001760 super = super->GetSuperClass();
1761 }
1762#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001763 return true;
1764}
1765
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001766// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001767bool ClassLinker::LinkMethods(Class* klass) {
1768 if (klass->IsInterface()) {
1769 // No vtable.
1770 size_t count = klass->NumVirtualMethods();
1771 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001772 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001773 return false;
1774 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001775 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001776 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001777 }
jeffhaobdb76512011-09-07 11:43:16 -07001778 // Link interface method tables
1779 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001780 } else {
1781 // Link virtual method tables
1782 LinkVirtualMethods(klass);
1783
1784 // Link interface method tables
1785 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001786 }
1787 return true;
1788}
1789
1790bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001791 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001792 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1793 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001794 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001795 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001796 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001797 // See if any of our virtual methods override the superclass.
1798 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001799 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001800 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001801 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001802 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001803 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001804 // Verify
1805 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001806 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001807 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1808 local_method->GetName()->ToModifiedUtf8().c_str(),
1809 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001810 return false;
1811 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001812 vtable->Set(j, local_method);
1813 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001814 break;
1815 }
1816 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001817 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001818 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001819 vtable->Set(actual_count, local_method);
1820 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001821 actual_count += 1;
1822 }
1823 }
1824 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001825 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001826 return false;
1827 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001828 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001829 CHECK_LE(actual_count, max_count);
1830 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001831 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001832 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001833 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001834 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001835 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001836 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001837 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001838 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001839 return false;
1840 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001841 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001842 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001843 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1844 vtable->Set(i, virtual_method);
1845 virtual_method->SetMethodIndex(i & 0xFFFF);
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 }
1849 return true;
1850}
1851
1852bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001853 size_t super_ifcount;
1854 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001855 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001856 } else {
1857 super_ifcount = 0;
1858 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001859 size_t ifcount = super_ifcount;
1860 ifcount += klass->NumInterfaces();
1861 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001862 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001863 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001864 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001865 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001866 // DCHECK(klass->GetIfTableCount() == 0);
1867 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001868 return true;
1869 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001870 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001871 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001872 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1873 for (size_t i = 0; i < super_ifcount; i++) {
1874 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1875 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001876 }
1877 // Flatten the interface inheritance hierarchy.
1878 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001879 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001880 Class* interface = klass->GetInterface(i);
1881 DCHECK(interface != NULL);
1882 if (!interface->IsInterface()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001883 Thread::Current()->ThrowNewException("Ljava/lang/IncompatibleClassChangeError;",
1884 "Class %s implements non-interface class %s",
1885 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1886 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001887 return false;
1888 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001889 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001890 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07001891 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001892 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1893 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001894 }
1895 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001896 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001897 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07001898
1899 // If we're an interface, we don't need the vtable pointers, so we're done.
1900 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001901 return true;
1902 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001903 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001904 for (size_t i = 0; i < ifcount; ++i) {
1905 InterfaceEntry* interface_entry = iftable->Get(i);
1906 Class* interface = interface_entry->GetInterface();
1907 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1908 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001909 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001910 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1911 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001912 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07001913 // For each method listed in the interface's method list, find the
1914 // matching method in our class's method list. We want to favor the
1915 // subclass over the superclass, which just requires walking
1916 // back from the end of the vtable. (This only matters if the
1917 // superclass defines a private method and this class redefines
1918 // it -- otherwise it would use the same vtable slot. In .dex files
1919 // those don't end up in the virtual method table, so it shouldn't
1920 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001921 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1922 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001923 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1924 if (!vtable_method->IsPublic()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001925 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessError;",
1926 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001927 return false;
1928 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001929 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001930 break;
1931 }
1932 }
1933 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001934 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07001935 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
1936 if (miranda_list[mir]->HasSameNameAndDescriptor(interface_method)) {
1937 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001938 break;
1939 }
1940 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001941 if (miranda_method == NULL) {
1942 // point the interface table at a phantom slot
1943 miranda_method = AllocMethod();
1944 memcpy(miranda_method, interface_method, sizeof(Method));
1945 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001946 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001947 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001948 }
1949 }
1950 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001951 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001952 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07001953 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001954 klass->SetVirtualMethods((old_method_count == 0)
1955 ? AllocObjectArray<Method>(new_method_count)
1956 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001957
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001958 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1959 CHECK(vtable != NULL);
1960 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07001961 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001962 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07001963 for (size_t i = 0; i < miranda_list.size(); ++i) {
1964 Method* meth = miranda_list[i]; //AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001965 // TODO: this shouldn't be a memcpy
Elliott Hughes4681c802011-09-25 18:04:37 -07001966 //memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001967 meth->SetDeclaringClass(klass);
1968 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
1969 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001970 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001971 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001972 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001973 // TODO: do not assign to the vtable field until it is fully constructed.
1974 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001975 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001976
1977 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1978 for (int i = 0; i < vtable->GetLength(); ++i) {
1979 CHECK(vtable->Get(i) != NULL);
1980 }
1981
1982// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1983
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001984 return true;
1985}
1986
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001987bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001988 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001989 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001990}
1991
1992bool ClassLinker::LinkStaticFields(Class* klass) {
1993 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001994 size_t allocated_class_size = klass->GetClassSize();
1995 bool success = LinkFields(klass, false);
1996 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001997 return success;
1998}
1999
Brian Carlstromdbc05252011-09-09 01:59:59 -07002000struct LinkFieldsComparator {
2001 bool operator()(const Field* field1, const Field* field2){
2002
2003 // First come reference fields, then 64-bit, and finally 32-bit
2004 const Class* type1 = field1->GetTypeDuringLinking();
2005 const Class* type2 = field2->GetTypeDuringLinking();
2006 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2007 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2008 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2009 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2010 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2011 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2012 if (order1 != order2) {
2013 return order1 < order2;
2014 }
2015
2016 // same basic group? then sort by string.
2017 std::string name1 = field1->GetName()->ToModifiedUtf8();
2018 std::string name2 = field2->GetName()->ToModifiedUtf8();
2019 return name1 < name2;
2020 }
2021};
2022
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002023bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002024 size_t num_fields =
2025 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
2026
2027 ObjectArray<Field>* fields =
2028 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002029
2030 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002031 size_t size;
2032 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002033 if (instance) {
2034 Class* super_class = klass->GetSuperClass();
2035 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002036 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002037 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002038 }
2039 size = field_offset.Uint32Value();
2040 } else {
2041 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07002042 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002043 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002044
Brian Carlstromdbc05252011-09-09 01:59:59 -07002045 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002046
Brian Carlstromdbc05252011-09-09 01:59:59 -07002047 // we want a relatively stable order so that adding new fields
2048 // minimizes distruption of C++ version such as Class and Method.
2049 std::deque<Field*> grouped_and_sorted_fields;
2050 for (size_t i = 0; i < num_fields; i++) {
2051 grouped_and_sorted_fields.push_back(fields->Get(i));
2052 }
2053 std::sort(grouped_and_sorted_fields.begin(),
2054 grouped_and_sorted_fields.end(),
2055 LinkFieldsComparator());
2056
2057 // References should be at the front.
2058 size_t current_field = 0;
2059 size_t num_reference_fields = 0;
2060 for (; current_field < num_fields; current_field++) {
2061 Field* field = grouped_and_sorted_fields.front();
2062 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002063 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002064 bool isPrimitive = type != NULL && type->IsPrimitive();
2065 if (isPrimitive) {
2066 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002067 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002068 grouped_and_sorted_fields.pop_front();
2069 num_reference_fields++;
2070 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002071 field->SetOffset(field_offset);
2072 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002073 }
2074
2075 // Now we want to pack all of the double-wide fields together. If
2076 // we're not aligned, though, we want to shuffle one 32-bit field
2077 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002078 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2079 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2080 Field* field = grouped_and_sorted_fields[i];
2081 const Class* type = field->GetTypeDuringLinking();
2082 CHECK(type != NULL); // should only be working on primitive types
2083 DCHECK(type->IsPrimitive());
2084 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2085 continue;
2086 }
2087 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002088 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002089 // drop the consumed field
2090 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2091 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002092 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002093 // whether we found a 32-bit field for padding or not, we advance
2094 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002095 }
2096
2097 // Alignment is good, shuffle any double-wide fields forward, and
2098 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002099 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2100 while (!grouped_and_sorted_fields.empty()) {
2101 Field* field = grouped_and_sorted_fields.front();
2102 grouped_and_sorted_fields.pop_front();
2103 const Class* type = field->GetTypeDuringLinking();
2104 CHECK(type != NULL); // should only be working on primitive types
2105 DCHECK(type->IsPrimitive());
2106 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002107 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002108 field_offset = MemberOffset(field_offset.Uint32Value() +
2109 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2110 ? sizeof(uint64_t)
2111 : sizeof(uint32_t)));
2112 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002113 }
2114
2115#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002116 // Make sure that all reference fields appear before
2117 // non-reference fields, and all double-wide fields are aligned.
2118 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002119 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002120 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002121 if (false) { // enable to debug field layout
Brian Carlstrom845490b2011-09-19 15:56:53 -07002122 LOG(INFO) << "LinkFields: " << (instance ? "instance" : "static")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002123 << " class=" << PrettyClass(klass)
2124 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002125 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2126 }
2127 const Class* type = field->GetTypeDuringLinking();
2128 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002129 if (!seen_non_ref) {
2130 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002131 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002132 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002133 } else {
2134 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002135 }
2136 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002137 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002138 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002139 }
2140#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002141 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002142 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07002143 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002144 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002145 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002146 klass->SetObjectSize(size);
2147 }
2148 } else {
2149 klass->SetNumReferenceStaticFields(num_reference_fields);
2150 klass->SetClassSize(size);
2151 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002152 return true;
2153}
2154
2155// Set the bitmap of reference offsets, refOffsets, from the ifields
2156// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002157void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002158 uint32_t reference_offsets = 0;
2159 Class* super_class = klass->GetSuperClass();
2160 if (super_class != NULL) {
2161 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002162 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002163 if (reference_offsets == CLASS_WALK_SUPER) {
2164 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002165 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002166 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002167 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002168 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002169}
2170
2171void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002172 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002173}
2174
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002175void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2176 uint32_t reference_offsets) {
2177 size_t num_reference_fields =
2178 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2179 : klass->NumReferenceStaticFieldsDuringLinking();
2180 const ObjectArray<Field>* fields =
2181 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002182 // All of the fields that contain object references are guaranteed
2183 // to be at the beginning of the fields list.
2184 for (size_t i = 0; i < num_reference_fields; ++i) {
2185 // Note that byte_offset is the offset from the beginning of
2186 // object, not the offset into instance data
2187 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002188 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002189 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2190 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2191 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002192 CHECK_NE(new_bit, 0U);
2193 reference_offsets |= new_bit;
2194 } else {
2195 reference_offsets = CLASS_WALK_SUPER;
2196 break;
2197 }
2198 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002199 // Update fields in klass
2200 if (instance) {
2201 klass->SetReferenceInstanceOffsets(reference_offsets);
2202 } else {
2203 klass->SetReferenceStaticOffsets(reference_offsets);
2204 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002205}
2206
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002207String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002208 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002209 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002210 if (resolved != NULL) {
2211 return resolved;
2212 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002213 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2214 int32_t utf16_length = dex_file.GetStringLength(string_id);
2215 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002216 // TODO: remote the const_cast below
2217 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002218 dex_cache->SetResolvedString(string_idx, string);
2219 return string;
2220}
2221
2222Class* ClassLinker::ResolveType(const DexFile& dex_file,
2223 uint32_t type_idx,
2224 DexCache* dex_cache,
2225 const ClassLoader* class_loader) {
2226 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002227 if (resolved == NULL) {
2228 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2229 if (descriptor[1] == '\0') {
2230 // only the descriptors of primitive types should be 1 character long
2231 resolved = FindPrimitiveClass(descriptor[0]);
2232 } else {
2233 resolved = FindClass(descriptor, class_loader);
2234 }
2235 if (resolved != NULL) {
2236 Class* check = resolved->IsArrayClass() ? resolved->GetComponentType() : resolved;
2237 if (dex_cache != check->GetDexCache()) {
2238 if (check->GetClassLoader() != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002239 Thread::Current()->ThrowNewException("Ljava/lang/IllegalAccessError;",
2240 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002241 resolved = NULL;
2242 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002243 }
2244 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002245 if (resolved != NULL) {
2246 dex_cache->SetResolvedType(type_idx, resolved);
2247 } else {
2248 DCHECK(Thread::Current()->IsExceptionPending());
2249 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002250 }
2251 return resolved;
2252}
2253
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002254Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2255 uint32_t method_idx,
2256 DexCache* dex_cache,
2257 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002258 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002259 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2260 if (resolved != NULL) {
2261 return resolved;
2262 }
2263 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2264 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2265 if (klass == NULL) {
2266 return NULL;
2267 }
2268
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002269 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002270 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002271 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002272 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002273 } else if (klass->IsInterface()) {
2274 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002275 } else {
2276 resolved = klass->FindVirtualMethod(name, signature);
2277 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002278 if (resolved != NULL) {
2279 dex_cache->SetResolvedMethod(method_idx, resolved);
2280 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002281 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002282 }
2283 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002284}
2285
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002286Field* ClassLinker::ResolveField(const DexFile& dex_file,
2287 uint32_t field_idx,
2288 DexCache* dex_cache,
2289 const ClassLoader* class_loader,
2290 bool is_static) {
2291 Field* resolved = dex_cache->GetResolvedField(field_idx);
2292 if (resolved != NULL) {
2293 return resolved;
2294 }
2295 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2296 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2297 if (klass == NULL) {
2298 return NULL;
2299 }
2300
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002301 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002302 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002303 if (field_type == NULL) {
2304 // TODO: LinkageError?
2305 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2306 << " in " << PrettyClass(klass);
2307 return NULL;
2308}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002309 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002310 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002311 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002312 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002313 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002314 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002315 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002316 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002317 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002318 }
2319 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002320}
2321
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002322void ClassLinker::DumpAllClasses(int flags) const {
2323 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2324 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2325 std::vector<Class*> all_classes;
2326 {
2327 MutexLock mu(lock_);
2328 typedef Table::const_iterator It; // TODO: C++0x auto
2329 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2330 all_classes.push_back(it->second);
2331 }
2332 }
2333
2334 for (size_t i = 0; i < all_classes.size(); ++i) {
2335 all_classes[i]->DumpClass(std::cerr, flags);
2336 }
2337}
2338
Elliott Hughese27955c2011-08-26 15:21:24 -07002339size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002340 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002341 return classes_.size();
2342}
2343
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002344} // namespace art