blob: 6ebc6384d53949ced83023494e5ba93af8c589d3 [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 Carlstrom58ae9412011-10-04 00:56:06 -070019#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070020#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070021#include "runtime.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070022#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070023#include "space.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070024#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070026#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070028
29namespace art {
30
Elliott Hughes4a2b4172011-09-20 17:08:25 -070031namespace {
32
33void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
34void ThrowNoClassDefFoundError(const char* fmt, ...) {
35 va_list args;
36 va_start(args, fmt);
37 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
38 va_end(args);
39}
40
Elliott Hughese555dc02011-09-25 10:46:35 -070041void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
42void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070043 va_list args;
44 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070045 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070046 va_end(args);
47}
48
49void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
50void ThrowLinkageError(const char* fmt, ...) {
51 va_list args;
52 va_start(args, fmt);
53 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
54 va_end(args);
55}
56
Elliott Hughescc5f9a92011-09-28 19:17:29 -070057void ThrowNoSuchMethodError(const char* kind,
58 Class* c, const StringPiece& name, const StringPiece& signature) {
59 DexCache* dex_cache = c->GetDexCache();
60 std::stringstream msg;
61 msg << "no " << kind << " method " << name << "." << signature
62 << " in class " << c->GetDescriptor()->ToModifiedUtf8()
63 << " or its superclasses";
64 if (dex_cache) {
65 msg << " (defined in " << dex_cache->GetLocation()->ToModifiedUtf8() << ")";
66 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070067 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070068}
69
Elliott Hughes4a2b4172011-09-20 17:08:25 -070070void ThrowEarlierClassFailure(Class* c) {
71 /*
72 * The class failed to initialize on a previous attempt, so we want to throw
73 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
74 * failed in verification, in which case v2 5.4.1 says we need to re-throw
75 * the previous error.
76 */
77 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
78
79 if (c->GetVerifyErrorClass() != NULL) {
80 // TODO: change the verifier to store an _instance_, with a useful detail message?
81 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070082 Thread::Current()->ThrowNewException(error_descriptor.c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -070083 PrettyDescriptor(c->GetDescriptor()).c_str());
84 } else {
85 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
86 }
87}
88
Elliott Hughes4d0207c2011-10-03 19:14:34 -070089void WrapExceptionInInitializer() {
90 JNIEnv* env = Thread::Current()->GetJniEnv();
91
92 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
93 CHECK(cause.get() != NULL);
94
95 env->ExceptionClear();
96
97 // TODO: add java.lang.Error to JniConstants?
98 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
99 CHECK(error_class.get() != NULL);
100 if (env->IsInstanceOf(cause.get(), error_class.get())) {
101 // We only wrap non-Error exceptions; an Error can just be used as-is.
102 env->Throw(cause.get());
103 return;
104 }
105
106 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
107 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
108 CHECK(eiie_class.get() != NULL);
109
110 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
111 CHECK(mid != NULL);
112
113 ScopedLocalRef<jthrowable> eiie(env,
114 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
115 env->Throw(eiie.get());
116}
117
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118}
119
Elliott Hughes418d20f2011-09-22 14:00:39 -0700120const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700121 "Ljava/lang/Class;",
122 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700123 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700124 "[Ljava/lang/Object;",
125 "Ljava/lang/String;",
Elliott Hughes80609252011-09-23 17:24:51 -0700126 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700127 "Ljava/lang/reflect/Field;",
128 "Ljava/lang/reflect/Method;",
129 "Ljava/lang/ClassLoader;",
130 "Ldalvik/system/BaseDexClassLoader;",
131 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700132 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700133 "Z",
134 "B",
135 "C",
136 "D",
137 "F",
138 "I",
139 "J",
140 "S",
141 "V",
142 "[Z",
143 "[B",
144 "[C",
145 "[D",
146 "[F",
147 "[I",
148 "[J",
149 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700150 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700151};
152
Elliott Hughes5f791332011-09-15 17:45:30 -0700153class ObjectLock {
154 public:
155 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
156 CHECK(object != NULL);
157 obj_->MonitorEnter(self_);
158 }
159
160 ~ObjectLock() {
161 obj_->MonitorExit(self_);
162 }
163
164 void Wait() {
165 return Monitor::Wait(self_, obj_, 0, 0, false);
166 }
167
168 void Notify() {
169 obj_->Notify();
170 }
171
172 void NotifyAll() {
173 obj_->NotifyAll();
174 }
175
176 private:
177 Thread* self_;
178 Object* obj_;
179 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
180};
181
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700182ClassLinker* ClassLinker::Create(const std::string& boot_class_path,
183 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700184 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700185 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700186 class_linker->Init(boot_class_path);
187 return class_linker.release();
188}
189
190ClassLinker* ClassLinker::Create(InternTable* intern_table) {
191 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
192 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700193 return class_linker.release();
194}
195
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700196ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700197 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700198 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199 array_interfaces_(NULL),
200 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700201 init_done_(false),
202 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700203 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700204}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700205
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700206void CreateClassPath(const std::string& class_path,
207 std::vector<const DexFile*>& class_path_vector) {
208 std::vector<std::string> parsed;
209 Split(class_path, ':', parsed);
210 for (size_t i = 0; i < parsed.size(); ++i) {
211 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
212 if (dex_file != NULL) {
213 class_path_vector.push_back(dex_file);
214 }
215 }
216}
217
218void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700219 const Runtime* runtime = Runtime::Current();
220 if (runtime->IsVerboseStartup()) {
221 LOG(INFO) << "ClassLinker::InitFrom entering";
222 }
223
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700224 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700225
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700226 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700227 Class* java_lang_Class = down_cast<Class*>(
228 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700229 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700230 java_lang_Class->SetClass(java_lang_Class);
231 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700232 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700233
Elliott Hughes418d20f2011-09-22 14:00:39 -0700234 // Class[] is used for reflection support.
235 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
236 class_array_class->SetComponentType(java_lang_Class);
237
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700238 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700239 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700240 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700241 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 java_lang_Class->SetSuperClass(java_lang_Object);
243 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700244
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700245 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700246 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700247 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700248
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700249 // Setup the char class to be used for char[]
250 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
251
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700252 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700253 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700254 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700255 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700256
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700257 // Setup String
258 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
259 String::SetClass(java_lang_String);
260 java_lang_String->SetObjectSize(sizeof(String));
261 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400262
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700264 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
265 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700266 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700267 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
268 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
269 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700270
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 // Create storage for root classes, save away our work so far (requires
272 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700273 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700274 SetClassRoot(kJavaLangClass, java_lang_Class);
275 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700276 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700277 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700278 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700279 SetClassRoot(kJavaLangString, java_lang_String);
280
281 // Setup the primitive type classes.
282 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
283 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
285 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
286 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
287 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
288 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
289 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
290
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700291 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700292 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700293 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294
295 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
296 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700297 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
299 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700300 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700302 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700303
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700304 // setup boot_class_path_ and register class_path now that we can
305 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700306 std::vector<const DexFile*> boot_class_path_vector;
307 CreateClassPath(boot_class_path, boot_class_path_vector);
308 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
309 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700310 CHECK(dex_file != NULL);
311 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700312 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313
Elliott Hughes80609252011-09-23 17:24:51 -0700314 // Constructor, Field, and Method are necessary so that FindClass can link members
315 Class* java_lang_reflect_Constructor = AllocClass(java_lang_Class, sizeof(MethodClass));
316 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
317 CHECK(java_lang_reflect_Constructor != NULL);
318 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
319 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor);
320 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
321
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
323 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700324 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700325 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
326 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
327 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
328 Field::SetClass(java_lang_reflect_Field);
329
330 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Elliott Hughes80609252011-09-23 17:24:51 -0700331 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332 CHECK(java_lang_reflect_Method != NULL);
333 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
334 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
335 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Elliott Hughes80609252011-09-23 17:24:51 -0700336 Method::SetClasses(java_lang_reflect_Constructor, java_lang_reflect_Method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337
338 // now we can use FindSystemClass
339
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700340 // run char class through InitializePrimitiveClass to finish init
341 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
342 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
343
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700344 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345 java_lang_Object->SetStatus(Class::kStatusNotReady);
346 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
347 CHECK_EQ(java_lang_Object, Object_class);
348 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
349 java_lang_String->SetStatus(Class::kStatusNotReady);
350 Class* String_class = FindSystemClass("Ljava/lang/String;");
351 CHECK_EQ(java_lang_String, String_class);
352 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
353
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700354 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
356 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
357
358 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
359 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
360
361 Class* found_char_array_class = FindSystemClass("[C");
362 CHECK_EQ(char_array_class, found_char_array_class);
363
364 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
365 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
366
367 Class* found_int_array_class = FindSystemClass("[I");
368 CHECK_EQ(int_array_class, found_int_array_class);
369
370 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
371 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
372
373 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
374 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
375
376 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
377 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
378
Elliott Hughes418d20f2011-09-22 14:00:39 -0700379 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
380 CHECK_EQ(class_array_class, found_class_array_class);
381
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
383 CHECK_EQ(object_array_class, found_object_array_class);
384
385 // Setup the single, global copies of "interfaces" and "iftable"
386 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
387 CHECK(java_lang_Cloneable != NULL);
388 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
389 CHECK(java_io_Serializable != NULL);
390 CHECK(array_interfaces_ != NULL);
391 array_interfaces_->Set(0, java_lang_Cloneable);
392 array_interfaces_->Set(1, java_io_Serializable);
393 // We assume that Cloneable/Serializable don't have superinterfaces --
394 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700395 // supers as well.
396 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
397 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398
Elliott Hughes418d20f2011-09-22 14:00:39 -0700399 // Sanity check Class[] and Object[]'s interfaces
400 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
401 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700402 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
403 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700404
Elliott Hughes80609252011-09-23 17:24:51 -0700405 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700406 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700407 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700408 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409
Elliott Hughes80609252011-09-23 17:24:51 -0700410 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
411 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
412 CHECK_EQ(java_lang_reflect_Constructor, Constructor_class);
413
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700415 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700416 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700417
418 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700419 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700420 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700421
422 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
423 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700424 java_lang_ref_FinalizerReference->SetAccessFlags(
425 java_lang_ref_FinalizerReference->GetAccessFlags() |
426 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700427 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428 java_lang_ref_PhantomReference->SetAccessFlags(
429 java_lang_ref_PhantomReference->GetAccessFlags() |
430 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700431 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700432 java_lang_ref_SoftReference->SetAccessFlags(
433 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700434 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435 java_lang_ref_WeakReference->SetAccessFlags(
436 java_lang_ref_WeakReference->GetAccessFlags() |
437 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700438
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700439 // Setup the ClassLoaders, adjusting the object_size_ as necessary
440 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
441 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
442 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
443 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
444
445 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
446 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
447 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
448
449 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
450 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
451 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
452 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
453
454 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700455 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
456 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700457 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700458
Brian Carlstroma663ea52011-08-19 23:33:41 -0700459 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700460
461 if (runtime->IsVerboseStartup()) {
462 LOG(INFO) << "ClassLinker::InitFrom exiting";
463 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700464}
465
466void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700467 const Runtime* runtime = Runtime::Current();
468 if (runtime->IsVerboseStartup()) {
469 LOG(INFO) << "ClassLinker::FinishInit entering";
470 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700471
472 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700473 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700474 // as the types of the field can't be resolved prior to the runtime being
475 // fully initialized
476 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
477 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
478
479 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
480 CHECK(pendingNext->GetName()->Equals("pendingNext"));
481 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
482
483 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
484 CHECK(queue->GetName()->Equals("queue"));
485 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
486 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
487
488 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
489 CHECK(queueNext->GetName()->Equals("queueNext"));
490 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
491
492 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
493 CHECK(referent->GetName()->Equals("referent"));
494 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
495
496 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
497 CHECK(zombie->GetName()->Equals("zombie"));
498 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
499
500 Heap::SetReferenceOffsets(referent->GetOffset(),
501 queue->GetOffset(),
502 queueNext->GetOffset(),
503 pendingNext->GetOffset(),
504 zombie->GetOffset());
505
Brian Carlstroma663ea52011-08-19 23:33:41 -0700506 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700507 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700508 ClassRoot class_root = static_cast<ClassRoot>(i);
509 Class* klass = GetClassRoot(class_root);
510 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700512 // note SetClassRoot does additional validation.
513 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700514 }
515
516 // disable the slow paths in FindClass and CreatePrimitiveClass now
517 // that Object, Class, and Object[] are setup
518 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700519
520 if (runtime->IsVerboseStartup()) {
521 LOG(INFO) << "ClassLinker::FinishInit exiting";
522 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700523}
524
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700525void ClassLinker::RunRootClinits() {
526 Thread* self = Thread::Current();
527 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
528 Class* c = GetClassRoot(ClassRoot(i));
529 if (!c->IsArrayClass() && !c->IsPrimitive()) {
530 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
531 CHECK(!self->IsExceptionPending());
532 }
533 }
534}
535
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700536OatFile* ClassLinker::OpenOat(const Space* space) {
537 const Runtime* runtime = Runtime::Current();
538 if (runtime->IsVerboseStartup()) {
539 LOG(INFO) << "ClassLinker::OpenOat entering";
540 }
541 const ImageHeader& image_header = space->GetImageHeader();
542 String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
543 std::string oat_filename;
544 oat_filename += runtime->GetHostPrefix();
545 oat_filename += oat_location->ToModifiedUtf8();
546 OatFile* oat_file = OatFile::Open(std::string(oat_filename), "", image_header.GetOatBaseAddr());
547 if (oat_file == NULL) {
548 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image";
549 return NULL;
550 }
551 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
552 uint32_t image_oat_checksum = image_header.GetOatChecksum();
553 if (oat_checksum != image_oat_checksum) {
554 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
555 << " to expected oat checksum " << std::hex << oat_checksum
556 << " in image";
557 return NULL;
558 }
559 oat_files_.push_back(oat_file);
560 if (runtime->IsVerboseStartup()) {
561 LOG(INFO) << "ClassLinker::OpenOat exiting";
562 }
563 return oat_file;
564}
565
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700566void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700567 const Runtime* runtime = Runtime::Current();
568 if (runtime->IsVerboseStartup()) {
569 LOG(INFO) << "ClassLinker::InitFromImage entering";
570 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700571 CHECK(!init_done_);
572
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700573 const std::vector<Space*>& spaces = Heap::GetSpaces();
574 for (size_t i = 0; i < spaces.size(); i++) {
575 Space* space = spaces[i] ;
576 if (space->IsImageSpace()) {
577 OatFile* oat_file = OpenOat(space);
578 CHECK(oat_file != NULL) << "Failed to open oat file for image";
579 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
580 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
581
582 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
583 static_cast<uint32_t>(dex_caches->GetLength()));
584 for (int i = 0; i < dex_caches->GetLength(); i++) {
585 DexCache* dex_cache = dex_caches->Get(i);
586 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
587
588 std::string dex_filename;
589 dex_filename += runtime->GetHostPrefix();
590 dex_filename += dex_file_location;
591 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
592 if (dex_file == NULL) {
593 LOG(FATAL) << "Failed to open dex file " << dex_filename
594 << " referenced from oat file as " << dex_file_location;
595 }
596
597 const OatFile::OatDexFile& oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
598 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file.GetDexFileChecksum());
599
600 RegisterDexFile(*dex_file, dex_cache);
601 }
602 }
603 }
604
Brian Carlstroma663ea52011-08-19 23:33:41 -0700605 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
606 DCHECK(heap_bitmap != NULL);
607
Brian Carlstroma663ea52011-08-19 23:33:41 -0700608 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700609 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700610
611 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700612 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
613 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700614
Brian Carlstroma663ea52011-08-19 23:33:41 -0700615 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700616 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
617 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700618
Brian Carlstroma663ea52011-08-19 23:33:41 -0700619 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700620 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700621 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700622 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
623 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
624 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
625 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
626 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
627 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
628 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
629 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700630 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700631 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700632
633 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700634
635 if (runtime->IsVerboseStartup()) {
636 LOG(INFO) << "ClassLinker::InitFromImage exiting";
637 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700638}
639
Brian Carlstrom78128a62011-09-15 17:21:19 -0700640void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700641 DCHECK(obj != NULL);
642 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700643 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700644
Brian Carlstromc74255f2011-09-11 22:47:39 -0700645 if (obj->IsString()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700646 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700647 return;
648 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700649 if (!obj->IsClass()) {
650 return;
651 }
652 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700653 // TODO: restore ClassLoader's list of DexFiles after image load
654 // CHECK(klass->GetClassLoader() == NULL);
655 const ClassLoader* class_loader = klass->GetClassLoader();
656 if (class_loader != NULL) {
657 // TODO: replace this hack with something based on command line arguments
658 Thread::Current()->SetClassLoaderOverride(class_loader);
659 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700660
661 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700662 // restore class to ClassLinker::classes_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700663 class_linker->InsertClass(descriptor, klass);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700664}
665
666// Keep in sync with InitCallback. Anything we visit, we need to
667// reinit references to when reinitializing a ClassLinker from a
668// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700669void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
670 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700671
672 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700673 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700674 }
675
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700676 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700677 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700678 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700679 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700680 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700681 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700682 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700683
Elliott Hughes410c0c82011-09-01 17:58:25 -0700684 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700685}
686
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700687ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700688 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700689 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700690 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700691 BooleanArray::ResetArrayClass();
692 ByteArray::ResetArrayClass();
693 CharArray::ResetArrayClass();
694 DoubleArray::ResetArrayClass();
695 FloatArray::ResetArrayClass();
696 IntArray::ResetArrayClass();
697 LongArray::ResetArrayClass();
698 ShortArray::ResetArrayClass();
699 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700700 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700701 STLDeleteElements(&boot_class_path_);
702 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700703}
704
705DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700706 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700707 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700708 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700709 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700710 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700711 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700712 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
713 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700714 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700715}
716
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700717CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
718 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700719}
720
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700721InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
722 DCHECK(interface->IsInterface());
723 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
724 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
725 interface_entry->SetInterface(interface);
726 return interface_entry;
727}
728
Brian Carlstrom4873d462011-08-21 15:23:39 -0700729Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
730 DCHECK_GE(class_size, sizeof(Class));
731 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700732 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
733 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700734 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700735}
736
Brian Carlstrom4873d462011-08-21 15:23:39 -0700737Class* ClassLinker::AllocClass(size_t class_size) {
738 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700739}
740
Jesse Wilson35baaab2011-08-10 16:18:03 -0400741Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700742 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700743}
744
745Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700746 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700747}
748
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700749ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
750 return ObjectArray<StackTraceElement>::Alloc(
751 GetClassRoot(kJavaLangStackTraceElementArrayClass),
752 length);
753}
754
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700755Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700756 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700757 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700758 if (class_loader != NULL) {
759 Class* klass = FindClass(descriptor, NULL);
760 if (klass != NULL) {
761 return klass;
762 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700763 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700764 }
765
Carl Shapirob5573532011-07-12 18:22:59 -0700766 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700767 DCHECK(self != NULL);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700768 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700769 // Find the class in the loaded classes table.
770 Class* klass = LookupClass(descriptor, class_loader);
771 if (klass == NULL) {
772 // Class is not yet loaded.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700773 if (descriptor[0] == '[' && descriptor[1] != '\0') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700774 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700775 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700776 const DexFile::ClassPath& class_path = ((class_loader != NULL)
777 ? ClassLoader::GetClassPath(class_loader)
778 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700779 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700780 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700781 std::string name(PrintableString(descriptor));
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700782 ThrowNoClassDefFoundError("Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700783 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700784 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700785 const DexFile& dex_file = *pair.first;
786 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700787 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700788 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700789 if (!init_done_) {
790 // finish up init of hand crafted class_roots_
791 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700792 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700793 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700794 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400795 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700796 klass = GetClassRoot(kJavaLangString);
Elliott Hughes80609252011-09-23 17:24:51 -0700797 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
798 klass = GetClassRoot(kJavaLangReflectConstructor);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700799 } else if (descriptor == "Ljava/lang/reflect/Field;") {
800 klass = GetClassRoot(kJavaLangReflectField);
801 } else if (descriptor == "Ljava/lang/reflect/Method;") {
802 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700803 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700804 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700805 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700806 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700807 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700808 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700809 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700810 klass->SetDexCache(dex_cache);
811 LoadClass(dex_file, dex_class_def, klass, class_loader);
812 // Check for a pending exception during load
813 if (self->IsExceptionPending()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700814 return NULL;
815 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700816 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700817 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700818 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700819 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700820 if (!success) {
821 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700822 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700823 klass = LookupClass(descriptor, class_loader);
824 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700825 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700826 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700827 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700828 CHECK(!klass->IsLoaded());
829 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700830 // Loading failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700831 CHECK(self->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700832 lock.NotifyAll();
833 return NULL;
834 }
835 CHECK(klass->IsLoaded());
836 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700837 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700838 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700839 // Linking failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700840 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700841 lock.NotifyAll();
842 return NULL;
843 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700844 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700845 }
846 }
847 }
848 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700849 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700850 ObjectLock lock(klass);
851 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700852 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700853 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700854 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700855 return NULL;
856 }
857 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700858 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700859 lock.Wait();
860 }
861 }
862 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700863 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700864 return NULL;
865 }
866 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700867 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700868 CHECK(!self->IsExceptionPending());
869 return klass;
870}
871
Brian Carlstrom4873d462011-08-21 15:23:39 -0700872// Precomputes size that will be needed for Class, matching LinkStaticFields
873size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
874 const DexFile::ClassDef& dex_class_def) {
875 const byte* class_data = dex_file.GetClassData(dex_class_def);
876 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
877 size_t num_static_fields = header.static_fields_size_;
878 size_t num_ref = 0;
879 size_t num_32 = 0;
880 size_t num_64 = 0;
881 if (num_static_fields != 0) {
882 uint32_t last_idx = 0;
883 for (size_t i = 0; i < num_static_fields; ++i) {
884 DexFile::Field dex_field;
885 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
886 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
887 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
888 char c = descriptor[0];
889 if (c == 'L' || c == '[') {
890 num_ref++;
891 } else if (c == 'J' || c == 'D') {
892 num_64++;
893 } else {
894 num_32++;
895 }
896 }
897 }
898
899 // start with generic class data
900 size_t size = sizeof(Class);
901 // follow with reference fields which must be contiguous at start
902 size += (num_ref * sizeof(uint32_t));
903 // if there are 64-bit fields to add, make sure they are aligned
904 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
905 if (num_32 != 0) {
906 // use an available 32-bit field for padding
907 num_32--;
908 }
909 size += sizeof(uint32_t); // either way, we are adding a word
910 DCHECK_EQ(size, RoundUp(size, 8));
911 }
912 // tack on any 64-bit fields now that alignment is assured
913 size += (num_64 * sizeof(uint64_t));
914 // tack on any remaining 32-bit fields
915 size += (num_32 * sizeof(uint32_t));
916 return size;
917}
918
Brian Carlstromf615a612011-07-23 12:50:34 -0700919void ClassLinker::LoadClass(const DexFile& dex_file,
920 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700921 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700922 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700923 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700924 CHECK(klass->GetDexCache() != NULL);
925 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700926 const byte* class_data = dex_file.GetClassData(dex_class_def);
927 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700928
Brian Carlstromf615a612011-07-23 12:50:34 -0700929 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700930 CHECK(descriptor != NULL);
931
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700932 klass->SetClass(GetClassRoot(kJavaLangClass));
933 if (klass->GetDescriptor() != NULL) {
934 DCHECK(klass->GetDescriptor()->Equals(descriptor));
935 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700936 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700937 }
938 uint32_t access_flags = dex_class_def.access_flags_;
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700939 // Make sure there aren't any "bonus" flags set, since we use them for runtime state.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700940 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
941 klass->SetAccessFlags(access_flags);
942 klass->SetClassLoader(class_loader);
943 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
944 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700945
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700946 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700947
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700948 size_t num_static_fields = header.static_fields_size_;
949 size_t num_instance_fields = header.instance_fields_size_;
950 size_t num_direct_methods = header.direct_methods_size_;
951 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700952
Brian Carlstromc74255f2011-09-11 22:47:39 -0700953 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700954
955 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700956 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700957
958 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700959 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700960 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700961 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700962 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700963 DexFile::Field dex_field;
964 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400965 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700966 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700967 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700968 }
969 }
970
971 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700972 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700973 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700974 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700975 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700976 DexFile::Field dex_field;
977 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400978 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700979 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700980 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700981 }
982 }
983
984 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700985 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700986 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700987 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700988 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700989 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700990 DexFile::Method dex_method;
991 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700992 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700993 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700994 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700995 // TODO: register maps
996 }
997 }
998
999 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001000 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001001 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001002 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001003 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001004 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001005 DexFile::Method dex_method;
1006 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -07001007 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001008 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001009 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001010 // TODO: register maps
1011 }
1012 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001013}
1014
Brian Carlstromf615a612011-07-23 12:50:34 -07001015void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1016 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001017 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001018 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001019 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001020 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001021 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1022 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001023 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001024 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001025 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001026 }
1027 }
1028}
1029
Brian Carlstromf615a612011-07-23 12:50:34 -07001030void ClassLinker::LoadField(const DexFile& dex_file,
1031 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001032 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001033 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001034 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001035 dst->SetDeclaringClass(klass);
1036 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1037 dst->SetTypeIdx(field_id.type_idx_);
1038 dst->SetAccessFlags(src.access_flags_);
1039
1040 // In order to access primitive types using GetTypeDuringLinking we need to
1041 // ensure they are resolved into the dex cache
1042 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1043 if (descriptor[1] == '\0') {
1044 // only the descriptors of primitive types should be 1 character long
1045 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
1046 DCHECK(resolved->IsPrimitive());
1047 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001048}
1049
Brian Carlstromf615a612011-07-23 12:50:34 -07001050void ClassLinker::LoadMethod(const DexFile& dex_file,
1051 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001052 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001053 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001054 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001055 dst->SetDeclaringClass(klass);
Elliott Hughes20cde902011-10-04 17:37:27 -07001056
Elliott Hughes80609252011-09-23 17:24:51 -07001057 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
1058 dst->SetName(method_name);
1059 if (method_name->Equals("<init>")) {
1060 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1061 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001062
1063 int32_t utf16_length;
1064 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
1065 dst->SetSignature(intern_table_->InternStrong(utf16_length, signature.c_str()));
1066
1067 if (method_name->Equals("finalize") && signature == "()V") {
1068 /*
1069 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1070 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1071 * exclude it here.
1072 *
1073 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1074 */
1075 if (klass->GetClassLoader() != NULL ||
1076 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1077 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1078 klass->SetFinalizable();
1079 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001080 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001081
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001082 dst->SetProtoIdx(method_id.proto_idx_);
1083 dst->SetCodeItemOffset(src.code_off_);
1084 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -07001085 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001086 dst->SetAccessFlags(src.access_flags_);
1087 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001088
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001089 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1090 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1091 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1092 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1093 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1094 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001095
Brian Carlstrom934486c2011-07-12 23:42:50 -07001096 // TODO: check for finalize method
1097
Brian Carlstromf615a612011-07-23 12:50:34 -07001098 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001099 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001100 dst->SetNumRegisters(code_item->registers_size_);
1101 dst->SetNumIns(code_item->ins_size_);
1102 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001103 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001104 uint16_t num_args = Method::NumArgRegisters(shorty);
1105 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001106 ++num_args;
1107 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001108 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001109 // TODO: native methods
1110 }
1111}
1112
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001113void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001114 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1115}
1116
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001117void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001118 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001119 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001120 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001121}
1122
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001123void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001124 RegisterDexFile(dex_file, AllocDexCache(dex_file));
1125}
1126
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001127void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -07001128 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001129 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1130 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001131 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001132 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001133}
1134
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001135const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001136 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001137 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1138 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001139 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001140 }
1141 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001142 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001143 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001144}
1145
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001146DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001147 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001148 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001149 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001150 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001151 }
1152 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001153 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001154 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001155}
1156
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001157Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1158 const char* descriptor,
1159 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001160 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001161 CHECK(primitive_class != NULL);
1162 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1163 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
1164 primitive_class->SetPrimitiveType(type);
1165 primitive_class->SetStatus(Class::kStatusInitialized);
1166 bool success = InsertClass(descriptor, primitive_class);
1167 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1168 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001169}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001170
Brian Carlstrombe977852011-07-19 14:54:54 -07001171// Create an array class (i.e. the class object for the array, not the
1172// array itself). "descriptor" looks like "[C" or "[[[[B" or
1173// "[Ljava/lang/String;".
1174//
1175// If "descriptor" refers to an array of primitives, look up the
1176// primitive type's internally-generated class object.
1177//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001178// "class_loader" is the class loader of the class that's referring to
1179// us. It's used to ensure that we're looking for the element type in
1180// the right context. It does NOT become the class loader for the
1181// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001182//
1183// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001184Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001185 const ClassLoader* class_loader) {
1186 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001187
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001188 // Identify the underlying component type
1189 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001190 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001191 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001192 return NULL;
1193 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001194
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001195 // See if the component type is already loaded. Array classes are
1196 // always associated with the class loader of their underlying
1197 // element type -- an array of Strings goes with the loader for
1198 // java/lang/String -- so we need to look for it there. (The
1199 // caller should have checked for the existence of the class
1200 // before calling here, but they did so with *their* class loader,
1201 // not the component type's loader.)
1202 //
1203 // If we find it, the caller adds "loader" to the class' initiating
1204 // loader list, which should prevent us from going through this again.
1205 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001206 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001207 // are the same, because our caller (FindClass) just did the
1208 // lookup. (Even if we get this wrong we still have correct behavior,
1209 // because we effectively do this lookup again when we add the new
1210 // class to the hash table --- necessary because of possible races with
1211 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001212 if (class_loader != component_type->GetClassLoader()) {
1213 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001214 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001215 return new_class;
1216 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001217 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001218
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001219 // Fill out the fields in the Class.
1220 //
1221 // It is possible to execute some methods against arrays, because
1222 // all arrays are subclasses of java_lang_Object_, so we need to set
1223 // up a vtable. We can just point at the one in java_lang_Object_.
1224 //
1225 // Array classes are simple enough that we don't need to do a full
1226 // link step.
1227
1228 Class* new_class = NULL;
1229 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001230 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001231 if (descriptor == "[Ljava/lang/Class;") {
1232 new_class = GetClassRoot(kClassArrayClass);
1233 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001234 new_class = GetClassRoot(kObjectArrayClass);
1235 } else if (descriptor == "[C") {
1236 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001237 } else if (descriptor == "[I") {
1238 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001239 }
1240 }
1241 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001242 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001243 if (new_class == NULL) {
1244 return NULL;
1245 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001246 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001247 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001248 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001249 if (new_class->GetDescriptor() != NULL) {
1250 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1251 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001252 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001253 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001254 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001255 new_class->SetSuperClass(java_lang_Object);
1256 new_class->SetVTable(java_lang_Object->GetVTable());
1257 new_class->SetPrimitiveType(Class::kPrimNot);
1258 new_class->SetClassLoader(component_type->GetClassLoader());
1259 new_class->SetStatus(Class::kStatusInitialized);
1260 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001261 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001262
1263
1264 // All arrays have java/lang/Cloneable and java/io/Serializable as
1265 // interfaces. We need to set that up here, so that stuff like
1266 // "instanceof" works right.
1267 //
1268 // Note: The GC could run during the call to FindSystemClass,
1269 // so we need to make sure the class object is GC-valid while we're in
1270 // there. Do this by clearing the interface list so the GC will just
1271 // think that the entries are null.
1272
1273
1274 // Use the single, global copies of "interfaces" and "iftable"
1275 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001276 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001277 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001278
1279 // Inherit access flags from the component type. Arrays can't be
1280 // used as a superclass or interface, so we want to add "final"
1281 // and remove "interface".
1282 //
1283 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001284 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001285 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001286 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1287 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001288
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001289 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001290 return new_class;
1291 }
1292 // Another thread must have loaded the class after we
1293 // started but before we finished. Abandon what we've
1294 // done.
1295 //
1296 // (Yes, this happens.)
1297
1298 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001299 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001300 DCHECK(other_class != NULL);
1301 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001302}
1303
1304Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001305 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001306 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001307 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001308 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001309 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001310 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001311 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001312 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001313 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001314 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001315 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001316 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001317 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001318 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001319 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001320 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001321 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001322 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001323 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001324 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001325 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001326 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001327 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001328}
1329
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001330bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1331 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001332 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001333 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001334 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001335}
1336
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001337Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001338 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001339 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001340 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001341 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001342 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001343 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001344 return klass;
1345 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001346 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001347 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001348}
1349
jeffhao98eacac2011-09-14 16:11:53 -07001350void ClassLinker::VerifyClass(Class* klass) {
1351 if (klass->IsVerified()) {
1352 return;
1353 }
1354
1355 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001356 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001357
jeffhao5cfd6fb2011-09-27 13:54:29 -07001358 if (DexVerifier::VerifyClass(klass)) {
1359 klass->SetStatus(Class::kStatusVerified);
1360 } else {
1361 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
1362 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1363
1364 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
1365 klass->SetStatus(Class::kStatusResolved);
1366 }
jeffhao98eacac2011-09-14 16:11:53 -07001367}
1368
Brian Carlstrom25c33252011-09-18 15:58:35 -07001369bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001370 CHECK(klass->IsResolved() || klass->IsErroneous())
1371 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001372
Carl Shapirob5573532011-07-12 18:22:59 -07001373 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001374
Brian Carlstrom25c33252011-09-18 15:58:35 -07001375 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001376 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001377 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001378 ObjectLock lock(klass);
1379
Brian Carlstromd1422f82011-09-28 11:37:09 -07001380 if (klass->GetStatus() == Class::kStatusInitialized) {
1381 return true;
1382 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001383
Brian Carlstromd1422f82011-09-28 11:37:09 -07001384 if (klass->IsErroneous()) {
1385 ThrowEarlierClassFailure(klass);
1386 return false;
1387 }
1388
1389 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001390 VerifyClass(klass);
1391 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001392 return false;
1393 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001394 }
1395
Brian Carlstrom25c33252011-09-18 15:58:35 -07001396 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1397 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001398 // if the class has a <clinit> but we can't run it during compilation,
1399 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001400 return false;
1401 }
1402
Brian Carlstromd1422f82011-09-28 11:37:09 -07001403 // If the class is kStatusInitializing, either this thread is
1404 // initializing higher up the stack or another thread has beat us
1405 // to initializing and we need to wait. Either way, this
1406 // invocation of InitializeClass will not be responsible for
1407 // running <clinit> and will return.
1408 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001409 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001410 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001411 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001412 return true;
1413 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001414 // No. That's fine. Wait for another thread to finish initializing.
1415 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001416 }
1417
1418 if (!ValidateSuperClassDescriptors(klass)) {
1419 klass->SetStatus(Class::kStatusError);
1420 return false;
1421 }
1422
Brian Carlstromd1422f82011-09-28 11:37:09 -07001423 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001424
Elliott Hughesdcc24742011-09-07 14:02:44 -07001425 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001426 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001427 }
1428
Brian Carlstrom25c33252011-09-18 15:58:35 -07001429 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001430 return false;
1431 }
1432
1433 InitializeStaticFields(klass);
1434
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001435 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001436 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001437 }
1438
1439 {
1440 ObjectLock lock(klass);
1441
1442 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001443 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001444 klass->SetStatus(Class::kStatusError);
1445 } else {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001446 ++Runtime::Current()->GetStats()->class_init_count;
1447 ++self->GetStats()->class_init_count;
1448 // TODO: class_init_time_ns
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001449 klass->SetStatus(Class::kStatusInitialized);
1450 }
1451 lock.NotifyAll();
1452 }
1453
1454 return true;
1455}
1456
Brian Carlstromd1422f82011-09-28 11:37:09 -07001457bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1458 while (true) {
1459 CHECK(!self->IsExceptionPending());
1460 lock.Wait();
1461
1462 // When we wake up, repeat the test for init-in-progress. If
1463 // there's an exception pending (only possible if
1464 // "interruptShouldThrow" was set), bail out.
1465 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001466 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001467 klass->SetStatus(Class::kStatusError);
1468 return false;
1469 }
1470 // Spurious wakeup? Go back to waiting.
1471 if (klass->GetStatus() == Class::kStatusInitializing) {
1472 continue;
1473 }
1474 if (klass->IsErroneous()) {
1475 // The caller wants an exception, but it was thrown in a
1476 // different thread. Synthesize one here.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001477 self->ThrowNewExceptionF("Ljava/lang/NoClassDefFoundError;",
Brian Carlstromd1422f82011-09-28 11:37:09 -07001478 "<clinit> failed for class %s; see exception in other thread",
1479 PrettyDescriptor(klass->GetDescriptor()).c_str());
1480 return false;
1481 }
1482 if (klass->IsInitialized()) {
1483 return true;
1484 }
1485 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1486 }
1487 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1488}
1489
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001490bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1491 if (klass->IsInterface()) {
1492 return true;
1493 }
1494 // begin with the methods local to the superclass
1495 if (klass->HasSuperClass() &&
1496 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1497 const Class* super = klass->GetSuperClass();
1498 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001499 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001500 if (method != super->GetVirtualMethod(i) &&
1501 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001502 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1503
1504 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 -07001505 return false;
1506 }
1507 }
1508 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001509 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1510 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1511 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001512 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1513 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001514 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001515 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001516 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001517 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1518
1519 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 -07001520 return false;
1521 }
1522 }
1523 }
1524 }
1525 return true;
1526}
1527
1528bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001529 const Class* klass1,
1530 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001531 if (method->IsMiranda()) {
1532 return true;
1533 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001534 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001535 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001536 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001537 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001538 const char* descriptor = it->GetDescriptor();
1539 if (descriptor == NULL) {
1540 break;
1541 }
1542 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1543 // Found a non-primitive type.
1544 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1545 return false;
1546 }
1547 }
1548 }
1549 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001550 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001551 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001552 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001553 return false;
1554 }
1555 }
1556 return true;
1557}
1558
1559// Returns true if classes referenced by the descriptor are the
1560// same classes in klass1 as they are in klass2.
1561bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001562 const Class* klass1,
1563 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001564 CHECK(descriptor != NULL);
1565 CHECK(klass1 != NULL);
1566 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001567 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001568 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001569 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001570 // TODO: found2 == NULL
1571 // TODO: lookup found1 in initiating loader list
1572 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001573 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001574 if (found1 == found2) {
1575 return true;
1576 } else {
1577 return false;
1578 }
1579 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001580 return true;
1581}
1582
Brian Carlstrom25c33252011-09-18 15:58:35 -07001583bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001584 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001585 if (!klass->IsInterface() && klass->HasSuperClass()) {
1586 Class* super_class = klass->GetSuperClass();
1587 if (super_class->GetStatus() != Class::kStatusInitialized) {
1588 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001589 Thread* self = Thread::Current();
1590 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001591 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001592 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001593 // TODO: check for a pending exception
1594 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001595 if (!can_run_clinit) {
1596 // Don't set status to error when we can't run <clinit>.
1597 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1598 klass->SetStatus(Class::kStatusVerified);
1599 return false;
1600 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001601 klass->SetStatus(Class::kStatusError);
1602 klass->NotifyAll();
1603 return false;
1604 }
1605 }
1606 }
1607 return true;
1608}
1609
Brian Carlstrom25c33252011-09-18 15:58:35 -07001610bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001611 CHECK(c != NULL);
1612 if (c->IsInitialized()) {
1613 return true;
1614 }
1615
Elliott Hughes5f791332011-09-15 17:45:30 -07001616 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001617 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001618 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001619 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001620}
1621
Brian Carlstromb9edb842011-08-28 16:31:06 -07001622StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1623 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001624 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1625 Class* klass = class_linker->ResolveType(type_idx, referrer);
1626 if (klass == NULL) {
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001627 CHECK(Thread::Current()->IsExceptionPending());
1628 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001629 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001630 // If we are the <clinit> of this class, just return our storage.
1631 //
1632 // Do not set the DexCache InitializedStaticStorage, since that
1633 // implies <clinit> has finished running.
1634 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1635 return klass;
1636 }
Brian Carlstrom25c33252011-09-18 15:58:35 -07001637 if (!class_linker->EnsureInitialized(klass, true)) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001638 CHECK(Thread::Current()->IsExceptionPending());
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001639 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001640 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001641 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001642 return klass;
1643}
1644
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001645void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1646 Class* c, std::map<int, Field*>& field_map) {
1647 const ClassLoader* cl = c->GetClassLoader();
1648 const byte* class_data = dex_file.GetClassData(dex_class_def);
1649 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1650 uint32_t last_idx = 0;
1651 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1652 DexFile::Field dex_field;
1653 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1654 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1655 }
1656}
1657
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001658void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001659 size_t num_static_fields = klass->NumStaticFields();
1660 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001661 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001662 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001663 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001664 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001665 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001666 return;
1667 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001668 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001669 const DexFile& dex_file = FindDexFile(dex_cache);
1670 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001671 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001672
1673 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1674 std::map<int, Field*> field_map;
1675 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1676
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001677 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001678 if (addr == NULL) {
1679 // All this class' static fields have default values.
1680 return;
1681 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001682 size_t array_size = DecodeUnsignedLeb128(&addr);
1683 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001684 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001685 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001686 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001687 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001688 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001689 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001690 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001691 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001692 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001693 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001694 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001695 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001696 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001697 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001698 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001699 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001700 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001701 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001702 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001703 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001704 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001705 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001706 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001707 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001708 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001709 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001710 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001711 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001712 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001713 break;
1714 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001715 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001716 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001717 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001718 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001719 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001720 break;
1721 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001722 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001723 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001724 }
1725}
1726
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001727bool ClassLinker::LinkClass(Class* klass) {
1728 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001729 if (!LinkSuperClass(klass)) {
1730 return false;
1731 }
1732 if (!LinkMethods(klass)) {
1733 return false;
1734 }
1735 if (!LinkInstanceFields(klass)) {
1736 return false;
1737 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001738 if (!LinkStaticFields(klass)) {
1739 return false;
1740 }
1741 CreateReferenceInstanceOffsets(klass);
1742 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001743 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1744 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001745 return true;
1746}
1747
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001748bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001749 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1750 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1751 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001752 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001753 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001754 return false;
1755 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001756 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001757 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001758 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1759 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07001760 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001761 klass->SetInterface(i, interface);
1762 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001763 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001764 return false;
1765 }
1766 // Verify
1767 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001768 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001769 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001770 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001771 PrettyDescriptor(interface->GetDescriptor()).c_str(),
1772 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001773 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001774 }
1775 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001776 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001777 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001778 return true;
1779}
1780
1781bool ClassLinker::LinkSuperClass(Class* klass) {
1782 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001783 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001784 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001785 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001786 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001787 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001788 return false;
1789 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001790 return true;
1791 }
1792 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001793 ThrowLinkageError("No superclass defined for class %s",
1794 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795 return false;
1796 }
1797 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001798 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001799 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001800 "Superclass %s of %s is %s",
1801 PrettyDescriptor(super->GetDescriptor()).c_str(),
1802 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001803 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001804 return false;
1805 }
1806 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001807 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001808 "Superclass %s is inaccessible by %s",
1809 PrettyDescriptor(super->GetDescriptor()).c_str(),
1810 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001811 return false;
1812 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001813
1814 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
1815 if (super->IsFinalizable()) {
1816 klass->SetFinalizable();
1817 }
1818
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001819#ifndef NDEBUG
1820 // Ensure super classes are fully resolved prior to resolving fields..
1821 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001822 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001823 super = super->GetSuperClass();
1824 }
1825#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001826 return true;
1827}
1828
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001829// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001830bool ClassLinker::LinkMethods(Class* klass) {
1831 if (klass->IsInterface()) {
1832 // No vtable.
1833 size_t count = klass->NumVirtualMethods();
1834 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001835 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001836 return false;
1837 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001838 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001839 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001840 }
jeffhaobdb76512011-09-07 11:43:16 -07001841 // Link interface method tables
1842 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001843 } else {
1844 // Link virtual method tables
1845 LinkVirtualMethods(klass);
1846
1847 // Link interface method tables
1848 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001849 }
1850 return true;
1851}
1852
1853bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001854 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001855 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1856 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001857 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001858 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001859 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001860 // See if any of our virtual methods override the superclass.
1861 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001862 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001863 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001864 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001865 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001866 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001867 // Verify
1868 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001869 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001870 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1871 local_method->GetName()->ToModifiedUtf8().c_str(),
1872 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001873 return false;
1874 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001875 vtable->Set(j, local_method);
1876 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001877 break;
1878 }
1879 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001880 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001881 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001882 vtable->Set(actual_count, local_method);
1883 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001884 actual_count += 1;
1885 }
1886 }
1887 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001888 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001889 return false;
1890 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001891 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001892 CHECK_LE(actual_count, max_count);
1893 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001894 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001895 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001896 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001897 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001898 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001899 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001900 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001901 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001902 return false;
1903 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001904 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001905 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001906 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1907 vtable->Set(i, virtual_method);
1908 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001909 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001910 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001911 }
1912 return true;
1913}
1914
1915bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001916 size_t super_ifcount;
1917 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001918 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001919 } else {
1920 super_ifcount = 0;
1921 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001922 size_t ifcount = super_ifcount;
1923 ifcount += klass->NumInterfaces();
1924 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001925 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001926 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001927 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001928 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001929 // DCHECK(klass->GetIfTableCount() == 0);
1930 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001931 return true;
1932 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001933 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001934 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001935 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1936 for (size_t i = 0; i < super_ifcount; i++) {
1937 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1938 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001939 }
1940 // Flatten the interface inheritance hierarchy.
1941 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001942 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001943 Class* interface = klass->GetInterface(i);
1944 DCHECK(interface != NULL);
1945 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001946 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001947 "Class %s implements non-interface class %s",
1948 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1949 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001950 return false;
1951 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001952 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001953 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07001954 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001955 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1956 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001957 }
1958 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001959 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001960 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07001961
1962 // If we're an interface, we don't need the vtable pointers, so we're done.
1963 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001964 return true;
1965 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001966 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001967 for (size_t i = 0; i < ifcount; ++i) {
1968 InterfaceEntry* interface_entry = iftable->Get(i);
1969 Class* interface = interface_entry->GetInterface();
1970 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1971 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001972 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001973 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1974 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001975 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07001976 // For each method listed in the interface's method list, find the
1977 // matching method in our class's method list. We want to favor the
1978 // subclass over the superclass, which just requires walking
1979 // back from the end of the vtable. (This only matters if the
1980 // superclass defines a private method and this class redefines
1981 // it -- otherwise it would use the same vtable slot. In .dex files
1982 // those don't end up in the virtual method table, so it shouldn't
1983 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001984 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1985 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001986 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1987 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001988 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001989 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001990 return false;
1991 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001992 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001993 break;
1994 }
1995 }
1996 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001997 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07001998 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
1999 if (miranda_list[mir]->HasSameNameAndDescriptor(interface_method)) {
2000 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002001 break;
2002 }
2003 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002004 if (miranda_method == NULL) {
2005 // point the interface table at a phantom slot
2006 miranda_method = AllocMethod();
2007 memcpy(miranda_method, interface_method, sizeof(Method));
2008 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002009 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002010 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002011 }
2012 }
2013 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002014 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002015 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002016 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002017 klass->SetVirtualMethods((old_method_count == 0)
2018 ? AllocObjectArray<Method>(new_method_count)
2019 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002021 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2022 CHECK(vtable != NULL);
2023 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002024 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002025 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002026 for (size_t i = 0; i < miranda_list.size(); ++i) {
2027 Method* meth = miranda_list[i]; //AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002028 // TODO: this shouldn't be a memcpy
Elliott Hughes4681c802011-09-25 18:04:37 -07002029 //memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002030 meth->SetDeclaringClass(klass);
2031 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
2032 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002033 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002034 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002035 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002036 // TODO: do not assign to the vtable field until it is fully constructed.
2037 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002038 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002039
2040 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2041 for (int i = 0; i < vtable->GetLength(); ++i) {
2042 CHECK(vtable->Get(i) != NULL);
2043 }
2044
2045// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2046
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002047 return true;
2048}
2049
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002050bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002051 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002052 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002053}
2054
2055bool ClassLinker::LinkStaticFields(Class* klass) {
2056 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002057 size_t allocated_class_size = klass->GetClassSize();
2058 bool success = LinkFields(klass, false);
2059 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002060 return success;
2061}
2062
Brian Carlstromdbc05252011-09-09 01:59:59 -07002063struct LinkFieldsComparator {
2064 bool operator()(const Field* field1, const Field* field2){
2065
2066 // First come reference fields, then 64-bit, and finally 32-bit
2067 const Class* type1 = field1->GetTypeDuringLinking();
2068 const Class* type2 = field2->GetTypeDuringLinking();
2069 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2070 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2071 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2072 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2073 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2074 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2075 if (order1 != order2) {
2076 return order1 < order2;
2077 }
2078
2079 // same basic group? then sort by string.
2080 std::string name1 = field1->GetName()->ToModifiedUtf8();
2081 std::string name2 = field2->GetName()->ToModifiedUtf8();
2082 return name1 < name2;
2083 }
2084};
2085
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002086bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002087 size_t num_fields =
2088 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
2089
2090 ObjectArray<Field>* fields =
2091 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002092
2093 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002094 size_t size;
2095 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002096 if (instance) {
2097 Class* super_class = klass->GetSuperClass();
2098 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002099 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002100 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002101 }
2102 size = field_offset.Uint32Value();
2103 } else {
2104 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07002105 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002106 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002107
Brian Carlstromdbc05252011-09-09 01:59:59 -07002108 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002109
Brian Carlstromdbc05252011-09-09 01:59:59 -07002110 // we want a relatively stable order so that adding new fields
2111 // minimizes distruption of C++ version such as Class and Method.
2112 std::deque<Field*> grouped_and_sorted_fields;
2113 for (size_t i = 0; i < num_fields; i++) {
2114 grouped_and_sorted_fields.push_back(fields->Get(i));
2115 }
2116 std::sort(grouped_and_sorted_fields.begin(),
2117 grouped_and_sorted_fields.end(),
2118 LinkFieldsComparator());
2119
2120 // References should be at the front.
2121 size_t current_field = 0;
2122 size_t num_reference_fields = 0;
2123 for (; current_field < num_fields; current_field++) {
2124 Field* field = grouped_and_sorted_fields.front();
2125 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002126 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002127 bool isPrimitive = type != NULL && type->IsPrimitive();
2128 if (isPrimitive) {
2129 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002130 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002131 grouped_and_sorted_fields.pop_front();
2132 num_reference_fields++;
2133 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002134 field->SetOffset(field_offset);
2135 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002136 }
2137
2138 // Now we want to pack all of the double-wide fields together. If
2139 // we're not aligned, though, we want to shuffle one 32-bit field
2140 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002141 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2142 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2143 Field* field = grouped_and_sorted_fields[i];
2144 const Class* type = field->GetTypeDuringLinking();
2145 CHECK(type != NULL); // should only be working on primitive types
2146 DCHECK(type->IsPrimitive());
2147 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2148 continue;
2149 }
2150 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002151 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002152 // drop the consumed field
2153 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2154 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002155 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002156 // whether we found a 32-bit field for padding or not, we advance
2157 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002158 }
2159
2160 // Alignment is good, shuffle any double-wide fields forward, and
2161 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002162 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2163 while (!grouped_and_sorted_fields.empty()) {
2164 Field* field = grouped_and_sorted_fields.front();
2165 grouped_and_sorted_fields.pop_front();
2166 const Class* type = field->GetTypeDuringLinking();
2167 CHECK(type != NULL); // should only be working on primitive types
2168 DCHECK(type->IsPrimitive());
2169 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002170 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002171 field_offset = MemberOffset(field_offset.Uint32Value() +
2172 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2173 ? sizeof(uint64_t)
2174 : sizeof(uint32_t)));
2175 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002176 }
2177
2178#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002179 // Make sure that all reference fields appear before
2180 // non-reference fields, and all double-wide fields are aligned.
2181 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002182 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002183 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002184 if (false) { // enable to debug field layout
Brian Carlstrom845490b2011-09-19 15:56:53 -07002185 LOG(INFO) << "LinkFields: " << (instance ? "instance" : "static")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002186 << " class=" << PrettyClass(klass)
2187 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002188 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2189 }
2190 const Class* type = field->GetTypeDuringLinking();
2191 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002192 if (!seen_non_ref) {
2193 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002194 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002195 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002196 } else {
2197 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002198 }
2199 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002200 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002201 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002202 }
2203#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002204 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002205 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07002206 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002207 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002208 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002209 klass->SetObjectSize(size);
2210 }
2211 } else {
2212 klass->SetNumReferenceStaticFields(num_reference_fields);
2213 klass->SetClassSize(size);
2214 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002215 return true;
2216}
2217
2218// Set the bitmap of reference offsets, refOffsets, from the ifields
2219// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002220void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002221 uint32_t reference_offsets = 0;
2222 Class* super_class = klass->GetSuperClass();
2223 if (super_class != NULL) {
2224 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002225 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002226 if (reference_offsets == CLASS_WALK_SUPER) {
2227 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002228 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002229 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002230 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002231 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002232}
2233
2234void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002235 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002236}
2237
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002238void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2239 uint32_t reference_offsets) {
2240 size_t num_reference_fields =
2241 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2242 : klass->NumReferenceStaticFieldsDuringLinking();
2243 const ObjectArray<Field>* fields =
2244 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002245 // All of the fields that contain object references are guaranteed
2246 // to be at the beginning of the fields list.
2247 for (size_t i = 0; i < num_reference_fields; ++i) {
2248 // Note that byte_offset is the offset from the beginning of
2249 // object, not the offset into instance data
2250 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002251 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002252 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2253 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2254 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002255 CHECK_NE(new_bit, 0U);
2256 reference_offsets |= new_bit;
2257 } else {
2258 reference_offsets = CLASS_WALK_SUPER;
2259 break;
2260 }
2261 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002262 // Update fields in klass
2263 if (instance) {
2264 klass->SetReferenceInstanceOffsets(reference_offsets);
2265 } else {
2266 klass->SetReferenceStaticOffsets(reference_offsets);
2267 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002268}
2269
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002270String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002271 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002272 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002273 if (resolved != NULL) {
2274 return resolved;
2275 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002276 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2277 int32_t utf16_length = dex_file.GetStringLength(string_id);
2278 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002279 // TODO: remote the const_cast below
2280 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002281 dex_cache->SetResolvedString(string_idx, string);
2282 return string;
2283}
2284
2285Class* ClassLinker::ResolveType(const DexFile& dex_file,
2286 uint32_t type_idx,
2287 DexCache* dex_cache,
2288 const ClassLoader* class_loader) {
2289 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002290 if (resolved == NULL) {
2291 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2292 if (descriptor[1] == '\0') {
2293 // only the descriptors of primitive types should be 1 character long
2294 resolved = FindPrimitiveClass(descriptor[0]);
2295 } else {
2296 resolved = FindClass(descriptor, class_loader);
2297 }
2298 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002299 Class* check = resolved;
2300 while (check->IsArrayClass()) {
2301 check = check->GetComponentType();
2302 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002303 if (dex_cache != check->GetDexCache()) {
2304 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002305 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002306 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002307 resolved = NULL;
2308 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309 }
2310 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002311 if (resolved != NULL) {
2312 dex_cache->SetResolvedType(type_idx, resolved);
2313 } else {
2314 DCHECK(Thread::Current()->IsExceptionPending());
2315 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002316 }
2317 return resolved;
2318}
2319
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002320Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2321 uint32_t method_idx,
2322 DexCache* dex_cache,
2323 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002324 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002325 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2326 if (resolved != NULL) {
2327 return resolved;
2328 }
2329 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2330 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2331 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002332 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002333 return NULL;
2334 }
2335
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002336 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002337 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002338 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002339 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002340 } else if (klass->IsInterface()) {
2341 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002342 } else {
2343 resolved = klass->FindVirtualMethod(name, signature);
2344 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002345 if (resolved != NULL) {
2346 dex_cache->SetResolvedMethod(method_idx, resolved);
2347 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002348 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002349 }
2350 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002351}
2352
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002353Field* ClassLinker::ResolveField(const DexFile& dex_file,
2354 uint32_t field_idx,
2355 DexCache* dex_cache,
2356 const ClassLoader* class_loader,
2357 bool is_static) {
2358 Field* resolved = dex_cache->GetResolvedField(field_idx);
2359 if (resolved != NULL) {
2360 return resolved;
2361 }
2362 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2363 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2364 if (klass == NULL) {
2365 return NULL;
2366 }
2367
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002368 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002369 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002370 if (field_type == NULL) {
2371 // TODO: LinkageError?
2372 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2373 << " in " << PrettyClass(klass);
2374 return NULL;
2375}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002376 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002377 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002378 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002379 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002380 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002381 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002382 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002383 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002384 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002385 }
2386 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002387}
2388
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002389void ClassLinker::DumpAllClasses(int flags) const {
2390 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2391 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2392 std::vector<Class*> all_classes;
2393 {
2394 MutexLock mu(lock_);
2395 typedef Table::const_iterator It; // TODO: C++0x auto
2396 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2397 all_classes.push_back(it->second);
2398 }
2399 }
2400
2401 for (size_t i = 0; i < all_classes.size(); ++i) {
2402 all_classes[i]->DumpClass(std::cerr, flags);
2403 }
2404}
2405
Elliott Hughese27955c2011-08-26 15:21:24 -07002406size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002407 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002408 return classes_.size();
2409}
2410
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002411} // namespace art