blob: f610f31e557fc88d94f4c90c362f205b66329fd8 [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004
Brian Carlstromdbc05252011-09-09 01:59:59 -07005#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070011#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070012#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070013#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "dex_verifier.h"
15#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070016#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070018#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070019#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070020#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070021#include "runtime.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070022#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070023#include "space.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070024#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070026#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070028
29namespace art {
30
Elliott Hughes4a2b4172011-09-20 17:08:25 -070031namespace {
32
33void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
34void ThrowNoClassDefFoundError(const char* fmt, ...) {
35 va_list args;
36 va_start(args, fmt);
37 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
38 va_end(args);
39}
40
Elliott Hughese555dc02011-09-25 10:46:35 -070041void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
42void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070043 va_list args;
44 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070045 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070046 va_end(args);
47}
48
49void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
50void ThrowLinkageError(const char* fmt, ...) {
51 va_list args;
52 va_start(args, fmt);
53 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
54 va_end(args);
55}
56
Elliott Hughescc5f9a92011-09-28 19:17:29 -070057void ThrowNoSuchMethodError(const char* kind,
58 Class* c, const StringPiece& name, const StringPiece& signature) {
59 DexCache* dex_cache = c->GetDexCache();
60 std::stringstream msg;
61 msg << "no " << kind << " method " << name << "." << signature
62 << " in class " << c->GetDescriptor()->ToModifiedUtf8()
63 << " or its superclasses";
64 if (dex_cache) {
65 msg << " (defined in " << dex_cache->GetLocation()->ToModifiedUtf8() << ")";
66 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070067 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070068}
69
Elliott Hughes4a2b4172011-09-20 17:08:25 -070070void ThrowEarlierClassFailure(Class* c) {
71 /*
72 * The class failed to initialize on a previous attempt, so we want to throw
73 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
74 * failed in verification, in which case v2 5.4.1 says we need to re-throw
75 * the previous error.
76 */
77 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
78
79 if (c->GetVerifyErrorClass() != NULL) {
80 // TODO: change the verifier to store an _instance_, with a useful detail message?
81 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070082 Thread::Current()->ThrowNewException(error_descriptor.c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -070083 PrettyDescriptor(c->GetDescriptor()).c_str());
84 } else {
85 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
86 }
87}
88
Elliott Hughes4d0207c2011-10-03 19:14:34 -070089void WrapExceptionInInitializer() {
90 JNIEnv* env = Thread::Current()->GetJniEnv();
91
92 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
93 CHECK(cause.get() != NULL);
94
95 env->ExceptionClear();
96
97 // TODO: add java.lang.Error to JniConstants?
98 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
99 CHECK(error_class.get() != NULL);
100 if (env->IsInstanceOf(cause.get(), error_class.get())) {
101 // We only wrap non-Error exceptions; an Error can just be used as-is.
102 env->Throw(cause.get());
103 return;
104 }
105
106 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
107 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
108 CHECK(eiie_class.get() != NULL);
109
110 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
111 CHECK(mid != NULL);
112
113 ScopedLocalRef<jthrowable> eiie(env,
114 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
115 env->Throw(eiie.get());
116}
117
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118}
119
Elliott Hughes418d20f2011-09-22 14:00:39 -0700120const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700121 "Ljava/lang/Class;",
122 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700123 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700124 "[Ljava/lang/Object;",
125 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700126 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700127 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700128 "Ljava/lang/reflect/Field;",
129 "Ljava/lang/reflect/Method;",
130 "Ljava/lang/ClassLoader;",
131 "Ldalvik/system/BaseDexClassLoader;",
132 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700133 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700134 "Z",
135 "B",
136 "C",
137 "D",
138 "F",
139 "I",
140 "J",
141 "S",
142 "V",
143 "[Z",
144 "[B",
145 "[C",
146 "[D",
147 "[F",
148 "[I",
149 "[J",
150 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700151 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700152};
153
Elliott Hughes5f791332011-09-15 17:45:30 -0700154class ObjectLock {
155 public:
156 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
157 CHECK(object != NULL);
158 obj_->MonitorEnter(self_);
159 }
160
161 ~ObjectLock() {
162 obj_->MonitorExit(self_);
163 }
164
165 void Wait() {
166 return Monitor::Wait(self_, obj_, 0, 0, false);
167 }
168
169 void Notify() {
170 obj_->Notify();
171 }
172
173 void NotifyAll() {
174 obj_->NotifyAll();
175 }
176
177 private:
178 Thread* self_;
179 Object* obj_;
180 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
181};
182
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700183ClassLinker* ClassLinker::Create(const std::string& boot_class_path,
184 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700185 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700186 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700187 class_linker->Init(boot_class_path);
188 return class_linker.release();
189}
190
191ClassLinker* ClassLinker::Create(InternTable* intern_table) {
192 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
193 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700194 return class_linker.release();
195}
196
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700197ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700198 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700199 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700200 array_interfaces_(NULL),
201 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700202 init_done_(false),
203 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700204 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700205}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700206
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700207void CreateClassPath(const std::string& class_path,
208 std::vector<const DexFile*>& class_path_vector) {
209 std::vector<std::string> parsed;
210 Split(class_path, ':', parsed);
211 for (size_t i = 0; i < parsed.size(); ++i) {
212 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
213 if (dex_file != NULL) {
214 class_path_vector.push_back(dex_file);
215 }
216 }
217}
218
219void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700220 const Runtime* runtime = Runtime::Current();
221 if (runtime->IsVerboseStartup()) {
222 LOG(INFO) << "ClassLinker::InitFrom entering";
223 }
224
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700225 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700226
Elliott Hughes30646832011-10-13 16:59:46 -0700227 // java_lang_Class comes first, it's needed for AllocClass
228 Class* java_lang_Class = down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700229 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700230 java_lang_Class->SetClass(java_lang_Class);
231 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700232 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700233
Elliott Hughes418d20f2011-09-22 14:00:39 -0700234 // Class[] is used for reflection support.
235 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
236 class_array_class->SetComponentType(java_lang_Class);
237
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700238 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700239 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700240 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700241 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 java_lang_Class->SetSuperClass(java_lang_Object);
243 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700244
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700245 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700246 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700247 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700248
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700249 // Setup the char class to be used for char[]
250 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
251
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700252 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700253 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700254 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700255 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700256
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700257 // Setup String
258 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
259 String::SetClass(java_lang_String);
260 java_lang_String->SetObjectSize(sizeof(String));
261 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400262
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700264 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
265 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700266 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700267 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
268 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
269 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700270
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 // Create storage for root classes, save away our work so far (requires
272 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700273 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700274 CHECK(class_roots_ != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700275 SetClassRoot(kJavaLangClass, java_lang_Class);
276 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700277 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700278 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700279 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700280 SetClassRoot(kJavaLangString, java_lang_String);
281
282 // Setup the primitive type classes.
283 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
284 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
286 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
287 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
288 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
289 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
290 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
291
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700293 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700294 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295
296 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
297 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700298 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
300 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700301 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700303 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700304
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700305 // setup boot_class_path_ and register class_path now that we can
306 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700307 std::vector<const DexFile*> boot_class_path_vector;
308 CreateClassPath(boot_class_path, boot_class_path_vector);
309 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
310 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700311 CHECK(dex_file != NULL);
312 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700313 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700314
Elliott Hughes80609252011-09-23 17:24:51 -0700315 // Constructor, Field, and Method are necessary so that FindClass can link members
316 Class* java_lang_reflect_Constructor = AllocClass(java_lang_Class, sizeof(MethodClass));
317 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
318 CHECK(java_lang_reflect_Constructor != NULL);
319 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
320 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor);
321 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
322
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700323 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
324 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700325 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
327 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
328 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
329 Field::SetClass(java_lang_reflect_Field);
330
331 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Elliott Hughes80609252011-09-23 17:24:51 -0700332 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700333 CHECK(java_lang_reflect_Method != NULL);
334 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
335 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
336 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Elliott Hughes80609252011-09-23 17:24:51 -0700337 Method::SetClasses(java_lang_reflect_Constructor, java_lang_reflect_Method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338
339 // now we can use FindSystemClass
340
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700341 // run char class through InitializePrimitiveClass to finish init
342 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
343 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
344
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700345 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346 java_lang_Object->SetStatus(Class::kStatusNotReady);
347 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
348 CHECK_EQ(java_lang_Object, Object_class);
349 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
350 java_lang_String->SetStatus(Class::kStatusNotReady);
351 Class* String_class = FindSystemClass("Ljava/lang/String;");
352 CHECK_EQ(java_lang_String, String_class);
353 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
354
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700355 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
357 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
358
359 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
360 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
361
362 Class* found_char_array_class = FindSystemClass("[C");
363 CHECK_EQ(char_array_class, found_char_array_class);
364
365 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
366 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
367
368 Class* found_int_array_class = FindSystemClass("[I");
369 CHECK_EQ(int_array_class, found_int_array_class);
370
371 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
372 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
373
374 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
375 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
376
377 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
378 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
379
Elliott Hughes418d20f2011-09-22 14:00:39 -0700380 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
381 CHECK_EQ(class_array_class, found_class_array_class);
382
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700383 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
384 CHECK_EQ(object_array_class, found_object_array_class);
385
386 // Setup the single, global copies of "interfaces" and "iftable"
387 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
388 CHECK(java_lang_Cloneable != NULL);
389 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
390 CHECK(java_io_Serializable != NULL);
391 CHECK(array_interfaces_ != NULL);
392 array_interfaces_->Set(0, java_lang_Cloneable);
393 array_interfaces_->Set(1, java_io_Serializable);
394 // We assume that Cloneable/Serializable don't have superinterfaces --
395 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700396 // supers as well.
397 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
398 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700399
Elliott Hughes418d20f2011-09-22 14:00:39 -0700400 // Sanity check Class[] and Object[]'s interfaces
401 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
402 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
404 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700405
Elliott Hughes80609252011-09-23 17:24:51 -0700406 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700407 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700408 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700409 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410
Elliott Hughes80609252011-09-23 17:24:51 -0700411 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
412 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
413 CHECK_EQ(java_lang_reflect_Constructor, Constructor_class);
414
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700415 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700416 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700417 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418
419 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700420 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700421 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700422
423 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700424 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
425 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700426 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427 java_lang_ref_FinalizerReference->SetAccessFlags(
428 java_lang_ref_FinalizerReference->GetAccessFlags() |
429 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700430 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700431 java_lang_ref_PhantomReference->SetAccessFlags(
432 java_lang_ref_PhantomReference->GetAccessFlags() |
433 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700434 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435 java_lang_ref_SoftReference->SetAccessFlags(
436 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700437 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700438 java_lang_ref_WeakReference->SetAccessFlags(
439 java_lang_ref_WeakReference->GetAccessFlags() |
440 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700441
Brian Carlstromaded5f72011-10-07 17:15:04 -0700442 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700443 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700444 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700445 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
446
447 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
448 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
449 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
450
451 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
452 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
453 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
454 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
455
456 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700457 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
458 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700459 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700460
Brian Carlstroma663ea52011-08-19 23:33:41 -0700461 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700462
463 if (runtime->IsVerboseStartup()) {
464 LOG(INFO) << "ClassLinker::InitFrom exiting";
465 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700466}
467
468void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700469 const Runtime* runtime = Runtime::Current();
470 if (runtime->IsVerboseStartup()) {
471 LOG(INFO) << "ClassLinker::FinishInit entering";
472 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700473
474 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700475 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700476 // as the types of the field can't be resolved prior to the runtime being
477 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700478 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700479 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700480 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
481
Elliott Hughesadb460d2011-10-05 17:02:34 -0700482 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
483
Brian Carlstrom16192862011-09-12 17:50:06 -0700484 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
485 CHECK(pendingNext->GetName()->Equals("pendingNext"));
486 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
487
488 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
489 CHECK(queue->GetName()->Equals("queue"));
Elliott Hughesadb460d2011-10-05 17:02:34 -0700490 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue), java_lang_ref_ReferenceQueue);
Brian Carlstrom16192862011-09-12 17:50:06 -0700491
492 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
493 CHECK(queueNext->GetName()->Equals("queueNext"));
494 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
495
496 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
497 CHECK(referent->GetName()->Equals("referent"));
498 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
499
500 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
501 CHECK(zombie->GetName()->Equals("zombie"));
502 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
503
504 Heap::SetReferenceOffsets(referent->GetOffset(),
505 queue->GetOffset(),
506 queueNext->GetOffset(),
507 pendingNext->GetOffset(),
508 zombie->GetOffset());
509
Brian Carlstroma663ea52011-08-19 23:33:41 -0700510 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700511 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700512 ClassRoot class_root = static_cast<ClassRoot>(i);
513 Class* klass = GetClassRoot(class_root);
514 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700515 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700516 // note SetClassRoot does additional validation.
517 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700518 }
519
Elliott Hughes92f14b22011-10-06 12:29:54 -0700520 CHECK(array_iftable_ != NULL);
521 CHECK(array_interfaces_ != NULL);
522
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700523 // disable the slow paths in FindClass and CreatePrimitiveClass now
524 // that Object, Class, and Object[] are setup
525 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700526
527 if (runtime->IsVerboseStartup()) {
528 LOG(INFO) << "ClassLinker::FinishInit exiting";
529 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700530}
531
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700532void ClassLinker::RunRootClinits() {
533 Thread* self = Thread::Current();
534 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
535 Class* c = GetClassRoot(ClassRoot(i));
536 if (!c->IsArrayClass() && !c->IsPrimitive()) {
537 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700538 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700539 }
540 }
541}
542
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700543OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700544 MutexLock mu(lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700545 const Runtime* runtime = Runtime::Current();
546 if (runtime->IsVerboseStartup()) {
547 LOG(INFO) << "ClassLinker::OpenOat entering";
548 }
549 const ImageHeader& image_header = space->GetImageHeader();
550 String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
551 std::string oat_filename;
552 oat_filename += runtime->GetHostPrefix();
553 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700554 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700555 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700556 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700557 return NULL;
558 }
559 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
560 uint32_t image_oat_checksum = image_header.GetOatChecksum();
561 if (oat_checksum != image_oat_checksum) {
562 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
563 << " to expected oat checksum " << std::hex << oat_checksum
564 << " in image";
565 return NULL;
566 }
567 oat_files_.push_back(oat_file);
568 if (runtime->IsVerboseStartup()) {
569 LOG(INFO) << "ClassLinker::OpenOat exiting";
570 }
571 return oat_file;
572}
573
Brian Carlstromaded5f72011-10-07 17:15:04 -0700574const OatFile* ClassLinker::FindOatFile(const DexFile& dex_file) {
575 MutexLock mu(lock_);
576 std::string dex_file_location = dex_file.GetLocation();
577 std::string location(dex_file_location);
578 CHECK(StringPiece(location).ends_with(".dex")
579 || StringPiece(location).ends_with(".zip")
580 || StringPiece(location).ends_with(".jar")
581 || StringPiece(location).ends_with(".apk"));
582 location.erase(location.size()-3);
583 location += "oat";
584 // TODO: check if dex_file matches an OatDexFile location and checksum
585 return FindOatFile(location);
586}
587
588const OatFile* ClassLinker::FindOatFile(const std::string& location) {
589 for (size_t i = 0; i < oat_files_.size(); i++) {
590 const OatFile* oat_file = oat_files_[i];
591 DCHECK(oat_file != NULL);
592 if (oat_file->GetLocation() == location) {
593 return oat_file;
594 }
595 }
596
597 const OatFile* oat_file = OatFile::Open(location, "", NULL);
598 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700599 if (location.empty() || location[0] != '/') {
600 LOG(ERROR) << "Failed to open oat file from " << location;
601 return NULL;
602 }
603 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
604 std::string art_cache = GetArtCacheOrDie();
605 std::string cache_file(location, 1); // skip leading slash
606 std::replace(cache_file.begin(), cache_file.end(), '/', '@');
607 std::string cache_location = art_cache + "/" + cache_file;
608 oat_file = OatFile::Open(cache_location, "", NULL);
609 if (oat_file == NULL) {
610 LOG(ERROR) << "Failed to open oat file from " << location << " or " << cache_location << ".";
611 return NULL;
612 }
613
614
Brian Carlstromaded5f72011-10-07 17:15:04 -0700615 }
616 return oat_file;
617}
618
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700619void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700620 const Runtime* runtime = Runtime::Current();
621 if (runtime->IsVerboseStartup()) {
622 LOG(INFO) << "ClassLinker::InitFromImage entering";
623 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700624 CHECK(!init_done_);
625
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700626 const std::vector<Space*>& spaces = Heap::GetSpaces();
627 for (size_t i = 0; i < spaces.size(); i++) {
628 Space* space = spaces[i] ;
629 if (space->IsImageSpace()) {
630 OatFile* oat_file = OpenOat(space);
631 CHECK(oat_file != NULL) << "Failed to open oat file for image";
632 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
633 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
634
635 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
636 static_cast<uint32_t>(dex_caches->GetLength()));
637 for (int i = 0; i < dex_caches->GetLength(); i++) {
638 DexCache* dex_cache = dex_caches->Get(i);
639 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
640
641 std::string dex_filename;
642 dex_filename += runtime->GetHostPrefix();
643 dex_filename += dex_file_location;
644 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
645 if (dex_file == NULL) {
646 LOG(FATAL) << "Failed to open dex file " << dex_filename
647 << " referenced from oat file as " << dex_file_location;
648 }
649
Brian Carlstromaded5f72011-10-07 17:15:04 -0700650 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
651 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700652
Brian Carlstromdf143242011-10-10 18:05:34 -0700653 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654 }
655 }
656 }
657
Brian Carlstroma663ea52011-08-19 23:33:41 -0700658 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
659 DCHECK(heap_bitmap != NULL);
660
Brian Carlstroma663ea52011-08-19 23:33:41 -0700661 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700662 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700663
664 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700665 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
666 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700667
Elliott Hughes92f14b22011-10-06 12:29:54 -0700668 // reinit array_interfaces_ and array_iftable_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700669 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
670 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700671 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
672 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700673
Brian Carlstroma663ea52011-08-19 23:33:41 -0700674 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700675 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700676 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700677 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
678 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
679 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
680 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
681 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
682 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
683 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
684 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700685 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700686 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700687
688 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700689
690 if (runtime->IsVerboseStartup()) {
691 LOG(INFO) << "ClassLinker::InitFromImage exiting";
692 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700693}
694
Brian Carlstrom78128a62011-09-15 17:21:19 -0700695void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700696 DCHECK(obj != NULL);
697 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700698 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700699
Brian Carlstromc74255f2011-09-11 22:47:39 -0700700 if (obj->IsString()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700701 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700702 return;
703 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700704 if (obj->IsClass()) {
705 // restore class to ClassLinker::classes_ table
706 Class* klass = obj->AsClass();
707 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
708 class_linker->InsertClass(descriptor, klass);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700709 return;
710 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700711}
712
713// Keep in sync with InitCallback. Anything we visit, we need to
714// reinit references to when reinitializing a ClassLinker from a
715// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700716void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
717 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700718
719 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700720 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700721 }
722
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700723 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700724 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700725 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700726 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700727 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700728 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700729 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700730
Elliott Hughes410c0c82011-09-01 17:58:25 -0700731 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700732}
733
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700734ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700735 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700736 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700737 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700738 BooleanArray::ResetArrayClass();
739 ByteArray::ResetArrayClass();
740 CharArray::ResetArrayClass();
741 DoubleArray::ResetArrayClass();
742 FloatArray::ResetArrayClass();
743 IntArray::ResetArrayClass();
744 LongArray::ResetArrayClass();
745 ShortArray::ResetArrayClass();
746 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700747 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700748 STLDeleteElements(&boot_class_path_);
749 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700750}
751
752DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Elliott Hughes30646832011-10-13 16:59:46 -0700753 String* location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
754 if (location == NULL) {
755 return NULL;
756 }
Brian Carlstrom83db7722011-08-26 17:32:56 -0700757 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Elliott Hughes30646832011-10-13 16:59:46 -0700758 if (dex_cache == NULL) {
759 return NULL;
760 }
761 // TODO: lots of missing null checks hidden in this call...
762 dex_cache->Init(location,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700763 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700764 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700765 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700766 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700767 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
768 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700769 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700770}
771
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700772CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
773 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700774}
775
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700776InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
777 DCHECK(interface->IsInterface());
778 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
779 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
780 interface_entry->SetInterface(interface);
781 return interface_entry;
782}
783
Brian Carlstrom4873d462011-08-21 15:23:39 -0700784Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
785 DCHECK_GE(class_size, sizeof(Class));
786 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700787 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
788 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700789 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700790}
791
Brian Carlstrom4873d462011-08-21 15:23:39 -0700792Class* ClassLinker::AllocClass(size_t class_size) {
793 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700794}
795
Jesse Wilson35baaab2011-08-10 16:18:03 -0400796Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700797 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700798}
799
800Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700801 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700802}
803
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700804ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
805 return ObjectArray<StackTraceElement>::Alloc(
806 GetClassRoot(kJavaLangStackTraceElementArrayClass),
807 length);
808}
809
Brian Carlstromaded5f72011-10-07 17:15:04 -0700810Class* EnsureResolved(Class* klass) {
811 DCHECK(klass != NULL);
812 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700813 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700814 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700815 ObjectLock lock(klass);
816 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700817 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700818 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700819 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700820 return NULL;
821 }
822 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700823 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700824 lock.Wait();
825 }
826 }
827 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700828 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700829 return NULL;
830 }
831 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700832 CHECK(klass->IsResolved()) << PrettyClass(klass);
833 CHECK(!self->IsExceptionPending())
834 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
835 return klass;
836}
837
838Class* ClassLinker::FindClass(const std::string& descriptor,
839 const ClassLoader* class_loader) {
840 CHECK_NE(descriptor.size(), 0U);
841 Thread* self = Thread::Current();
842 DCHECK(self != NULL);
843 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
844 // Find the class in the loaded classes table.
845 Class* klass = LookupClass(descriptor, class_loader);
846 if (klass != NULL) {
847 return EnsureResolved(klass);
848 }
849 if (descriptor.size() == 1) {
850 // only the descriptors of primitive types should be 1 character long
851 return FindPrimitiveClass(descriptor[0]);
852 }
853 // Class is not yet loaded.
854 if (descriptor[0] == '[') {
855 return CreateArrayClass(descriptor, class_loader);
856 }
857 if (class_loader == NULL) {
858 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
859 if (pair.second == NULL) {
860 std::string name(PrintableString(descriptor));
861 ThrowNoClassDefFoundError("Class %s not found in boot class loader", name.c_str());
862 return NULL;
863 }
864 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
865 }
866
867 if (ClassLoader::UseCompileTimeClassPath()) {
868 const std::vector<const DexFile*>& class_path
869 = ClassLoader::GetCompileTimeClassPath(class_loader);
870 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
871 if (pair.second == NULL) {
872 return FindSystemClass(descriptor);
873 }
874 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
875 }
876
877 std::string class_name_string = DescriptorToDot(descriptor);
878 ScopedThreadStateChange(self, Thread::kNative);
879 JNIEnv* env = self->GetJniEnv();
Brian Carlstromdf143242011-10-10 18:05:34 -0700880 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
881 CHECK(c.get() != NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700882 // TODO: cache method?
Brian Carlstromdf143242011-10-10 18:05:34 -0700883 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700884 CHECK(mid != NULL);
Brian Carlstromdf143242011-10-10 18:05:34 -0700885 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -0700886 if (class_name_object.get() == NULL) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700887 return NULL;
888 }
Brian Carlstromdf143242011-10-10 18:05:34 -0700889 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
890 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
891 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700892}
893
894Class* ClassLinker::DefineClass(const std::string& descriptor,
895 const ClassLoader* class_loader,
896 const DexFile& dex_file,
897 const DexFile::ClassDef& dex_class_def) {
898 Class* klass;
899 // Load the class from the dex file.
900 if (!init_done_) {
901 // finish up init of hand crafted class_roots_
902 if (descriptor == "Ljava/lang/Object;") {
903 klass = GetClassRoot(kJavaLangObject);
904 } else if (descriptor == "Ljava/lang/Class;") {
905 klass = GetClassRoot(kJavaLangClass);
906 } else if (descriptor == "Ljava/lang/String;") {
907 klass = GetClassRoot(kJavaLangString);
908 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
909 klass = GetClassRoot(kJavaLangReflectConstructor);
910 } else if (descriptor == "Ljava/lang/reflect/Field;") {
911 klass = GetClassRoot(kJavaLangReflectField);
912 } else if (descriptor == "Ljava/lang/reflect/Method;") {
913 klass = GetClassRoot(kJavaLangReflectMethod);
914 } else {
915 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
916 }
917 } else {
918 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
919 }
920 klass->SetDexCache(FindDexCache(dex_file));
921 LoadClass(dex_file, dex_class_def, klass, class_loader);
922 // Check for a pending exception during load
923 Thread* self = Thread::Current();
924 if (self->IsExceptionPending()) {
925 return NULL;
926 }
927 ObjectLock lock(klass);
928 klass->SetClinitThreadId(self->GetTid());
929 // Add the newly loaded class to the loaded classes table.
930 bool success = InsertClass(descriptor, klass); // TODO: just return collision
931 if (!success) {
932 // We may fail to insert if we raced with another thread.
933 klass->SetClinitThreadId(0);
934 klass = LookupClass(descriptor, class_loader);
935 CHECK(klass != NULL);
936 return klass;
937 }
938 // Finish loading (if necessary) by finding parents
939 CHECK(!klass->IsLoaded());
940 if (!LoadSuperAndInterfaces(klass, dex_file)) {
941 // Loading failed.
942 CHECK(self->IsExceptionPending());
943 lock.NotifyAll();
944 return NULL;
945 }
946 CHECK(klass->IsLoaded());
947 // Link the class (if necessary)
948 CHECK(!klass->IsResolved());
949 if (!LinkClass(klass)) {
950 // Linking failed.
951 CHECK(self->IsExceptionPending());
952 lock.NotifyAll();
953 return NULL;
954 }
955 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700956 return klass;
957}
958
Brian Carlstrom4873d462011-08-21 15:23:39 -0700959// Precomputes size that will be needed for Class, matching LinkStaticFields
960size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
961 const DexFile::ClassDef& dex_class_def) {
962 const byte* class_data = dex_file.GetClassData(dex_class_def);
963 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
964 size_t num_static_fields = header.static_fields_size_;
965 size_t num_ref = 0;
966 size_t num_32 = 0;
967 size_t num_64 = 0;
968 if (num_static_fields != 0) {
969 uint32_t last_idx = 0;
970 for (size_t i = 0; i < num_static_fields; ++i) {
971 DexFile::Field dex_field;
972 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
973 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
974 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
975 char c = descriptor[0];
976 if (c == 'L' || c == '[') {
977 num_ref++;
978 } else if (c == 'J' || c == 'D') {
979 num_64++;
980 } else {
981 num_32++;
982 }
983 }
984 }
985
986 // start with generic class data
987 size_t size = sizeof(Class);
988 // follow with reference fields which must be contiguous at start
989 size += (num_ref * sizeof(uint32_t));
990 // if there are 64-bit fields to add, make sure they are aligned
991 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
992 if (num_32 != 0) {
993 // use an available 32-bit field for padding
994 num_32--;
995 }
996 size += sizeof(uint32_t); // either way, we are adding a word
997 DCHECK_EQ(size, RoundUp(size, 8));
998 }
999 // tack on any 64-bit fields now that alignment is assured
1000 size += (num_64 * sizeof(uint64_t));
1001 // tack on any remaining 32-bit fields
1002 size += (num_32 * sizeof(uint32_t));
1003 return size;
1004}
1005
Brian Carlstrom92827a52011-10-10 15:50:01 -07001006void LinkCode(Method* method, const OatFile::OatClass* oat_class, uint32_t method_index) {
1007 // Every kind of method should at least get an invoke stub from the oat_method.
1008 // non-abstract methods also get their code pointers.
1009 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
1010 oat_method.LinkMethod(method);
1011
1012 if (method->IsAbstract()) {
1013 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1014 return;
1015 }
1016 if (method->IsNative()) {
1017 // unregistering restores the dlsym lookup stub
1018 method->UnregisterNative();
1019 return;
1020 }
1021}
1022
Brian Carlstromf615a612011-07-23 12:50:34 -07001023void ClassLinker::LoadClass(const DexFile& dex_file,
1024 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001025 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001026 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001027 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001028 CHECK(klass->GetDexCache() != NULL);
1029 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001030 const byte* class_data = dex_file.GetClassData(dex_class_def);
1031 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001032
Brian Carlstromf615a612011-07-23 12:50:34 -07001033 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001034 CHECK(descriptor != NULL);
1035
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001036 klass->SetClass(GetClassRoot(kJavaLangClass));
1037 if (klass->GetDescriptor() != NULL) {
1038 DCHECK(klass->GetDescriptor()->Equals(descriptor));
1039 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001040 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001041 if (klass->GetDescriptor() == NULL) {
1042 return;
1043 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001044 }
1045 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001046 // Make sure that none of our runtime-only flags are set.
1047 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001048 klass->SetAccessFlags(access_flags);
1049 klass->SetClassLoader(class_loader);
1050 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
1051 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001052
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001053 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001054
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001055 size_t num_static_fields = header.static_fields_size_;
1056 size_t num_instance_fields = header.instance_fields_size_;
1057 size_t num_direct_methods = header.direct_methods_size_;
1058 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001059
Jesse Wilson6384f642011-10-07 18:08:35 -04001060 const char* source_file = dex_file.dexGetSourceFile(dex_class_def);
1061 if (source_file != NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001062 String* source_file_string = intern_table_->InternStrong(source_file);
1063 if (source_file_string == NULL) {
1064 return;
1065 }
1066 klass->SetSourceFile(source_file_string);
Jesse Wilson6384f642011-10-07 18:08:35 -04001067 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001068
1069 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -07001070 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001071
1072 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001073 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001074 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001075 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001076 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001077 DexFile::Field dex_field;
1078 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001079 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001080 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001081 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001082 }
1083 }
1084
1085 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001086 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001087 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001088 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001089 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001090 DexFile::Field dex_field;
1091 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001092 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001093 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001094 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001095 }
1096 }
1097
Brian Carlstromaded5f72011-10-07 17:15:04 -07001098 UniquePtr<const OatFile::OatClass> oat_class;
1099 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
1100 const OatFile* oat_file = FindOatFile(dex_file);
1101 if (oat_file != NULL) {
1102 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1103 if (oat_dex_file != NULL) {
1104 uint32_t class_def_index;
1105 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1106 CHECK(found) << descriptor;
1107 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001108 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001109 }
1110 }
1111 }
1112 size_t method_index = 0;
1113
Brian Carlstrom934486c2011-07-12 23:42:50 -07001114 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001115 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001116 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001117 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001118 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001119 for (size_t i = 0; i < num_direct_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001120 DexFile::Method dex_method;
1121 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom92827a52011-10-10 15:50:01 -07001122 Method* method = AllocMethod();
1123 klass->SetDirectMethod(i, method);
1124 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001125 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001126 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001127 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001128 }
1129 }
1130
1131 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001132 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001133 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001134 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001135 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001136 for (size_t i = 0; i < num_virtual_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001137 DexFile::Method dex_method;
1138 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom92827a52011-10-10 15:50:01 -07001139 Method* method = AllocMethod();
1140 klass->SetVirtualMethod(i, method);
1141 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001142 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001143 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001144 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001145 }
1146 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001147}
1148
Brian Carlstromf615a612011-07-23 12:50:34 -07001149void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1150 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001151 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001152 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001153 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001154 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001155 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1156 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001157 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001158 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001159 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001160 }
1161 }
1162}
1163
Brian Carlstromf615a612011-07-23 12:50:34 -07001164void ClassLinker::LoadField(const DexFile& dex_file,
1165 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001166 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001167 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001168 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001169 dst->SetDeclaringClass(klass);
1170 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1171 dst->SetTypeIdx(field_id.type_idx_);
1172 dst->SetAccessFlags(src.access_flags_);
1173
1174 // In order to access primitive types using GetTypeDuringLinking we need to
1175 // ensure they are resolved into the dex cache
1176 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1177 if (descriptor[1] == '\0') {
1178 // only the descriptors of primitive types should be 1 character long
1179 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
1180 DCHECK(resolved->IsPrimitive());
1181 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001182}
1183
Brian Carlstromf615a612011-07-23 12:50:34 -07001184void ClassLinker::LoadMethod(const DexFile& dex_file,
1185 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001186 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001187 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001188 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001189 dst->SetDeclaringClass(klass);
Elliott Hughes20cde902011-10-04 17:37:27 -07001190
Elliott Hughes80609252011-09-23 17:24:51 -07001191 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Elliott Hughes30646832011-10-13 16:59:46 -07001192 if (method_name == NULL) {
1193 return;
1194 }
Elliott Hughes80609252011-09-23 17:24:51 -07001195 dst->SetName(method_name);
1196 if (method_name->Equals("<init>")) {
1197 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1198 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001199
1200 int32_t utf16_length;
1201 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Elliott Hughes30646832011-10-13 16:59:46 -07001202 String* signature_string = intern_table_->InternStrong(utf16_length, signature.c_str());
1203 if (signature_string == NULL) {
1204 return;
1205 }
1206 dst->SetSignature(signature_string);
Elliott Hughes20cde902011-10-04 17:37:27 -07001207
1208 if (method_name->Equals("finalize") && signature == "()V") {
1209 /*
1210 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1211 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1212 * exclude it here.
1213 *
1214 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1215 */
1216 if (klass->GetClassLoader() != NULL ||
1217 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1218 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1219 klass->SetFinalizable();
1220 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001221 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001222
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001223 dst->SetProtoIdx(method_id.proto_idx_);
1224 dst->SetCodeItemOffset(src.code_off_);
1225 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Elliott Hughes30646832011-10-13 16:59:46 -07001226 String* shorty_string = intern_table_->InternStrong(shorty);
1227 dst->SetShorty(shorty_string);
1228 if (shorty_string == NULL) {
1229 return;
1230 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001231 dst->SetAccessFlags(src.access_flags_);
1232 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001233
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001234 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1235 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1236 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1237 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1238 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1239 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001240
Brian Carlstrom934486c2011-07-12 23:42:50 -07001241 // TODO: check for finalize method
1242
Brian Carlstromf615a612011-07-23 12:50:34 -07001243 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001244 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001245 dst->SetNumRegisters(code_item->registers_size_);
1246 dst->SetNumIns(code_item->ins_size_);
1247 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001248 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001249 uint16_t num_args = Method::NumArgRegisters(shorty);
1250 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001251 ++num_args;
1252 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001253 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001254 // TODO: native methods
1255 }
1256}
1257
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001258void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001259 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1260}
1261
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001262void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001263 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001264 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001265 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001266}
1267
Brian Carlstromaded5f72011-10-07 17:15:04 -07001268bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
1269 lock_.AssertHeld();
1270 for (size_t i = 0; i != dex_files_.size(); ++i) {
1271 if (dex_files_[i] == &dex_file) {
1272 return true;
1273 }
1274 }
1275 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001276}
1277
Brian Carlstromaded5f72011-10-07 17:15:04 -07001278bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001279 MutexLock mu(lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001280 return IsDexFileRegistered(dex_file);
1281}
1282
1283void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, DexCache* dex_cache) {
1284 lock_.AssertHeld();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001285 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1286 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001287 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001288 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001289}
1290
Brian Carlstromaded5f72011-10-07 17:15:04 -07001291void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
1292 MutexLock mu(lock_);
1293 if (IsDexFileRegisteredLocked(dex_file)) {
1294 return;
1295 }
1296 RegisterDexFileLocked(dex_file, AllocDexCache(dex_file));
1297}
1298
1299void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
1300 MutexLock mu(lock_);
1301 RegisterDexFileLocked(dex_file, dex_cache);
1302}
1303
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001304const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001305 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001306 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1307 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001308 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001309 }
1310 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001311 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001312 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001313}
1314
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001315DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001316 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001317 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001318 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001319 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001320 }
1321 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001322 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001323 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001324}
1325
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001326Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1327 const char* descriptor,
1328 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001329 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001330 CHECK(primitive_class != NULL);
1331 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1332 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001333 CHECK(primitive_class->GetDescriptor() != NULL);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001334 primitive_class->SetPrimitiveType(type);
1335 primitive_class->SetStatus(Class::kStatusInitialized);
1336 bool success = InsertClass(descriptor, primitive_class);
1337 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1338 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001339}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001340
Brian Carlstrombe977852011-07-19 14:54:54 -07001341// Create an array class (i.e. the class object for the array, not the
1342// array itself). "descriptor" looks like "[C" or "[[[[B" or
1343// "[Ljava/lang/String;".
1344//
1345// If "descriptor" refers to an array of primitives, look up the
1346// primitive type's internally-generated class object.
1347//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001348// "class_loader" is the class loader of the class that's referring to
1349// us. It's used to ensure that we're looking for the element type in
1350// the right context. It does NOT become the class loader for the
1351// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001352//
1353// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001354Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001355 const ClassLoader* class_loader) {
1356 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001357
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001358 // Identify the underlying component type
1359 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001360 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001361 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001362 return NULL;
1363 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001364
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001365 // See if the component type is already loaded. Array classes are
1366 // always associated with the class loader of their underlying
1367 // element type -- an array of Strings goes with the loader for
1368 // java/lang/String -- so we need to look for it there. (The
1369 // caller should have checked for the existence of the class
1370 // before calling here, but they did so with *their* class loader,
1371 // not the component type's loader.)
1372 //
1373 // If we find it, the caller adds "loader" to the class' initiating
1374 // loader list, which should prevent us from going through this again.
1375 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001376 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001377 // are the same, because our caller (FindClass) just did the
1378 // lookup. (Even if we get this wrong we still have correct behavior,
1379 // because we effectively do this lookup again when we add the new
1380 // class to the hash table --- necessary because of possible races with
1381 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001382 if (class_loader != component_type->GetClassLoader()) {
1383 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001384 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001385 return new_class;
1386 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001387 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001388
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001389 // Fill out the fields in the Class.
1390 //
1391 // It is possible to execute some methods against arrays, because
1392 // all arrays are subclasses of java_lang_Object_, so we need to set
1393 // up a vtable. We can just point at the one in java_lang_Object_.
1394 //
1395 // Array classes are simple enough that we don't need to do a full
1396 // link step.
1397
1398 Class* new_class = NULL;
1399 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001400 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001401 if (descriptor == "[Ljava/lang/Class;") {
1402 new_class = GetClassRoot(kClassArrayClass);
1403 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001404 new_class = GetClassRoot(kObjectArrayClass);
1405 } else if (descriptor == "[C") {
1406 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001407 } else if (descriptor == "[I") {
1408 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001409 }
1410 }
1411 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001412 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001413 if (new_class == NULL) {
1414 return NULL;
1415 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001416 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001417 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001418 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001419 if (new_class->GetDescriptor() != NULL) {
1420 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1421 } else {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001422 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001423 if (new_class->GetDescriptor() == NULL) {
1424 return NULL;
1425 }
Brian Carlstrom693267a2011-09-06 09:25:34 -07001426 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001427 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001428 new_class->SetSuperClass(java_lang_Object);
1429 new_class->SetVTable(java_lang_Object->GetVTable());
1430 new_class->SetPrimitiveType(Class::kPrimNot);
1431 new_class->SetClassLoader(component_type->GetClassLoader());
1432 new_class->SetStatus(Class::kStatusInitialized);
1433 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001434 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001435
1436
1437 // All arrays have java/lang/Cloneable and java/io/Serializable as
1438 // interfaces. We need to set that up here, so that stuff like
1439 // "instanceof" works right.
1440 //
1441 // Note: The GC could run during the call to FindSystemClass,
1442 // so we need to make sure the class object is GC-valid while we're in
1443 // there. Do this by clearing the interface list so the GC will just
1444 // think that the entries are null.
1445
1446
1447 // Use the single, global copies of "interfaces" and "iftable"
1448 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001449 CHECK(array_interfaces_ != NULL);
1450 CHECK(array_iftable_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001451 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001452 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001453
1454 // Inherit access flags from the component type. Arrays can't be
1455 // used as a superclass or interface, so we want to add "final"
1456 // and remove "interface".
1457 //
1458 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001459 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001460 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001461 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1462 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001463
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001464 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001465 return new_class;
1466 }
1467 // Another thread must have loaded the class after we
1468 // started but before we finished. Abandon what we've
1469 // done.
1470 //
1471 // (Yes, this happens.)
1472
1473 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001474 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001475 DCHECK(other_class != NULL);
1476 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001477}
1478
1479Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001480 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001481 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001482 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001483 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001484 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001485 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001486 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001487 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001488 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001489 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001490 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001491 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001492 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001493 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001494 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001495 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001496 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001497 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001498 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001499 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001500 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001501 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001502 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001503}
1504
Brian Carlstromaded5f72011-10-07 17:15:04 -07001505bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001506 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001507 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001508 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001509 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001510}
1511
Brian Carlstromaded5f72011-10-07 17:15:04 -07001512Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001513 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001514 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001515 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001516 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001517 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001518 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001519 return klass;
1520 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001521 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001522 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001523}
1524
jeffhao98eacac2011-09-14 16:11:53 -07001525void ClassLinker::VerifyClass(Class* klass) {
1526 if (klass->IsVerified()) {
1527 return;
1528 }
1529
1530 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001531 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001532
jeffhao5cfd6fb2011-09-27 13:54:29 -07001533 if (DexVerifier::VerifyClass(klass)) {
1534 klass->SetStatus(Class::kStatusVerified);
1535 } else {
1536 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001537 Thread* self = Thread::Current();
1538 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1539 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
1540 PrettyDescriptor(klass->GetDescriptor()).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001541 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001542 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001543 }
jeffhao98eacac2011-09-14 16:11:53 -07001544}
1545
Jesse Wilson95caa792011-10-12 18:14:17 -04001546Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
1547 ClassLoader* loader, ObjectArray<Method>* methods, ObjectArray<Object>* throws) {
1548 Class* klass = AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass));
1549 CHECK(klass != NULL);
1550 klass->SetObjectSize(sizeof(Proxy));
1551 klass->SetDescriptor(intern_table_->InternStrong(name));
1552 klass->SetAccessFlags(kAccPublic | kAccFinal);
1553 klass->SetClassLoader(loader);
1554 klass->SetStatus(Class::kStatusInitialized);
1555 klass->SetInterfaces(interfaces);
1556
1557 klass->SetDirectMethods(AllocObjectArray<Method>(1));
1558 klass->SetDirectMethod(0, CreateProxyConstructor(klass));
1559
1560 size_t num_virtual_methods = methods->GetLength();
1561 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1562 for (size_t i = 0; i < num_virtual_methods; ++i) {
1563 Method* prototype = methods->Get(i);
1564 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype, throws->Get(i)));
1565 }
1566
1567 if (!LinkMethods(klass)) {
1568 DCHECK(Thread::Current()->IsExceptionPending());
1569 return NULL;
1570 }
1571
1572 return klass;
1573}
1574
1575Method* ClassLinker::CreateProxyConstructor(Class* klass) {
1576 Method* constructor = AllocMethod();
1577 constructor->SetDeclaringClass(klass);
1578 constructor->SetName(intern_table_->InternStrong("<init>"));
1579 constructor->SetSignature(intern_table_->InternStrong("(Ljava/lang/reflect/InvocationHandler;)V"));
1580 constructor->SetShorty(intern_table_->InternStrong("LV"));
1581 constructor->SetAccessFlags(kAccPublic | kAccNative);
1582
1583 // TODO: return type
1584 // TODO: code block
1585
1586 return constructor;
1587}
1588
1589Method* ClassLinker::CreateProxyMethod(Class* klass, Method* prototype, Object* throws) {
1590 Method* method = AllocMethod();
1591 method->SetDeclaringClass(klass);
1592 method->SetName(const_cast<String*>(prototype->GetName()));
1593 method->SetSignature(const_cast<String*>(prototype->GetSignature()));
1594 method->SetShorty(prototype->GetShorty());
1595 method->SetAccessFlags(prototype->GetAccessFlags());
1596 method->SetExceptionTypes(throws);
1597
1598 // TODO: return type
1599 // method->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
1600
1601 // TODO: code block
1602 // method->SetCodeItemOffset(src.code_off_);
1603 // method->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1604 // method->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1605 // method->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1606 // method->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1607 // method->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1608 // method->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
1609 // method->SetNumRegisters(code_item->registers_size_);
1610 // method->SetNumIns(code_item->ins_size_);
1611 // method->SetNumOuts(code_item->outs_size_);
1612 // LinkCode(method, oat_class.get(), method_index);
1613
1614 return method;
1615}
1616
Brian Carlstrom25c33252011-09-18 15:58:35 -07001617bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001618 CHECK(klass->IsResolved() || klass->IsErroneous())
1619 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001620
Carl Shapirob5573532011-07-12 18:22:59 -07001621 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001622
Brian Carlstrom25c33252011-09-18 15:58:35 -07001623 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001624 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001625 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001626 ObjectLock lock(klass);
1627
Brian Carlstromd1422f82011-09-28 11:37:09 -07001628 if (klass->GetStatus() == Class::kStatusInitialized) {
1629 return true;
1630 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001631
Brian Carlstromd1422f82011-09-28 11:37:09 -07001632 if (klass->IsErroneous()) {
1633 ThrowEarlierClassFailure(klass);
1634 return false;
1635 }
1636
1637 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001638 VerifyClass(klass);
1639 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640 return false;
1641 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001642 }
1643
Brian Carlstrom25c33252011-09-18 15:58:35 -07001644 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1645 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001646 // if the class has a <clinit> but we can't run it during compilation,
1647 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001648 return false;
1649 }
1650
Brian Carlstromd1422f82011-09-28 11:37:09 -07001651 // If the class is kStatusInitializing, either this thread is
1652 // initializing higher up the stack or another thread has beat us
1653 // to initializing and we need to wait. Either way, this
1654 // invocation of InitializeClass will not be responsible for
1655 // running <clinit> and will return.
1656 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001657 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001658 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001659 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001660 return true;
1661 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001662 // No. That's fine. Wait for another thread to finish initializing.
1663 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001664 }
1665
1666 if (!ValidateSuperClassDescriptors(klass)) {
1667 klass->SetStatus(Class::kStatusError);
1668 return false;
1669 }
1670
Brian Carlstromd1422f82011-09-28 11:37:09 -07001671 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001672
Elliott Hughesdcc24742011-09-07 14:02:44 -07001673 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001674 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001675 }
1676
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001677 uint64_t t0 = NanoTime();
1678
Brian Carlstrom25c33252011-09-18 15:58:35 -07001679 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001680 return false;
1681 }
1682
1683 InitializeStaticFields(klass);
1684
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001685 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001686 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001687 }
1688
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001689 uint64_t t1 = NanoTime();
1690
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001691 {
1692 ObjectLock lock(klass);
1693
1694 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001695 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001696 klass->SetStatus(Class::kStatusError);
1697 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001698 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1699 RuntimeStats* thread_stats = self->GetStats();
1700 ++global_stats->class_init_count;
1701 ++thread_stats->class_init_count;
1702 global_stats->class_init_time_ns += (t1 - t0);
1703 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001704 klass->SetStatus(Class::kStatusInitialized);
1705 }
1706 lock.NotifyAll();
1707 }
1708
1709 return true;
1710}
1711
Brian Carlstromd1422f82011-09-28 11:37:09 -07001712bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1713 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001714 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001715 lock.Wait();
1716
1717 // When we wake up, repeat the test for init-in-progress. If
1718 // there's an exception pending (only possible if
1719 // "interruptShouldThrow" was set), bail out.
1720 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001721 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001722 klass->SetStatus(Class::kStatusError);
1723 return false;
1724 }
1725 // Spurious wakeup? Go back to waiting.
1726 if (klass->GetStatus() == Class::kStatusInitializing) {
1727 continue;
1728 }
1729 if (klass->IsErroneous()) {
1730 // The caller wants an exception, but it was thrown in a
1731 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001732 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
1733 PrettyDescriptor(klass->GetDescriptor()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001734 return false;
1735 }
1736 if (klass->IsInitialized()) {
1737 return true;
1738 }
1739 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1740 }
1741 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1742}
1743
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001744bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1745 if (klass->IsInterface()) {
1746 return true;
1747 }
1748 // begin with the methods local to the superclass
1749 if (klass->HasSuperClass() &&
1750 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1751 const Class* super = klass->GetSuperClass();
1752 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001753 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001754 if (method != super->GetVirtualMethod(i) &&
1755 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001756 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1757
1758 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 -07001759 return false;
1760 }
1761 }
1762 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001763 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1764 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1765 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001766 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1767 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001768 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001770 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001771 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1772
1773 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 -07001774 return false;
1775 }
1776 }
1777 }
1778 }
1779 return true;
1780}
1781
1782bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001783 const Class* klass1,
1784 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001785 if (method->IsMiranda()) {
1786 return true;
1787 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001788 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001789 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001790 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001791 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001792 const char* descriptor = it->GetDescriptor();
1793 if (descriptor == NULL) {
1794 break;
1795 }
1796 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1797 // Found a non-primitive type.
1798 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1799 return false;
1800 }
1801 }
1802 }
1803 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001804 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001805 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001806 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001807 return false;
1808 }
1809 }
1810 return true;
1811}
1812
1813// Returns true if classes referenced by the descriptor are the
1814// same classes in klass1 as they are in klass2.
1815bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001816 const Class* klass1,
1817 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001818 CHECK(descriptor != NULL);
1819 CHECK(klass1 != NULL);
1820 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001821 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001822 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001823 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001824 // TODO: found2 == NULL
1825 // TODO: lookup found1 in initiating loader list
1826 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001827 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001828 if (found1 == found2) {
1829 return true;
1830 } else {
1831 return false;
1832 }
1833 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001834 return true;
1835}
1836
Brian Carlstrom25c33252011-09-18 15:58:35 -07001837bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001838 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001839 if (!klass->IsInterface() && klass->HasSuperClass()) {
1840 Class* super_class = klass->GetSuperClass();
1841 if (super_class->GetStatus() != Class::kStatusInitialized) {
1842 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001843 Thread* self = Thread::Current();
1844 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001845 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001846 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001847 // TODO: check for a pending exception
1848 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001849 if (!can_run_clinit) {
1850 // Don't set status to error when we can't run <clinit>.
1851 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1852 klass->SetStatus(Class::kStatusVerified);
1853 return false;
1854 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001855 klass->SetStatus(Class::kStatusError);
1856 klass->NotifyAll();
1857 return false;
1858 }
1859 }
1860 }
1861 return true;
1862}
1863
Brian Carlstrom25c33252011-09-18 15:58:35 -07001864bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001865 CHECK(c != NULL);
1866 if (c->IsInitialized()) {
1867 return true;
1868 }
1869
Elliott Hughes5f791332011-09-15 17:45:30 -07001870 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001871 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001872 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001873 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001874}
1875
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001876void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1877 Class* c, std::map<int, Field*>& field_map) {
1878 const ClassLoader* cl = c->GetClassLoader();
1879 const byte* class_data = dex_file.GetClassData(dex_class_def);
1880 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1881 uint32_t last_idx = 0;
1882 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1883 DexFile::Field dex_field;
1884 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1885 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1886 }
1887}
1888
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001889void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001890 size_t num_static_fields = klass->NumStaticFields();
1891 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001892 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001893 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001894 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001895 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001896 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001897 return;
1898 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001899 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001900 const DexFile& dex_file = FindDexFile(dex_cache);
1901 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001902 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001903
1904 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1905 std::map<int, Field*> field_map;
1906 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1907
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001908 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001909 if (addr == NULL) {
1910 // All this class' static fields have default values.
1911 return;
1912 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001913 size_t array_size = DecodeUnsignedLeb128(&addr);
1914 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001915 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001916 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001917 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001918 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001919 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001920 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001921 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001922 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001923 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001924 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001925 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001926 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001927 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001928 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001929 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001930 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001931 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001932 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001933 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001934 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001935 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001936 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001937 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001938 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001939 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001940 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001941 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001942 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001943 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001944 break;
1945 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001946 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001947 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001948 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001949 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001950 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001951 break;
1952 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001953 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001954 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001955 }
1956}
1957
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001958bool ClassLinker::LinkClass(Class* klass) {
1959 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001960 if (!LinkSuperClass(klass)) {
1961 return false;
1962 }
1963 if (!LinkMethods(klass)) {
1964 return false;
1965 }
1966 if (!LinkInstanceFields(klass)) {
1967 return false;
1968 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001969 if (!LinkStaticFields(klass)) {
1970 return false;
1971 }
1972 CreateReferenceInstanceOffsets(klass);
1973 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001974 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1975 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001976 return true;
1977}
1978
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001979bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001980 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1981 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1982 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001983 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001984 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001985 return false;
1986 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001987 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001988 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001989 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1990 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07001991 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001992 klass->SetInterface(i, interface);
1993 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001994 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001995 return false;
1996 }
1997 // Verify
1998 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001999 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002000 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002001 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002002 PrettyDescriptor(interface->GetDescriptor()).c_str(),
2003 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002004 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002005 }
2006 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002007 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002008 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002009 return true;
2010}
2011
2012bool ClassLinker::LinkSuperClass(Class* klass) {
2013 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002014 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002015 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002016 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002017 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002018 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002019 return false;
2020 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002021 return true;
2022 }
2023 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002024 ThrowLinkageError("No superclass defined for class %s",
2025 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002026 return false;
2027 }
2028 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002029 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002030 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002031 "Superclass %s of %s is %s",
2032 PrettyDescriptor(super->GetDescriptor()).c_str(),
2033 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002034 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002035 return false;
2036 }
2037 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002038 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002039 "Superclass %s is inaccessible by %s",
2040 PrettyDescriptor(super->GetDescriptor()).c_str(),
2041 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002042 return false;
2043 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002044
2045 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2046 if (super->IsFinalizable()) {
2047 klass->SetFinalizable();
2048 }
2049
Elliott Hughes2da50362011-10-10 16:57:08 -07002050 // Inherit reference flags (if any) from the superclass.
2051 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2052 if (reference_flags != 0) {
2053 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2054 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002055 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002056 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002057 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
2058 PrettyDescriptor(klass->GetDescriptor()).c_str());
2059 return false;
2060 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002061
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002062#ifndef NDEBUG
2063 // Ensure super classes are fully resolved prior to resolving fields..
2064 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002065 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002066 super = super->GetSuperClass();
2067 }
2068#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002069 return true;
2070}
2071
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002072// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002073bool ClassLinker::LinkMethods(Class* klass) {
2074 if (klass->IsInterface()) {
2075 // No vtable.
2076 size_t count = klass->NumVirtualMethods();
2077 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002078 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002079 return false;
2080 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002081 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002082 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002083 }
jeffhaobdb76512011-09-07 11:43:16 -07002084 // Link interface method tables
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002085 return LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002086 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002087 // Link virtual and interface method tables
2088 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002089 }
2090 return true;
2091}
2092
2093bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002094 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002095 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2096 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002097 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002098 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002099 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002100 // See if any of our virtual methods override the superclass.
2101 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002102 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002103 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002104 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002105 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002106 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002107 // Verify
2108 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002109 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002110 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2111 local_method->GetName()->ToModifiedUtf8().c_str(),
2112 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002113 return false;
2114 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002115 vtable->Set(j, local_method);
2116 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002117 break;
2118 }
2119 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002120 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002121 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002122 vtable->Set(actual_count, local_method);
2123 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002124 actual_count += 1;
2125 }
2126 }
2127 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002128 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002129 return false;
2130 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002131 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002132 CHECK_LE(actual_count, max_count);
2133 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002134 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002135 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002136 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002137 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002138 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002139 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002140 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002141 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002142 return false;
2143 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002144 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002145 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002146 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2147 vtable->Set(i, virtual_method);
2148 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002149 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002150 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002151 }
2152 return true;
2153}
2154
2155bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002156 size_t super_ifcount;
2157 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002158 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002159 } else {
2160 super_ifcount = 0;
2161 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002162 size_t ifcount = super_ifcount;
2163 ifcount += klass->NumInterfaces();
2164 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002165 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002166 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002167 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002168 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002169 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002170 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002171 return true;
2172 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002173 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002174 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002175 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2176 for (size_t i = 0; i < super_ifcount; i++) {
2177 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2178 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002179 }
2180 // Flatten the interface inheritance hierarchy.
2181 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002182 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002183 Class* interface = klass->GetInterface(i);
2184 DCHECK(interface != NULL);
2185 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002186 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002187 "Class %s implements non-interface class %s",
2188 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2189 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002190 return false;
2191 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002192 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002193 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002194 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002195 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2196 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002197 }
2198 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002199 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002200 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002201
2202 // If we're an interface, we don't need the vtable pointers, so we're done.
2203 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002204 return true;
2205 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002206 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002207 for (size_t i = 0; i < ifcount; ++i) {
2208 InterfaceEntry* interface_entry = iftable->Get(i);
2209 Class* interface = interface_entry->GetInterface();
2210 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2211 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002212 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002213 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2214 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002215 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002216 // For each method listed in the interface's method list, find the
2217 // matching method in our class's method list. We want to favor the
2218 // subclass over the superclass, which just requires walking
2219 // back from the end of the vtable. (This only matters if the
2220 // superclass defines a private method and this class redefines
2221 // it -- otherwise it would use the same vtable slot. In .dex files
2222 // those don't end up in the virtual method table, so it shouldn't
2223 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002224 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2225 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002226 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
2227 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002228 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002229 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002230 return false;
2231 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002232 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002233 break;
2234 }
2235 }
2236 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002237 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07002238 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
2239 if (miranda_list[mir]->HasSameNameAndDescriptor(interface_method)) {
2240 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002241 break;
2242 }
2243 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002244 if (miranda_method == NULL) {
2245 // point the interface table at a phantom slot
2246 miranda_method = AllocMethod();
2247 memcpy(miranda_method, interface_method, sizeof(Method));
2248 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002249 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002250 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002251 }
2252 }
2253 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002254 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002255 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002256 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002257 klass->SetVirtualMethods((old_method_count == 0)
2258 ? AllocObjectArray<Method>(new_method_count)
2259 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002260
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002261 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2262 CHECK(vtable != NULL);
2263 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002264 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002265 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002266 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002267 Method* method = miranda_list[i];
2268 method->SetDeclaringClass(klass);
2269 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2270 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2271 klass->SetVirtualMethod(old_method_count + i, method);
2272 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002273 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002274 // TODO: do not assign to the vtable field until it is fully constructed.
2275 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002276 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002277
2278 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2279 for (int i = 0; i < vtable->GetLength(); ++i) {
2280 CHECK(vtable->Get(i) != NULL);
2281 }
2282
2283// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2284
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002285 return true;
2286}
2287
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002289 CHECK(klass != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002290 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002291}
2292
2293bool ClassLinker::LinkStaticFields(Class* klass) {
2294 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002295 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002296 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002297 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002298 return success;
2299}
2300
Brian Carlstromdbc05252011-09-09 01:59:59 -07002301struct LinkFieldsComparator {
2302 bool operator()(const Field* field1, const Field* field2){
2303
2304 // First come reference fields, then 64-bit, and finally 32-bit
2305 const Class* type1 = field1->GetTypeDuringLinking();
2306 const Class* type2 = field2->GetTypeDuringLinking();
2307 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2308 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2309 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2310 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2311 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2312 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2313 if (order1 != order2) {
2314 return order1 < order2;
2315 }
2316
2317 // same basic group? then sort by string.
2318 std::string name1 = field1->GetName()->ToModifiedUtf8();
2319 std::string name2 = field2->GetName()->ToModifiedUtf8();
2320 return name1 < name2;
2321 }
2322};
2323
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002324bool ClassLinker::LinkFields(Class* klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002325 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002326 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002327
2328 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002329 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002330
2331 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002332 size_t size;
2333 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002334 if (is_static) {
2335 size = klass->GetClassSize();
2336 field_offset = Class::FieldsOffset();
2337 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002338 Class* super_class = klass->GetSuperClass();
2339 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002340 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002341 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002342 }
2343 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002344 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002345
Brian Carlstromdbc05252011-09-09 01:59:59 -07002346 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002347
Brian Carlstromdbc05252011-09-09 01:59:59 -07002348 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002349 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002350 std::deque<Field*> grouped_and_sorted_fields;
2351 for (size_t i = 0; i < num_fields; i++) {
2352 grouped_and_sorted_fields.push_back(fields->Get(i));
2353 }
2354 std::sort(grouped_and_sorted_fields.begin(),
2355 grouped_and_sorted_fields.end(),
2356 LinkFieldsComparator());
2357
2358 // References should be at the front.
2359 size_t current_field = 0;
2360 size_t num_reference_fields = 0;
2361 for (; current_field < num_fields; current_field++) {
2362 Field* field = grouped_and_sorted_fields.front();
2363 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002364 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002365 bool isPrimitive = type != NULL && type->IsPrimitive();
2366 if (isPrimitive) {
2367 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002368 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002369 grouped_and_sorted_fields.pop_front();
2370 num_reference_fields++;
2371 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002372 field->SetOffset(field_offset);
2373 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002374 }
2375
2376 // Now we want to pack all of the double-wide fields together. If
2377 // we're not aligned, though, we want to shuffle one 32-bit field
2378 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002379 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2380 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2381 Field* field = grouped_and_sorted_fields[i];
2382 const Class* type = field->GetTypeDuringLinking();
2383 CHECK(type != NULL); // should only be working on primitive types
2384 DCHECK(type->IsPrimitive());
2385 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2386 continue;
2387 }
2388 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002389 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002390 // drop the consumed field
2391 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2392 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002393 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002394 // whether we found a 32-bit field for padding or not, we advance
2395 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002396 }
2397
2398 // Alignment is good, shuffle any double-wide fields forward, and
2399 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002400 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2401 while (!grouped_and_sorted_fields.empty()) {
2402 Field* field = grouped_and_sorted_fields.front();
2403 grouped_and_sorted_fields.pop_front();
2404 const Class* type = field->GetTypeDuringLinking();
2405 CHECK(type != NULL); // should only be working on primitive types
2406 DCHECK(type->IsPrimitive());
2407 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002408 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002409 field_offset = MemberOffset(field_offset.Uint32Value() +
2410 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2411 ? sizeof(uint64_t)
2412 : sizeof(uint32_t)));
2413 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002414 }
2415
Elliott Hughesadb460d2011-10-05 17:02:34 -07002416 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002417 if (!is_static && klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002418 // We know there are no non-reference fields in the Reference classes, and we know
2419 // that 'referent' is alphabetically last, so this is easy...
2420 CHECK_EQ(num_reference_fields, num_fields);
2421 CHECK(fields->Get(num_fields - 1)->GetName()->Equals("referent"));
2422 --num_reference_fields;
2423 }
2424
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002425#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002426 // Make sure that all reference fields appear before
2427 // non-reference fields, and all double-wide fields are aligned.
2428 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002429 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002430 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002431 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002432 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002433 << " class=" << PrettyClass(klass)
2434 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002435 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2436 }
2437 const Class* type = field->GetTypeDuringLinking();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002438 bool is_primitive = (type != NULL && type->IsPrimitive());
2439 if (klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;") && field->GetName()->Equals("referent")) {
2440 is_primitive = true; // We lied above, so we have to expect a lie here.
2441 }
2442 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002443 if (!seen_non_ref) {
2444 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002445 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002446 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002447 } else {
2448 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002449 }
2450 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002451 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002452 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002453 }
2454#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002455 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002456 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002457 if (is_static) {
2458 klass->SetNumReferenceStaticFields(num_reference_fields);
2459 klass->SetClassSize(size);
2460 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002461 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002462 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002463 klass->SetObjectSize(size);
2464 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002465 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002466 return true;
2467}
2468
2469// Set the bitmap of reference offsets, refOffsets, from the ifields
2470// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002471void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002472 uint32_t reference_offsets = 0;
2473 Class* super_class = klass->GetSuperClass();
2474 if (super_class != NULL) {
2475 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002476 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002477 if (reference_offsets == CLASS_WALK_SUPER) {
2478 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002479 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002480 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002481 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002482 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002483}
2484
2485void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002486 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002487}
2488
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002489void ClassLinker::CreateReferenceOffsets(Class* klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002490 uint32_t reference_offsets) {
2491 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002492 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2493 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002494 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002495 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002496 // All of the fields that contain object references are guaranteed
2497 // to be at the beginning of the fields list.
2498 for (size_t i = 0; i < num_reference_fields; ++i) {
2499 // Note that byte_offset is the offset from the beginning of
2500 // object, not the offset into instance data
2501 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002502 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002503 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2504 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2505 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002506 CHECK_NE(new_bit, 0U);
2507 reference_offsets |= new_bit;
2508 } else {
2509 reference_offsets = CLASS_WALK_SUPER;
2510 break;
2511 }
2512 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002513 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002514 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002515 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002516 } else {
2517 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002518 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519}
2520
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002521String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002522 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002523 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002524 if (resolved != NULL) {
2525 return resolved;
2526 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002527 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2528 int32_t utf16_length = dex_file.GetStringLength(string_id);
2529 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002530 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002531 dex_cache->SetResolvedString(string_idx, string);
2532 return string;
2533}
2534
2535Class* ClassLinker::ResolveType(const DexFile& dex_file,
2536 uint32_t type_idx,
2537 DexCache* dex_cache,
2538 const ClassLoader* class_loader) {
2539 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002540 if (resolved == NULL) {
2541 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002542 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002543 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002544 Class* check = resolved;
2545 while (check->IsArrayClass()) {
2546 check = check->GetComponentType();
2547 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002548 if (dex_cache != check->GetDexCache()) {
2549 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002550 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002551 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002552 resolved = NULL;
2553 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002554 }
2555 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002556 if (resolved != NULL) {
2557 dex_cache->SetResolvedType(type_idx, resolved);
2558 } else {
2559 DCHECK(Thread::Current()->IsExceptionPending());
2560 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002561 }
2562 return resolved;
2563}
2564
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002565Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2566 uint32_t method_idx,
2567 DexCache* dex_cache,
2568 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002569 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002570 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2571 if (resolved != NULL) {
2572 return resolved;
2573 }
2574 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2575 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2576 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002577 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002578 return NULL;
2579 }
2580
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002581 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002582 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002583 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002584 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002585 } else if (klass->IsInterface()) {
2586 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002587 } else {
2588 resolved = klass->FindVirtualMethod(name, signature);
2589 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002590 if (resolved != NULL) {
2591 dex_cache->SetResolvedMethod(method_idx, resolved);
2592 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002593 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002594 }
2595 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002596}
2597
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002598Field* ClassLinker::ResolveField(const DexFile& dex_file,
2599 uint32_t field_idx,
2600 DexCache* dex_cache,
2601 const ClassLoader* class_loader,
2602 bool is_static) {
2603 Field* resolved = dex_cache->GetResolvedField(field_idx);
2604 if (resolved != NULL) {
2605 return resolved;
2606 }
2607 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2608 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2609 if (klass == NULL) {
2610 return NULL;
2611 }
2612
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002613 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002614 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002615 if (field_type == NULL) {
2616 // TODO: LinkageError?
2617 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2618 << " in " << PrettyClass(klass);
2619 return NULL;
2620}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002621 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002622 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002623 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002624 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002625 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002626 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002627 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002628 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002629 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002630 }
2631 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002632}
2633
Ian Rogersad25ac52011-10-04 19:13:33 -07002634const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2635 Class* declaring_class = referrer->GetDeclaringClass();
2636 DexCache* dex_cache = declaring_class->GetDexCache();
2637 const DexFile& dex_file = FindDexFile(dex_cache);
2638 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2639 return dex_file.GetShorty(method_id.proto_idx_);
2640}
2641
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002642void ClassLinker::DumpAllClasses(int flags) const {
2643 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2644 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2645 std::vector<Class*> all_classes;
2646 {
2647 MutexLock mu(lock_);
2648 typedef Table::const_iterator It; // TODO: C++0x auto
2649 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2650 all_classes.push_back(it->second);
2651 }
2652 }
2653
2654 for (size_t i = 0; i < all_classes.size(); ++i) {
2655 all_classes[i]->DumpClass(std::cerr, flags);
2656 }
2657}
2658
Elliott Hughese27955c2011-08-26 15:21:24 -07002659size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002660 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002661 return classes_.size();
2662}
2663
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002664} // namespace art