blob: b4e332d4f6d13b0c553e96f782f8ba744588d1d6 [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004
Brian Carlstromdbc05252011-09-09 01:59:59 -07005#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070011#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070012#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070013#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "dex_verifier.h"
15#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070016#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070018#include "monitor.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070019#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070020#include "runtime.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070021#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070022#include "space.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070023#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070024#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070026
27namespace art {
28
Elliott Hughes4a2b4172011-09-20 17:08:25 -070029namespace {
30
31void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
32void ThrowNoClassDefFoundError(const char* fmt, ...) {
33 va_list args;
34 va_start(args, fmt);
35 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
36 va_end(args);
37}
38
Elliott Hughese555dc02011-09-25 10:46:35 -070039void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
40void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070041 va_list args;
42 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070043 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070044 va_end(args);
45}
46
47void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
48void ThrowLinkageError(const char* fmt, ...) {
49 va_list args;
50 va_start(args, fmt);
51 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
52 va_end(args);
53}
54
Elliott Hughescc5f9a92011-09-28 19:17:29 -070055void ThrowNoSuchMethodError(const char* kind,
56 Class* c, const StringPiece& name, const StringPiece& signature) {
57 DexCache* dex_cache = c->GetDexCache();
58 std::stringstream msg;
59 msg << "no " << kind << " method " << name << "." << signature
60 << " in class " << c->GetDescriptor()->ToModifiedUtf8()
61 << " or its superclasses";
62 if (dex_cache) {
63 msg << " (defined in " << dex_cache->GetLocation()->ToModifiedUtf8() << ")";
64 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070065 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070066}
67
Elliott Hughes4a2b4172011-09-20 17:08:25 -070068void ThrowEarlierClassFailure(Class* c) {
69 /*
70 * The class failed to initialize on a previous attempt, so we want to throw
71 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
72 * failed in verification, in which case v2 5.4.1 says we need to re-throw
73 * the previous error.
74 */
75 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
76
77 if (c->GetVerifyErrorClass() != NULL) {
78 // TODO: change the verifier to store an _instance_, with a useful detail message?
79 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070080 Thread::Current()->ThrowNewException(error_descriptor.c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -070081 PrettyDescriptor(c->GetDescriptor()).c_str());
82 } else {
83 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
84 }
85}
86
Elliott Hughes4d0207c2011-10-03 19:14:34 -070087void WrapExceptionInInitializer() {
88 JNIEnv* env = Thread::Current()->GetJniEnv();
89
90 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
91 CHECK(cause.get() != NULL);
92
93 env->ExceptionClear();
94
95 // TODO: add java.lang.Error to JniConstants?
96 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
97 CHECK(error_class.get() != NULL);
98 if (env->IsInstanceOf(cause.get(), error_class.get())) {
99 // We only wrap non-Error exceptions; an Error can just be used as-is.
100 env->Throw(cause.get());
101 return;
102 }
103
104 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
105 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
106 CHECK(eiie_class.get() != NULL);
107
108 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
109 CHECK(mid != NULL);
110
111 ScopedLocalRef<jthrowable> eiie(env,
112 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
113 env->Throw(eiie.get());
114}
115
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700116}
117
Elliott Hughes418d20f2011-09-22 14:00:39 -0700118const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700119 "Ljava/lang/Class;",
120 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700121 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700122 "[Ljava/lang/Object;",
123 "Ljava/lang/String;",
Elliott Hughes80609252011-09-23 17:24:51 -0700124 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700125 "Ljava/lang/reflect/Field;",
126 "Ljava/lang/reflect/Method;",
127 "Ljava/lang/ClassLoader;",
128 "Ldalvik/system/BaseDexClassLoader;",
129 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700130 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700131 "Z",
132 "B",
133 "C",
134 "D",
135 "F",
136 "I",
137 "J",
138 "S",
139 "V",
140 "[Z",
141 "[B",
142 "[C",
143 "[D",
144 "[F",
145 "[I",
146 "[J",
147 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700148 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700149};
150
Elliott Hughes5f791332011-09-15 17:45:30 -0700151class ObjectLock {
152 public:
153 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
154 CHECK(object != NULL);
155 obj_->MonitorEnter(self_);
156 }
157
158 ~ObjectLock() {
159 obj_->MonitorExit(self_);
160 }
161
162 void Wait() {
163 return Monitor::Wait(self_, obj_, 0, 0, false);
164 }
165
166 void Notify() {
167 obj_->Notify();
168 }
169
170 void NotifyAll() {
171 obj_->NotifyAll();
172 }
173
174 private:
175 Thread* self_;
176 Object* obj_;
177 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
178};
179
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700180ClassLinker* ClassLinker::Create(const std::vector<const DexFile*>& boot_class_path,
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700181 const std::vector<const DexFile*>& class_path,
Brian Carlstromc74255f2011-09-11 22:47:39 -0700182 InternTable* intern_table, bool image) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700183 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700184 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700185 if (image) {
186 class_linker->InitFromImage(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700187 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700188 class_linker->Init(boot_class_path, class_path);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700189 }
Carl Shapiro61e019d2011-07-14 16:53:09 -0700190 // TODO: check for failure during initialization
191 return class_linker.release();
192}
193
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700194ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700195 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700196 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700197 array_interfaces_(NULL),
198 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700199 init_done_(false),
200 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700201 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700202}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700203
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700204void ClassLinker::Init(const std::vector<const DexFile*>& boot_class_path,
205 const std::vector<const DexFile*>& class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700206 const Runtime* runtime = Runtime::Current();
207 if (runtime->IsVerboseStartup()) {
208 LOG(INFO) << "ClassLinker::InitFrom entering";
209 }
210
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700211 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700212
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700213 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700214 Class* java_lang_Class = down_cast<Class*>(
215 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700216 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700217 java_lang_Class->SetClass(java_lang_Class);
218 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700219 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700220
Elliott Hughes418d20f2011-09-22 14:00:39 -0700221 // Class[] is used for reflection support.
222 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
223 class_array_class->SetComponentType(java_lang_Class);
224
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700225 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700226 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700227 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700228 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700229 java_lang_Class->SetSuperClass(java_lang_Object);
230 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700231
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700232 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700233 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700234 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700235
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700236 // Setup the char class to be used for char[]
237 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
238
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700239 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700240 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700241 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700242 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700243
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700244 // Setup String
245 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
246 String::SetClass(java_lang_String);
247 java_lang_String->SetObjectSize(sizeof(String));
248 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400249
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700250 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700251 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
252 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700253 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700254 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
255 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
256 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700257
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258 // Create storage for root classes, save away our work so far (requires
259 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700260 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700261 SetClassRoot(kJavaLangClass, java_lang_Class);
262 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700263 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700264 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700265 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700266 SetClassRoot(kJavaLangString, java_lang_String);
267
268 // Setup the primitive type classes.
269 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
270 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
272 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
273 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
274 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
275 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
276 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
277
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700278 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700279 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700280 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700281
282 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
283 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700284 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
286 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700287 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700289 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700290
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700291 // setup boot_class_path_ and register class_path now that we can
292 // use AllocObjectArray to create DexCache instances
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700293 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700294 const DexFile* dex_file = boot_class_path[i];
295 CHECK(dex_file != NULL);
296 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700297 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700298 for (size_t i = 0; i != class_path.size(); ++i) {
299 const DexFile* dex_file = class_path[i];
300 CHECK(dex_file != NULL);
301 RegisterDexFile(*dex_file);
302 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303
Elliott Hughes80609252011-09-23 17:24:51 -0700304 // Constructor, Field, and Method are necessary so that FindClass can link members
305 Class* java_lang_reflect_Constructor = AllocClass(java_lang_Class, sizeof(MethodClass));
306 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
307 CHECK(java_lang_reflect_Constructor != NULL);
308 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
309 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor);
310 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
311
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700312 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
313 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700314 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
316 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
317 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
318 Field::SetClass(java_lang_reflect_Field);
319
320 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Elliott Hughes80609252011-09-23 17:24:51 -0700321 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322 CHECK(java_lang_reflect_Method != NULL);
323 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
324 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
325 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Elliott Hughes80609252011-09-23 17:24:51 -0700326 Method::SetClasses(java_lang_reflect_Constructor, java_lang_reflect_Method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700327
328 // now we can use FindSystemClass
329
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700330 // run char class through InitializePrimitiveClass to finish init
331 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
332 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
333
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700334 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700335 java_lang_Object->SetStatus(Class::kStatusNotReady);
336 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
337 CHECK_EQ(java_lang_Object, Object_class);
338 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
339 java_lang_String->SetStatus(Class::kStatusNotReady);
340 Class* String_class = FindSystemClass("Ljava/lang/String;");
341 CHECK_EQ(java_lang_String, String_class);
342 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
343
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700344 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
346 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
347
348 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
349 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
350
351 Class* found_char_array_class = FindSystemClass("[C");
352 CHECK_EQ(char_array_class, found_char_array_class);
353
354 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
355 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
356
357 Class* found_int_array_class = FindSystemClass("[I");
358 CHECK_EQ(int_array_class, found_int_array_class);
359
360 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
361 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
362
363 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
364 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
365
366 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
367 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
368
Elliott Hughes418d20f2011-09-22 14:00:39 -0700369 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
370 CHECK_EQ(class_array_class, found_class_array_class);
371
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700372 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
373 CHECK_EQ(object_array_class, found_object_array_class);
374
375 // Setup the single, global copies of "interfaces" and "iftable"
376 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
377 CHECK(java_lang_Cloneable != NULL);
378 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
379 CHECK(java_io_Serializable != NULL);
380 CHECK(array_interfaces_ != NULL);
381 array_interfaces_->Set(0, java_lang_Cloneable);
382 array_interfaces_->Set(1, java_io_Serializable);
383 // We assume that Cloneable/Serializable don't have superinterfaces --
384 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700385 // supers as well.
386 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
387 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700388
Elliott Hughes418d20f2011-09-22 14:00:39 -0700389 // Sanity check Class[] and Object[]'s interfaces
390 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
391 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
393 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700394
Elliott Hughes80609252011-09-23 17:24:51 -0700395 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700396 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700397 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700398 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700399
Elliott Hughes80609252011-09-23 17:24:51 -0700400 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
401 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
402 CHECK_EQ(java_lang_reflect_Constructor, Constructor_class);
403
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700404 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700405 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700406 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407
408 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700409 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700410 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700411
412 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
413 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414 java_lang_ref_FinalizerReference->SetAccessFlags(
415 java_lang_ref_FinalizerReference->GetAccessFlags() |
416 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700417 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418 java_lang_ref_PhantomReference->SetAccessFlags(
419 java_lang_ref_PhantomReference->GetAccessFlags() |
420 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700421 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422 java_lang_ref_SoftReference->SetAccessFlags(
423 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700424 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425 java_lang_ref_WeakReference->SetAccessFlags(
426 java_lang_ref_WeakReference->GetAccessFlags() |
427 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700428
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700429 // Setup the ClassLoaders, adjusting the object_size_ as necessary
430 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
431 CHECK_LT(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
432 java_lang_ClassLoader->SetObjectSize(sizeof(ClassLoader));
433 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
434
435 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
436 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
437 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
438
439 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
440 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
441 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
442 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
443
444 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700445 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
446 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700447 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700448
Brian Carlstroma663ea52011-08-19 23:33:41 -0700449 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700450
451 if (runtime->IsVerboseStartup()) {
452 LOG(INFO) << "ClassLinker::InitFrom exiting";
453 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700454}
455
456void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700457 const Runtime* runtime = Runtime::Current();
458 if (runtime->IsVerboseStartup()) {
459 LOG(INFO) << "ClassLinker::FinishInit entering";
460 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700461
462 // Let the heap know some key offsets into java.lang.ref instances
463 // NB we hard code the field indexes here rather than using FindInstanceField
464 // as the types of the field can't be resolved prior to the runtime being
465 // fully initialized
466 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
467 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
468
469 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
470 CHECK(pendingNext->GetName()->Equals("pendingNext"));
471 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
472
473 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
474 CHECK(queue->GetName()->Equals("queue"));
475 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue),
476 FindSystemClass("Ljava/lang/ref/ReferenceQueue;"));
477
478 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
479 CHECK(queueNext->GetName()->Equals("queueNext"));
480 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
481
482 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
483 CHECK(referent->GetName()->Equals("referent"));
484 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
485
486 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
487 CHECK(zombie->GetName()->Equals("zombie"));
488 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
489
490 Heap::SetReferenceOffsets(referent->GetOffset(),
491 queue->GetOffset(),
492 queueNext->GetOffset(),
493 pendingNext->GetOffset(),
494 zombie->GetOffset());
495
Brian Carlstroma663ea52011-08-19 23:33:41 -0700496 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700497 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700498 ClassRoot class_root = static_cast<ClassRoot>(i);
499 Class* klass = GetClassRoot(class_root);
500 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700501 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700502 // note SetClassRoot does additional validation.
503 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700504 }
505
506 // disable the slow paths in FindClass and CreatePrimitiveClass now
507 // that Object, Class, and Object[] are setup
508 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700509
510 if (runtime->IsVerboseStartup()) {
511 LOG(INFO) << "ClassLinker::FinishInit exiting";
512 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700513}
514
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700515void ClassLinker::RunRootClinits() {
516 Thread* self = Thread::Current();
517 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
518 Class* c = GetClassRoot(ClassRoot(i));
519 if (!c->IsArrayClass() && !c->IsPrimitive()) {
520 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
521 CHECK(!self->IsExceptionPending());
522 }
523 }
524}
525
Brian Carlstromc74255f2011-09-11 22:47:39 -0700526struct ClassLinker::InitFromImageCallbackState {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700527 ClassLinker* class_linker;
528
529 Class* class_roots[kClassRootsMax];
530
531 typedef std::tr1::unordered_map<std::string, ClassRoot> Table;
532 Table descriptor_to_class_root;
533
Brian Carlstroma663ea52011-08-19 23:33:41 -0700534 typedef std::tr1::unordered_set<DexCache*, DexCacheHash> Set;
535 Set dex_caches;
536};
537
Brian Carlstromc74255f2011-09-11 22:47:39 -0700538void ClassLinker::InitFromImage(const std::vector<const DexFile*>& boot_class_path,
539 const std::vector<const DexFile*>& class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700540 const Runtime* runtime = Runtime::Current();
541 if (runtime->IsVerboseStartup()) {
542 LOG(INFO) << "ClassLinker::InitFromImage entering";
543 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700544 CHECK(!init_done_);
545
546 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
547 DCHECK(heap_bitmap != NULL);
548
Brian Carlstromc74255f2011-09-11 22:47:39 -0700549 InitFromImageCallbackState state;
Brian Carlstroma663ea52011-08-19 23:33:41 -0700550 state.class_linker = this;
551 for (size_t i = 0; i < kClassRootsMax; i++) {
552 ClassRoot class_root = static_cast<ClassRoot>(i);
553 state.descriptor_to_class_root[GetClassRootDescriptor(class_root)] = class_root;
554 }
555
556 // reinit clases_ table
Brian Carlstromc74255f2011-09-11 22:47:39 -0700557 heap_bitmap->Walk(InitFromImageCallback, &state);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700558
559 // reinit class_roots_
560 Class* object_array_class = state.class_roots[kObjectArrayClass];
561 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
562 for (size_t i = 0; i < kClassRootsMax; i++) {
563 ClassRoot class_root = static_cast<ClassRoot>(i);
564 SetClassRoot(class_root, state.class_roots[class_root]);
565 }
566
Brian Carlstroma663ea52011-08-19 23:33:41 -0700567 // reinit array_interfaces_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700568 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
569 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700570
571 // build a map from location to DexCache to match up with DexFile::GetLocation
572 std::tr1::unordered_map<std::string, DexCache*> location_to_dex_cache;
Brian Carlstromc74255f2011-09-11 22:47:39 -0700573 typedef InitFromImageCallbackState::Set::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700574 for (It it = state.dex_caches.begin(), end = state.dex_caches.end(); it != end; ++it) {
575 DexCache* dex_cache = *it;
576 std::string location = dex_cache->GetLocation()->ToModifiedUtf8();
577 location_to_dex_cache[location] = dex_cache;
578 }
Elliott Hughes14134a12011-09-30 16:55:51 -0700579 CHECK(boot_class_path.size() + class_path.size() == location_to_dex_cache.size())
580 << "(" << boot_class_path.size() << " + " << class_path.size()
581 << " != " << location_to_dex_cache.size() << ")";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700582
583 // reinit boot_class_path with DexFile arguments and found DexCaches
584 for (size_t i = 0; i != boot_class_path.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700585 const DexFile* dex_file = boot_class_path[i];
586 CHECK(dex_file != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700587 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700588 CHECK(dex_cache != NULL) << dex_file->GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700589 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700590 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700591
592 // register class_path with DexFile arguments and found DexCaches
593 for (size_t i = 0; i != class_path.size(); ++i) {
594 const DexFile* dex_file = class_path[i];
595 CHECK(dex_file != NULL);
596 DexCache* dex_cache = location_to_dex_cache[dex_file->GetLocation()];
597 CHECK(dex_cache != NULL) << dex_file->GetLocation();
598 RegisterDexFile(*dex_file, dex_cache);
599 }
600
Brian Carlstroma663ea52011-08-19 23:33:41 -0700601 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700602 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700603 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700604 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
605 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
606 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
607 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
608 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
609 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
610 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
611 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700612 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700613 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700614
615 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700616
617 if (runtime->IsVerboseStartup()) {
618 LOG(INFO) << "ClassLinker::InitFromImage exiting";
619 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700620}
621
Brian Carlstrom78128a62011-09-15 17:21:19 -0700622void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700623 DCHECK(obj != NULL);
624 DCHECK(arg != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700625 InitFromImageCallbackState* state = reinterpret_cast<InitFromImageCallbackState*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700626
Brian Carlstromc74255f2011-09-11 22:47:39 -0700627 if (obj->IsString()) {
628 state->class_linker->intern_table_->RegisterStrong(obj->AsString());
629 return;
630 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700631 if (!obj->IsClass()) {
632 return;
633 }
634 Class* klass = obj->AsClass();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700635 // TODO: restore ClassLoader's list of DexFiles after image load
636 // CHECK(klass->GetClassLoader() == NULL);
637 const ClassLoader* class_loader = klass->GetClassLoader();
638 if (class_loader != NULL) {
639 // TODO: replace this hack with something based on command line arguments
640 Thread::Current()->SetClassLoaderOverride(class_loader);
641 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700642
643 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700644 // restore class to ClassLinker::classes_ table
645 state->class_linker->InsertClass(descriptor, klass);
646
647 // note DexCache to match with DexFile later
648 DexCache* dex_cache = klass->GetDexCache();
649 if (dex_cache != NULL) {
650 state->dex_caches.insert(dex_cache);
651 } else {
Brian Carlstromb63ec392011-08-27 17:38:27 -0700652 DCHECK(klass->IsArrayClass() || klass->IsPrimitive());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700653 }
654
655 // check if this is a root, if so, register it
Brian Carlstromc74255f2011-09-11 22:47:39 -0700656 typedef InitFromImageCallbackState::Table::const_iterator It; // TODO: C++0x auto
Brian Carlstroma663ea52011-08-19 23:33:41 -0700657 It it = state->descriptor_to_class_root.find(descriptor);
658 if (it != state->descriptor_to_class_root.end()) {
659 ClassRoot class_root = it->second;
660 state->class_roots[class_root] = klass;
661 }
662}
663
664// Keep in sync with InitCallback. Anything we visit, we need to
665// reinit references to when reinitializing a ClassLinker from a
666// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700667void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
668 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700669
670 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700671 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700672 }
673
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700674 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700675 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700676 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700677 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700678 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700679 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700680 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700681
Elliott Hughes410c0c82011-09-01 17:58:25 -0700682 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700683}
684
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700685ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700686 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700687 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700688 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700689 BooleanArray::ResetArrayClass();
690 ByteArray::ResetArrayClass();
691 CharArray::ResetArrayClass();
692 DoubleArray::ResetArrayClass();
693 FloatArray::ResetArrayClass();
694 IntArray::ResetArrayClass();
695 LongArray::ResetArrayClass();
696 ShortArray::ResetArrayClass();
697 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700698 StackTraceElement::ResetClass();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700699}
700
701DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700702 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700703 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700704 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700705 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700706 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700707 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700708 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
709 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700710 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700711}
712
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700713CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
714 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700715}
716
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700717InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
718 DCHECK(interface->IsInterface());
719 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
720 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
721 interface_entry->SetInterface(interface);
722 return interface_entry;
723}
724
Brian Carlstrom4873d462011-08-21 15:23:39 -0700725Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
726 DCHECK_GE(class_size, sizeof(Class));
727 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700728 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
729 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700730 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700731}
732
Brian Carlstrom4873d462011-08-21 15:23:39 -0700733Class* ClassLinker::AllocClass(size_t class_size) {
734 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700735}
736
Jesse Wilson35baaab2011-08-10 16:18:03 -0400737Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700738 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700739}
740
741Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700742 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700743}
744
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700745ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
746 return ObjectArray<StackTraceElement>::Alloc(
747 GetClassRoot(kJavaLangStackTraceElementArrayClass),
748 length);
749}
750
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700751Class* ClassLinker::FindClass(const StringPiece& descriptor,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700752 const ClassLoader* class_loader) {
Brian Carlstrom4a289ed2011-08-16 17:17:49 -0700753 // TODO: remove this contrived parent class loader check when we have a real ClassLoader.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700754 if (class_loader != NULL) {
755 Class* klass = FindClass(descriptor, NULL);
756 if (klass != NULL) {
757 return klass;
758 }
Elliott Hughesbd935992011-08-22 11:59:34 -0700759 Thread::Current()->ClearException();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700760 }
761
Carl Shapirob5573532011-07-12 18:22:59 -0700762 Thread* self = Thread::Current();
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700763 DCHECK(self != NULL);
Brian Carlstrom27ec9612011-09-19 20:20:38 -0700764 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700765 // Find the class in the loaded classes table.
766 Class* klass = LookupClass(descriptor, class_loader);
767 if (klass == NULL) {
768 // Class is not yet loaded.
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700769 if (descriptor[0] == '[' && descriptor[1] != '\0') {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700770 return CreateArrayClass(descriptor, class_loader);
Brian Carlstroma331b3c2011-07-18 17:47:56 -0700771 }
Brian Carlstrom8a487412011-08-29 20:08:52 -0700772 const DexFile::ClassPath& class_path = ((class_loader != NULL)
773 ? ClassLoader::GetClassPath(class_loader)
774 : boot_class_path_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700775 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700776 if (pair.second == NULL) {
Elliott Hughesbd935992011-08-22 11:59:34 -0700777 std::string name(PrintableString(descriptor));
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700778 ThrowNoClassDefFoundError("Class %s not found in class loader %p", name.c_str(), class_loader);
Brian Carlstrom6cc18452011-07-18 15:10:33 -0700779 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700780 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700781 const DexFile& dex_file = *pair.first;
782 const DexFile::ClassDef& dex_class_def = *pair.second;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700783 DexCache* dex_cache = FindDexCache(dex_file);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700784 // Load the class from the dex file.
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700785 if (!init_done_) {
786 // finish up init of hand crafted class_roots_
787 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700788 klass = GetClassRoot(kJavaLangObject);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700789 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700790 klass = GetClassRoot(kJavaLangClass);
Jesse Wilson14150742011-07-29 19:04:44 -0400791 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700792 klass = GetClassRoot(kJavaLangString);
Elliott Hughes80609252011-09-23 17:24:51 -0700793 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
794 klass = GetClassRoot(kJavaLangReflectConstructor);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700795 } else if (descriptor == "Ljava/lang/reflect/Field;") {
796 klass = GetClassRoot(kJavaLangReflectField);
797 } else if (descriptor == "Ljava/lang/reflect/Method;") {
798 klass = GetClassRoot(kJavaLangReflectMethod);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700799 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700800 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700801 }
Carl Shapiro565f5072011-07-10 13:39:43 -0700802 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700803 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
Carl Shapiro565f5072011-07-10 13:39:43 -0700804 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700805 if (!klass->IsResolved()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700806 klass->SetDexCache(dex_cache);
807 LoadClass(dex_file, dex_class_def, klass, class_loader);
808 // Check for a pending exception during load
809 if (self->IsExceptionPending()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700810 return NULL;
811 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700812 ObjectLock lock(klass);
Elliott Hughesdcc24742011-09-07 14:02:44 -0700813 klass->SetClinitThreadId(self->GetTid());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700814 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700815 bool success = InsertClass(descriptor, klass); // TODO: just return collision
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700816 if (!success) {
817 // We may fail to insert if we raced with another thread.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700818 klass->SetClinitThreadId(0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700819 klass = LookupClass(descriptor, class_loader);
820 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700821 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700822 } else {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700823 // Finish loading (if necessary) by finding parents
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700824 CHECK(!klass->IsLoaded());
825 if (!LoadSuperAndInterfaces(klass, dex_file)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700826 // Loading failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700827 CHECK(self->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700828 lock.NotifyAll();
829 return NULL;
830 }
831 CHECK(klass->IsLoaded());
832 // Link the class (if necessary)
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700833 CHECK(!klass->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700834 if (!LinkClass(klass)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700835 // Linking failed.
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700836 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700837 lock.NotifyAll();
838 return NULL;
839 }
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700840 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700841 }
842 }
843 }
844 // Link the class if it has not already been linked.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700845 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700846 ObjectLock lock(klass);
847 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700848 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700849 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700850 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700851 return NULL;
852 }
853 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700854 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700855 lock.Wait();
856 }
857 }
858 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700859 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700860 return NULL;
861 }
862 // Return the loaded class. No exceptions should be pending.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700863 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700864 CHECK(!self->IsExceptionPending());
865 return klass;
866}
867
Brian Carlstrom4873d462011-08-21 15:23:39 -0700868// Precomputes size that will be needed for Class, matching LinkStaticFields
869size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
870 const DexFile::ClassDef& dex_class_def) {
871 const byte* class_data = dex_file.GetClassData(dex_class_def);
872 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
873 size_t num_static_fields = header.static_fields_size_;
874 size_t num_ref = 0;
875 size_t num_32 = 0;
876 size_t num_64 = 0;
877 if (num_static_fields != 0) {
878 uint32_t last_idx = 0;
879 for (size_t i = 0; i < num_static_fields; ++i) {
880 DexFile::Field dex_field;
881 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
882 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
883 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
884 char c = descriptor[0];
885 if (c == 'L' || c == '[') {
886 num_ref++;
887 } else if (c == 'J' || c == 'D') {
888 num_64++;
889 } else {
890 num_32++;
891 }
892 }
893 }
894
895 // start with generic class data
896 size_t size = sizeof(Class);
897 // follow with reference fields which must be contiguous at start
898 size += (num_ref * sizeof(uint32_t));
899 // if there are 64-bit fields to add, make sure they are aligned
900 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
901 if (num_32 != 0) {
902 // use an available 32-bit field for padding
903 num_32--;
904 }
905 size += sizeof(uint32_t); // either way, we are adding a word
906 DCHECK_EQ(size, RoundUp(size, 8));
907 }
908 // tack on any 64-bit fields now that alignment is assured
909 size += (num_64 * sizeof(uint64_t));
910 // tack on any remaining 32-bit fields
911 size += (num_32 * sizeof(uint32_t));
912 return size;
913}
914
Brian Carlstromf615a612011-07-23 12:50:34 -0700915void ClassLinker::LoadClass(const DexFile& dex_file,
916 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700917 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700918 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700919 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700920 CHECK(klass->GetDexCache() != NULL);
921 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700922 const byte* class_data = dex_file.GetClassData(dex_class_def);
923 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700924
Brian Carlstromf615a612011-07-23 12:50:34 -0700925 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700926 CHECK(descriptor != NULL);
927
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700928 klass->SetClass(GetClassRoot(kJavaLangClass));
929 if (klass->GetDescriptor() != NULL) {
930 DCHECK(klass->GetDescriptor()->Equals(descriptor));
931 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700932 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700933 }
934 uint32_t access_flags = dex_class_def.access_flags_;
935 // Make sure there aren't any "bonus" flags set, since we use them for runtime
936 // state.
937 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
938 klass->SetAccessFlags(access_flags);
939 klass->SetClassLoader(class_loader);
940 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
941 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700942
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700943 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700944
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700945 size_t num_static_fields = header.static_fields_size_;
946 size_t num_instance_fields = header.instance_fields_size_;
947 size_t num_direct_methods = header.direct_methods_size_;
948 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -0700949
Brian Carlstromc74255f2011-09-11 22:47:39 -0700950 klass->SetSourceFile(intern_table_->InternStrong(dex_file.dexGetSourceFile(dex_class_def)));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700951
952 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -0700953 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700954
955 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700956 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700957 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700958 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700959 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700960 DexFile::Field dex_field;
961 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400962 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700963 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700964 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700965 }
966 }
967
968 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700969 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700970 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700971 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700972 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700973 DexFile::Field dex_field;
974 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -0400975 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700976 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -0700977 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700978 }
979 }
980
981 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700982 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700983 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700984 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -0700985 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700986 for (size_t i = 0; i < num_direct_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -0700987 DexFile::Method dex_method;
988 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -0700989 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700990 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700991 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700992 // TODO: register maps
993 }
994 }
995
996 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700997 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700998 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700999 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001000 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001001 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001002 DexFile::Method dex_method;
1003 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -07001004 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001005 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001006 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001007 // TODO: register maps
1008 }
1009 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001010}
1011
Brian Carlstromf615a612011-07-23 12:50:34 -07001012void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1013 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001014 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001015 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001016 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001017 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001018 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1019 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001020 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001021 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001022 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001023 }
1024 }
1025}
1026
Brian Carlstromf615a612011-07-23 12:50:34 -07001027void ClassLinker::LoadField(const DexFile& dex_file,
1028 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001029 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001030 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001031 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001032 dst->SetDeclaringClass(klass);
1033 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1034 dst->SetTypeIdx(field_id.type_idx_);
1035 dst->SetAccessFlags(src.access_flags_);
1036
1037 // In order to access primitive types using GetTypeDuringLinking we need to
1038 // ensure they are resolved into the dex cache
1039 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1040 if (descriptor[1] == '\0') {
1041 // only the descriptors of primitive types should be 1 character long
1042 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
1043 DCHECK(resolved->IsPrimitive());
1044 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001045}
1046
Brian Carlstromf615a612011-07-23 12:50:34 -07001047void ClassLinker::LoadMethod(const DexFile& dex_file,
1048 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001049 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001050 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001051 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001052 dst->SetDeclaringClass(klass);
Elliott Hughes80609252011-09-23 17:24:51 -07001053 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
1054 dst->SetName(method_name);
1055 if (method_name->Equals("<init>")) {
1056 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1057 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001058 {
1059 int32_t utf16_length;
Elliott Hughes0c424cb2011-08-26 10:16:25 -07001060 std::string utf8(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Brian Carlstromc74255f2011-09-11 22:47:39 -07001061 dst->SetSignature(intern_table_->InternStrong(utf16_length, utf8.c_str()));
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001062 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001063 dst->SetProtoIdx(method_id.proto_idx_);
1064 dst->SetCodeItemOffset(src.code_off_);
1065 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -07001066 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001067 dst->SetAccessFlags(src.access_flags_);
1068 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001069
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001070 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1071 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1072 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1073 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1074 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1075 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001076
Brian Carlstrom934486c2011-07-12 23:42:50 -07001077 // TODO: check for finalize method
1078
Brian Carlstromf615a612011-07-23 12:50:34 -07001079 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001080 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001081 dst->SetNumRegisters(code_item->registers_size_);
1082 dst->SetNumIns(code_item->ins_size_);
1083 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001084 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001085 uint16_t num_args = Method::NumArgRegisters(shorty);
1086 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001087 ++num_args;
1088 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001089 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001090 // TODO: native methods
1091 }
1092}
1093
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001094void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001095 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1096}
1097
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001098void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001099 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001100 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001101 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001102}
1103
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001104void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001105 RegisterDexFile(dex_file, AllocDexCache(dex_file));
1106}
1107
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001108void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom16192862011-09-12 17:50:06 -07001109 MutexLock mu(lock_);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001110 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1111 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001112 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001113 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001114}
1115
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001116const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001117 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001118 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1119 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001120 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001121 }
1122 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001123 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001124 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001125}
1126
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001127DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001128 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001129 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001130 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001131 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001132 }
1133 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001134 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001135 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001136}
1137
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001138Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1139 const char* descriptor,
1140 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001141 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001142 CHECK(primitive_class != NULL);
1143 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1144 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
1145 primitive_class->SetPrimitiveType(type);
1146 primitive_class->SetStatus(Class::kStatusInitialized);
1147 bool success = InsertClass(descriptor, primitive_class);
1148 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1149 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001150}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001151
Brian Carlstrombe977852011-07-19 14:54:54 -07001152// Create an array class (i.e. the class object for the array, not the
1153// array itself). "descriptor" looks like "[C" or "[[[[B" or
1154// "[Ljava/lang/String;".
1155//
1156// If "descriptor" refers to an array of primitives, look up the
1157// primitive type's internally-generated class object.
1158//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001159// "class_loader" is the class loader of the class that's referring to
1160// us. It's used to ensure that we're looking for the element type in
1161// the right context. It does NOT become the class loader for the
1162// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001163//
1164// Returns NULL with an exception raised on failure.
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001165Class* ClassLinker::CreateArrayClass(const StringPiece& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001166 const ClassLoader* class_loader) {
1167 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001168
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001169 // Identify the underlying component type
1170 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001171 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001172 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001173 return NULL;
1174 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001175
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001176 // See if the component type is already loaded. Array classes are
1177 // always associated with the class loader of their underlying
1178 // element type -- an array of Strings goes with the loader for
1179 // java/lang/String -- so we need to look for it there. (The
1180 // caller should have checked for the existence of the class
1181 // before calling here, but they did so with *their* class loader,
1182 // not the component type's loader.)
1183 //
1184 // If we find it, the caller adds "loader" to the class' initiating
1185 // loader list, which should prevent us from going through this again.
1186 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001187 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001188 // are the same, because our caller (FindClass) just did the
1189 // lookup. (Even if we get this wrong we still have correct behavior,
1190 // because we effectively do this lookup again when we add the new
1191 // class to the hash table --- necessary because of possible races with
1192 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001193 if (class_loader != component_type->GetClassLoader()) {
1194 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001195 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001196 return new_class;
1197 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001198 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001199
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001200 // Fill out the fields in the Class.
1201 //
1202 // It is possible to execute some methods against arrays, because
1203 // all arrays are subclasses of java_lang_Object_, so we need to set
1204 // up a vtable. We can just point at the one in java_lang_Object_.
1205 //
1206 // Array classes are simple enough that we don't need to do a full
1207 // link step.
1208
1209 Class* new_class = NULL;
1210 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001211 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001212 if (descriptor == "[Ljava/lang/Class;") {
1213 new_class = GetClassRoot(kClassArrayClass);
1214 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001215 new_class = GetClassRoot(kObjectArrayClass);
1216 } else if (descriptor == "[C") {
1217 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001218 } else if (descriptor == "[I") {
1219 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001220 }
1221 }
1222 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001223 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001224 if (new_class == NULL) {
1225 return NULL;
1226 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001227 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001228 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001229 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001230 if (new_class->GetDescriptor() != NULL) {
1231 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1232 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001233 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.ToString().c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001234 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001235 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001236 new_class->SetSuperClass(java_lang_Object);
1237 new_class->SetVTable(java_lang_Object->GetVTable());
1238 new_class->SetPrimitiveType(Class::kPrimNot);
1239 new_class->SetClassLoader(component_type->GetClassLoader());
1240 new_class->SetStatus(Class::kStatusInitialized);
1241 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001242 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001243
1244
1245 // All arrays have java/lang/Cloneable and java/io/Serializable as
1246 // interfaces. We need to set that up here, so that stuff like
1247 // "instanceof" works right.
1248 //
1249 // Note: The GC could run during the call to FindSystemClass,
1250 // so we need to make sure the class object is GC-valid while we're in
1251 // there. Do this by clearing the interface list so the GC will just
1252 // think that the entries are null.
1253
1254
1255 // Use the single, global copies of "interfaces" and "iftable"
1256 // (remember not to free them for arrays).
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001257 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001258 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001259
1260 // Inherit access flags from the component type. Arrays can't be
1261 // used as a superclass or interface, so we want to add "final"
1262 // and remove "interface".
1263 //
1264 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001265 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001266 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001267 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1268 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001269
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001270 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001271 return new_class;
1272 }
1273 // Another thread must have loaded the class after we
1274 // started but before we finished. Abandon what we've
1275 // done.
1276 //
1277 // (Yes, this happens.)
1278
1279 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001280 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001281 DCHECK(other_class != NULL);
1282 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001283}
1284
1285Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001286 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001287 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001288 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001289 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001290 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001291 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001292 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001293 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001294 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001295 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001296 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001297 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001298 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001299 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001300 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001301 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001302 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001303 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001304 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001305 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001306 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001307 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001308 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001309}
1310
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001311bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass) {
1312 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001313 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001314 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001315 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001316}
1317
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001318Class* ClassLinker::LookupClass(const StringPiece& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001319 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001320 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001321 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001322 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001323 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001324 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001325 return klass;
1326 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001327 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001328 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001329}
1330
jeffhao98eacac2011-09-14 16:11:53 -07001331void ClassLinker::VerifyClass(Class* klass) {
1332 if (klass->IsVerified()) {
1333 return;
1334 }
1335
1336 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001337 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001338
jeffhao5cfd6fb2011-09-27 13:54:29 -07001339 if (DexVerifier::VerifyClass(klass)) {
1340 klass->SetStatus(Class::kStatusVerified);
1341 } else {
1342 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
1343 CHECK(!Thread::Current()->IsExceptionPending()) << PrettyTypeOf(Thread::Current()->GetException());
1344
1345 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
1346 klass->SetStatus(Class::kStatusResolved);
1347 }
jeffhao98eacac2011-09-14 16:11:53 -07001348}
1349
Brian Carlstrom25c33252011-09-18 15:58:35 -07001350bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001351 CHECK(klass->IsResolved() || klass->IsErroneous())
1352 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001353
Carl Shapirob5573532011-07-12 18:22:59 -07001354 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001355
Brian Carlstrom25c33252011-09-18 15:58:35 -07001356 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001357 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001358 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001359 ObjectLock lock(klass);
1360
Brian Carlstromd1422f82011-09-28 11:37:09 -07001361 if (klass->GetStatus() == Class::kStatusInitialized) {
1362 return true;
1363 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001364
Brian Carlstromd1422f82011-09-28 11:37:09 -07001365 if (klass->IsErroneous()) {
1366 ThrowEarlierClassFailure(klass);
1367 return false;
1368 }
1369
1370 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001371 VerifyClass(klass);
1372 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001373 return false;
1374 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001375 }
1376
Brian Carlstrom25c33252011-09-18 15:58:35 -07001377 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1378 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001379 // if the class has a <clinit> but we can't run it during compilation,
1380 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001381 return false;
1382 }
1383
Brian Carlstromd1422f82011-09-28 11:37:09 -07001384 // If the class is kStatusInitializing, either this thread is
1385 // initializing higher up the stack or another thread has beat us
1386 // to initializing and we need to wait. Either way, this
1387 // invocation of InitializeClass will not be responsible for
1388 // running <clinit> and will return.
1389 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001390 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001391 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001392 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001393 return true;
1394 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001395 // No. That's fine. Wait for another thread to finish initializing.
1396 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001397 }
1398
1399 if (!ValidateSuperClassDescriptors(klass)) {
1400 klass->SetStatus(Class::kStatusError);
1401 return false;
1402 }
1403
Brian Carlstromd1422f82011-09-28 11:37:09 -07001404 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001405
Elliott Hughesdcc24742011-09-07 14:02:44 -07001406 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001407 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001408 }
1409
Brian Carlstrom25c33252011-09-18 15:58:35 -07001410 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001411 return false;
1412 }
1413
1414 InitializeStaticFields(klass);
1415
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001416 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001417 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001418 }
1419
1420 {
1421 ObjectLock lock(klass);
1422
1423 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001424 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001425 klass->SetStatus(Class::kStatusError);
1426 } else {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001427 ++Runtime::Current()->GetStats()->class_init_count;
1428 ++self->GetStats()->class_init_count;
1429 // TODO: class_init_time_ns
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001430 klass->SetStatus(Class::kStatusInitialized);
1431 }
1432 lock.NotifyAll();
1433 }
1434
1435 return true;
1436}
1437
Brian Carlstromd1422f82011-09-28 11:37:09 -07001438bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1439 while (true) {
1440 CHECK(!self->IsExceptionPending());
1441 lock.Wait();
1442
1443 // When we wake up, repeat the test for init-in-progress. If
1444 // there's an exception pending (only possible if
1445 // "interruptShouldThrow" was set), bail out.
1446 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001447 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001448 klass->SetStatus(Class::kStatusError);
1449 return false;
1450 }
1451 // Spurious wakeup? Go back to waiting.
1452 if (klass->GetStatus() == Class::kStatusInitializing) {
1453 continue;
1454 }
1455 if (klass->IsErroneous()) {
1456 // The caller wants an exception, but it was thrown in a
1457 // different thread. Synthesize one here.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001458 self->ThrowNewExceptionF("Ljava/lang/NoClassDefFoundError;",
Brian Carlstromd1422f82011-09-28 11:37:09 -07001459 "<clinit> failed for class %s; see exception in other thread",
1460 PrettyDescriptor(klass->GetDescriptor()).c_str());
1461 return false;
1462 }
1463 if (klass->IsInitialized()) {
1464 return true;
1465 }
1466 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1467 }
1468 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1469}
1470
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001471bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1472 if (klass->IsInterface()) {
1473 return true;
1474 }
1475 // begin with the methods local to the superclass
1476 if (klass->HasSuperClass() &&
1477 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1478 const Class* super = klass->GetSuperClass();
1479 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001480 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001481 if (method != super->GetVirtualMethod(i) &&
1482 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001483 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1484
1485 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 -07001486 return false;
1487 }
1488 }
1489 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001490 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1491 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1492 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001493 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1494 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001495 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001496 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001497 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001498 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1499
1500 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 -07001501 return false;
1502 }
1503 }
1504 }
1505 }
1506 return true;
1507}
1508
1509bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001510 const Class* klass1,
1511 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001512 if (method->IsMiranda()) {
1513 return true;
1514 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001515 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001516 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001517 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001518 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001519 const char* descriptor = it->GetDescriptor();
1520 if (descriptor == NULL) {
1521 break;
1522 }
1523 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1524 // Found a non-primitive type.
1525 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1526 return false;
1527 }
1528 }
1529 }
1530 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001531 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001532 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001533 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001534 return false;
1535 }
1536 }
1537 return true;
1538}
1539
1540// Returns true if classes referenced by the descriptor are the
1541// same classes in klass1 as they are in klass2.
1542bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001543 const Class* klass1,
1544 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001545 CHECK(descriptor != NULL);
1546 CHECK(klass1 != NULL);
1547 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001548 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001549 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001550 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001551 // TODO: found2 == NULL
1552 // TODO: lookup found1 in initiating loader list
1553 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001554 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001555 if (found1 == found2) {
1556 return true;
1557 } else {
1558 return false;
1559 }
1560 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001561 return true;
1562}
1563
Brian Carlstrom25c33252011-09-18 15:58:35 -07001564bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001565 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001566 if (!klass->IsInterface() && klass->HasSuperClass()) {
1567 Class* super_class = klass->GetSuperClass();
1568 if (super_class->GetStatus() != Class::kStatusInitialized) {
1569 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001570 Thread* self = Thread::Current();
1571 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001572 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001573 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001574 // TODO: check for a pending exception
1575 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001576 if (!can_run_clinit) {
1577 // Don't set status to error when we can't run <clinit>.
1578 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1579 klass->SetStatus(Class::kStatusVerified);
1580 return false;
1581 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001582 klass->SetStatus(Class::kStatusError);
1583 klass->NotifyAll();
1584 return false;
1585 }
1586 }
1587 }
1588 return true;
1589}
1590
Brian Carlstrom25c33252011-09-18 15:58:35 -07001591bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001592 CHECK(c != NULL);
1593 if (c->IsInitialized()) {
1594 return true;
1595 }
1596
Elliott Hughes5f791332011-09-15 17:45:30 -07001597 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001598 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001599 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001600 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001601}
1602
Brian Carlstromb9edb842011-08-28 16:31:06 -07001603StaticStorageBase* ClassLinker::InitializeStaticStorageFromCode(uint32_t type_idx,
1604 const Method* referrer) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001605 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1606 Class* klass = class_linker->ResolveType(type_idx, referrer);
1607 if (klass == NULL) {
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001608 CHECK(Thread::Current()->IsExceptionPending());
1609 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001610 }
Brian Carlstrom193a44d2011-09-04 12:01:42 -07001611 // If we are the <clinit> of this class, just return our storage.
1612 //
1613 // Do not set the DexCache InitializedStaticStorage, since that
1614 // implies <clinit> has finished running.
1615 if (klass == referrer->GetDeclaringClass() && referrer->GetName()->Equals("<clinit>")) {
1616 return klass;
1617 }
Brian Carlstrom25c33252011-09-18 15:58:35 -07001618 if (!class_linker->EnsureInitialized(klass, true)) {
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001619 CHECK(Thread::Current()->IsExceptionPending());
Ian Rogerscbba6ac2011-09-22 16:28:37 -07001620 return NULL; // Failure - Indicate to caller to deliver exception
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001621 }
Brian Carlstrom848a4b32011-09-04 11:29:27 -07001622 referrer->GetDexCacheInitializedStaticStorage()->Set(type_idx, klass);
Brian Carlstrom1caa2c22011-08-28 13:02:33 -07001623 return klass;
1624}
1625
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001626void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1627 Class* c, std::map<int, Field*>& field_map) {
1628 const ClassLoader* cl = c->GetClassLoader();
1629 const byte* class_data = dex_file.GetClassData(dex_class_def);
1630 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1631 uint32_t last_idx = 0;
1632 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1633 DexFile::Field dex_field;
1634 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1635 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1636 }
1637}
1638
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001639void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001640 size_t num_static_fields = klass->NumStaticFields();
1641 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001642 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001643 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001644 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001645 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001646 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001647 return;
1648 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001649 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001650 const DexFile& dex_file = FindDexFile(dex_cache);
1651 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001652 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001653
1654 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1655 std::map<int, Field*> field_map;
1656 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1657
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001658 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001659 if (addr == NULL) {
1660 // All this class' static fields have default values.
1661 return;
1662 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001663 size_t array_size = DecodeUnsignedLeb128(&addr);
1664 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001665 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001666 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001667 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001668 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001669 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001670 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001671 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001672 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001673 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001674 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001675 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001676 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001677 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001678 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001679 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001680 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001681 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001682 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001683 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001684 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001685 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001686 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001687 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001688 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001689 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001690 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001691 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001692 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001693 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001694 break;
1695 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001696 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001697 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001698 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001699 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001700 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001701 break;
1702 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001703 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001704 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001705 }
1706}
1707
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001708bool ClassLinker::LinkClass(Class* klass) {
1709 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710 if (!LinkSuperClass(klass)) {
1711 return false;
1712 }
1713 if (!LinkMethods(klass)) {
1714 return false;
1715 }
1716 if (!LinkInstanceFields(klass)) {
1717 return false;
1718 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001719 if (!LinkStaticFields(klass)) {
1720 return false;
1721 }
1722 CreateReferenceInstanceOffsets(klass);
1723 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001724 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1725 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001726 return true;
1727}
1728
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001729bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001730 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1731 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1732 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001733 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001734 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001735 return false;
1736 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001737 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001738 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001739 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1740 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07001741 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001742 klass->SetInterface(i, interface);
1743 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001744 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001745 return false;
1746 }
1747 // Verify
1748 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001749 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001750 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001751 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001752 PrettyDescriptor(interface->GetDescriptor()).c_str(),
1753 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001754 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001755 }
1756 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001757 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001758 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001759 return true;
1760}
1761
1762bool ClassLinker::LinkSuperClass(Class* klass) {
1763 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001764 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001765 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001766 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001767 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001768 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769 return false;
1770 }
1771 // TODO: clear finalize attribute
1772 return true;
1773 }
1774 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001775 ThrowLinkageError("No superclass defined for class %s",
1776 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001777 return false;
1778 }
1779 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001780 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001781 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001782 "Superclass %s of %s is %s",
1783 PrettyDescriptor(super->GetDescriptor()).c_str(),
1784 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001785 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001786 return false;
1787 }
1788 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001789 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001790 "Superclass %s is inaccessible by %s",
1791 PrettyDescriptor(super->GetDescriptor()).c_str(),
1792 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001793 return false;
1794 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001795#ifndef NDEBUG
1796 // Ensure super classes are fully resolved prior to resolving fields..
1797 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001798 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001799 super = super->GetSuperClass();
1800 }
1801#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001802 return true;
1803}
1804
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001805// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001806bool ClassLinker::LinkMethods(Class* klass) {
1807 if (klass->IsInterface()) {
1808 // No vtable.
1809 size_t count = klass->NumVirtualMethods();
1810 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001811 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001812 return false;
1813 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001814 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001815 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001816 }
jeffhaobdb76512011-09-07 11:43:16 -07001817 // Link interface method tables
1818 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001819 } else {
1820 // Link virtual method tables
1821 LinkVirtualMethods(klass);
1822
1823 // Link interface method tables
1824 LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001825 }
1826 return true;
1827}
1828
1829bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001830 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001831 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1832 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001833 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001834 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001835 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001836 // See if any of our virtual methods override the superclass.
1837 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001838 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001839 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001840 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001841 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001842 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001843 // Verify
1844 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001845 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001846 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1847 local_method->GetName()->ToModifiedUtf8().c_str(),
1848 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001849 return false;
1850 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001851 vtable->Set(j, local_method);
1852 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001853 break;
1854 }
1855 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001856 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001857 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001858 vtable->Set(actual_count, local_method);
1859 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001860 actual_count += 1;
1861 }
1862 }
1863 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001864 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001865 return false;
1866 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001867 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001868 CHECK_LE(actual_count, max_count);
1869 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001870 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001871 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001872 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001873 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001874 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001875 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001876 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001877 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001878 return false;
1879 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001880 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001881 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001882 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1883 vtable->Set(i, virtual_method);
1884 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001885 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001886 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001887 }
1888 return true;
1889}
1890
1891bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001892 size_t super_ifcount;
1893 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001894 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001895 } else {
1896 super_ifcount = 0;
1897 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001898 size_t ifcount = super_ifcount;
1899 ifcount += klass->NumInterfaces();
1900 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001901 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001902 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001903 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001904 // TODO: enable these asserts with klass status validation
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001905 // DCHECK(klass->GetIfTableCount() == 0);
1906 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001907 return true;
1908 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001909 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001910 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001911 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
1912 for (size_t i = 0; i < super_ifcount; i++) {
1913 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
1914 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001915 }
1916 // Flatten the interface inheritance hierarchy.
1917 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001918 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001919 Class* interface = klass->GetInterface(i);
1920 DCHECK(interface != NULL);
1921 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001922 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001923 "Class %s implements non-interface class %s",
1924 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1925 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001926 return false;
1927 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001928 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001929 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07001930 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001931 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
1932 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001933 }
1934 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001935 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001936 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07001937
1938 // If we're an interface, we don't need the vtable pointers, so we're done.
1939 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001940 return true;
1941 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001942 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001943 for (size_t i = 0; i < ifcount; ++i) {
1944 InterfaceEntry* interface_entry = iftable->Get(i);
1945 Class* interface = interface_entry->GetInterface();
1946 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
1947 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001948 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001949 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
1950 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001951 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07001952 // For each method listed in the interface's method list, find the
1953 // matching method in our class's method list. We want to favor the
1954 // subclass over the superclass, which just requires walking
1955 // back from the end of the vtable. (This only matters if the
1956 // superclass defines a private method and this class redefines
1957 // it -- otherwise it would use the same vtable slot. In .dex files
1958 // those don't end up in the virtual method table, so it shouldn't
1959 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001960 for (k = vtable->GetLength() - 1; k >= 0; --k) {
1961 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001962 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
1963 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001964 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001965 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001966 return false;
1967 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001968 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001969 break;
1970 }
1971 }
1972 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001973 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07001974 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
1975 if (miranda_list[mir]->HasSameNameAndDescriptor(interface_method)) {
1976 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001977 break;
1978 }
1979 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001980 if (miranda_method == NULL) {
1981 // point the interface table at a phantom slot
1982 miranda_method = AllocMethod();
1983 memcpy(miranda_method, interface_method, sizeof(Method));
1984 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001985 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001986 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001987 }
1988 }
1989 }
Elliott Hughes4681c802011-09-25 18:04:37 -07001990 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001991 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07001992 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001993 klass->SetVirtualMethods((old_method_count == 0)
1994 ? AllocObjectArray<Method>(new_method_count)
1995 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001996
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001997 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
1998 CHECK(vtable != NULL);
1999 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002000 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002001 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002002 for (size_t i = 0; i < miranda_list.size(); ++i) {
2003 Method* meth = miranda_list[i]; //AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002004 // TODO: this shouldn't be a memcpy
Elliott Hughes4681c802011-09-25 18:04:37 -07002005 //memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002006 meth->SetDeclaringClass(klass);
2007 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
2008 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002009 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002010 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002011 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002012 // TODO: do not assign to the vtable field until it is fully constructed.
2013 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002014 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002015
2016 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2017 for (int i = 0; i < vtable->GetLength(); ++i) {
2018 CHECK(vtable->Get(i) != NULL);
2019 }
2020
2021// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2022
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002023 return true;
2024}
2025
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002026bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002027 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002028 return LinkFields(klass, true);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002029}
2030
2031bool ClassLinker::LinkStaticFields(Class* klass) {
2032 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002033 size_t allocated_class_size = klass->GetClassSize();
2034 bool success = LinkFields(klass, false);
2035 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002036 return success;
2037}
2038
Brian Carlstromdbc05252011-09-09 01:59:59 -07002039struct LinkFieldsComparator {
2040 bool operator()(const Field* field1, const Field* field2){
2041
2042 // First come reference fields, then 64-bit, and finally 32-bit
2043 const Class* type1 = field1->GetTypeDuringLinking();
2044 const Class* type2 = field2->GetTypeDuringLinking();
2045 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2046 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2047 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2048 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2049 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2050 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2051 if (order1 != order2) {
2052 return order1 < order2;
2053 }
2054
2055 // same basic group? then sort by string.
2056 std::string name1 = field1->GetName()->ToModifiedUtf8();
2057 std::string name2 = field2->GetName()->ToModifiedUtf8();
2058 return name1 < name2;
2059 }
2060};
2061
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002062bool ClassLinker::LinkFields(Class* klass, bool instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002063 size_t num_fields =
2064 instance ? klass->NumInstanceFields() : klass->NumStaticFields();
2065
2066 ObjectArray<Field>* fields =
2067 instance ? klass->GetIFields() : klass->GetSFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002068
2069 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002070 size_t size;
2071 MemberOffset field_offset(0);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002072 if (instance) {
2073 Class* super_class = klass->GetSuperClass();
2074 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002075 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002076 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002077 }
2078 size = field_offset.Uint32Value();
2079 } else {
2080 size = klass->GetClassSize();
Brian Carlstrom693267a2011-09-06 09:25:34 -07002081 field_offset = Class::FieldsOffset();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002082 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002083
Brian Carlstromdbc05252011-09-09 01:59:59 -07002084 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002085
Brian Carlstromdbc05252011-09-09 01:59:59 -07002086 // we want a relatively stable order so that adding new fields
2087 // minimizes distruption of C++ version such as Class and Method.
2088 std::deque<Field*> grouped_and_sorted_fields;
2089 for (size_t i = 0; i < num_fields; i++) {
2090 grouped_and_sorted_fields.push_back(fields->Get(i));
2091 }
2092 std::sort(grouped_and_sorted_fields.begin(),
2093 grouped_and_sorted_fields.end(),
2094 LinkFieldsComparator());
2095
2096 // References should be at the front.
2097 size_t current_field = 0;
2098 size_t num_reference_fields = 0;
2099 for (; current_field < num_fields; current_field++) {
2100 Field* field = grouped_and_sorted_fields.front();
2101 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002102 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002103 bool isPrimitive = type != NULL && type->IsPrimitive();
2104 if (isPrimitive) {
2105 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002106 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002107 grouped_and_sorted_fields.pop_front();
2108 num_reference_fields++;
2109 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002110 field->SetOffset(field_offset);
2111 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002112 }
2113
2114 // Now we want to pack all of the double-wide fields together. If
2115 // we're not aligned, though, we want to shuffle one 32-bit field
2116 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002117 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2118 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2119 Field* field = grouped_and_sorted_fields[i];
2120 const Class* type = field->GetTypeDuringLinking();
2121 CHECK(type != NULL); // should only be working on primitive types
2122 DCHECK(type->IsPrimitive());
2123 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2124 continue;
2125 }
2126 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002127 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002128 // drop the consumed field
2129 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2130 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002131 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002132 // whether we found a 32-bit field for padding or not, we advance
2133 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002134 }
2135
2136 // Alignment is good, shuffle any double-wide fields forward, and
2137 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002138 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2139 while (!grouped_and_sorted_fields.empty()) {
2140 Field* field = grouped_and_sorted_fields.front();
2141 grouped_and_sorted_fields.pop_front();
2142 const Class* type = field->GetTypeDuringLinking();
2143 CHECK(type != NULL); // should only be working on primitive types
2144 DCHECK(type->IsPrimitive());
2145 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002146 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002147 field_offset = MemberOffset(field_offset.Uint32Value() +
2148 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2149 ? sizeof(uint64_t)
2150 : sizeof(uint32_t)));
2151 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002152 }
2153
2154#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002155 // Make sure that all reference fields appear before
2156 // non-reference fields, and all double-wide fields are aligned.
2157 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002158 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002159 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002160 if (false) { // enable to debug field layout
Brian Carlstrom845490b2011-09-19 15:56:53 -07002161 LOG(INFO) << "LinkFields: " << (instance ? "instance" : "static")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002162 << " class=" << PrettyClass(klass)
2163 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002164 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2165 }
2166 const Class* type = field->GetTypeDuringLinking();
2167 if (type != NULL && type->IsPrimitive()) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002168 if (!seen_non_ref) {
2169 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002170 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002171 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002172 } else {
2173 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002174 }
2175 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002176 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002177 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002178 }
2179#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002180 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002181 // Update klass
Brian Carlstromdbc05252011-09-09 01:59:59 -07002182 if (instance) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002183 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002184 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002185 klass->SetObjectSize(size);
2186 }
2187 } else {
2188 klass->SetNumReferenceStaticFields(num_reference_fields);
2189 klass->SetClassSize(size);
2190 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002191 return true;
2192}
2193
2194// Set the bitmap of reference offsets, refOffsets, from the ifields
2195// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002196void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002197 uint32_t reference_offsets = 0;
2198 Class* super_class = klass->GetSuperClass();
2199 if (super_class != NULL) {
2200 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002201 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002202 if (reference_offsets == CLASS_WALK_SUPER) {
2203 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002204 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002205 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002206 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002207 CreateReferenceOffsets(klass, true, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002208}
2209
2210void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002211 CreateReferenceOffsets(klass, false, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002212}
2213
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002214void ClassLinker::CreateReferenceOffsets(Class* klass, bool instance,
2215 uint32_t reference_offsets) {
2216 size_t num_reference_fields =
2217 instance ? klass->NumReferenceInstanceFieldsDuringLinking()
2218 : klass->NumReferenceStaticFieldsDuringLinking();
2219 const ObjectArray<Field>* fields =
2220 instance ? klass->GetIFields() : klass->GetSFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002221 // All of the fields that contain object references are guaranteed
2222 // to be at the beginning of the fields list.
2223 for (size_t i = 0; i < num_reference_fields; ++i) {
2224 // Note that byte_offset is the offset from the beginning of
2225 // object, not the offset into instance data
2226 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002227 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002228 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2229 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2230 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002231 CHECK_NE(new_bit, 0U);
2232 reference_offsets |= new_bit;
2233 } else {
2234 reference_offsets = CLASS_WALK_SUPER;
2235 break;
2236 }
2237 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002238 // Update fields in klass
2239 if (instance) {
2240 klass->SetReferenceInstanceOffsets(reference_offsets);
2241 } else {
2242 klass->SetReferenceStaticOffsets(reference_offsets);
2243 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002244}
2245
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002246String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002247 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002248 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002249 if (resolved != NULL) {
2250 return resolved;
2251 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002252 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2253 int32_t utf16_length = dex_file.GetStringLength(string_id);
2254 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002255 // TODO: remote the const_cast below
2256 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002257 dex_cache->SetResolvedString(string_idx, string);
2258 return string;
2259}
2260
2261Class* ClassLinker::ResolveType(const DexFile& dex_file,
2262 uint32_t type_idx,
2263 DexCache* dex_cache,
2264 const ClassLoader* class_loader) {
2265 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002266 if (resolved == NULL) {
2267 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
2268 if (descriptor[1] == '\0') {
2269 // only the descriptors of primitive types should be 1 character long
2270 resolved = FindPrimitiveClass(descriptor[0]);
2271 } else {
2272 resolved = FindClass(descriptor, class_loader);
2273 }
2274 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002275 Class* check = resolved;
2276 while (check->IsArrayClass()) {
2277 check = check->GetComponentType();
2278 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002279 if (dex_cache != check->GetDexCache()) {
2280 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002281 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002282 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002283 resolved = NULL;
2284 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002285 }
2286 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002287 if (resolved != NULL) {
2288 dex_cache->SetResolvedType(type_idx, resolved);
2289 } else {
2290 DCHECK(Thread::Current()->IsExceptionPending());
2291 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002292 }
2293 return resolved;
2294}
2295
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002296Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2297 uint32_t method_idx,
2298 DexCache* dex_cache,
2299 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002300 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002301 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2302 if (resolved != NULL) {
2303 return resolved;
2304 }
2305 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2306 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2307 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002308 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002309 return NULL;
2310 }
2311
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002312 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002313 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002314 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002315 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002316 } else if (klass->IsInterface()) {
2317 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002318 } else {
2319 resolved = klass->FindVirtualMethod(name, signature);
2320 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002321 if (resolved != NULL) {
2322 dex_cache->SetResolvedMethod(method_idx, resolved);
2323 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002324 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002325 }
2326 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002327}
2328
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002329Field* ClassLinker::ResolveField(const DexFile& dex_file,
2330 uint32_t field_idx,
2331 DexCache* dex_cache,
2332 const ClassLoader* class_loader,
2333 bool is_static) {
2334 Field* resolved = dex_cache->GetResolvedField(field_idx);
2335 if (resolved != NULL) {
2336 return resolved;
2337 }
2338 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2339 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2340 if (klass == NULL) {
2341 return NULL;
2342 }
2343
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002344 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002345 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002346 if (field_type == NULL) {
2347 // TODO: LinkageError?
2348 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2349 << " in " << PrettyClass(klass);
2350 return NULL;
2351}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002352 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002353 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002354 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002355 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002356 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002357 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002358 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002359 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002360 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002361 }
2362 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002363}
2364
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002365void ClassLinker::DumpAllClasses(int flags) const {
2366 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2367 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2368 std::vector<Class*> all_classes;
2369 {
2370 MutexLock mu(lock_);
2371 typedef Table::const_iterator It; // TODO: C++0x auto
2372 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2373 all_classes.push_back(it->second);
2374 }
2375 }
2376
2377 for (size_t i = 0; i < all_classes.size(); ++i) {
2378 all_classes[i]->DumpClass(std::cerr, flags);
2379 }
2380}
2381
Elliott Hughese27955c2011-08-26 15:21:24 -07002382size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002383 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002384 return classes_.size();
2385}
2386
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002387} // namespace art