blob: 0299c4aab830ab24602ee8c5e7d27e990052d666 [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
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700227 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700228 Class* java_lang_Class = down_cast<Class*>(
229 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700230 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700231 java_lang_Class->SetClass(java_lang_Class);
232 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700233 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700234
Elliott Hughes418d20f2011-09-22 14:00:39 -0700235 // Class[] is used for reflection support.
236 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
237 class_array_class->SetComponentType(java_lang_Class);
238
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700239 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700240 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700241 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700242 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700243 java_lang_Class->SetSuperClass(java_lang_Object);
244 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700245
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700246 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700247 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700248 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700249
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700250 // Setup the char class to be used for char[]
251 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
252
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700253 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700254 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700255 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700256 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700257
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258 // Setup String
259 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
260 String::SetClass(java_lang_String);
261 java_lang_String->SetObjectSize(sizeof(String));
262 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400263
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700264 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700265 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
266 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700267 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700268 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
269 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
270 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700271
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700272 // Create storage for root classes, save away our work so far (requires
273 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700274 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
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();
554 OatFile* oat_file = OatFile::Open(std::string(oat_filename), "", image_header.GetOatBaseAddr());
555 if (oat_file == NULL) {
556 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image";
557 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) {
599 LOG(ERROR) << "Failed to open oat file " << location;
600 return NULL;
601 }
602 return oat_file;
603}
604
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700605void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700606 const Runtime* runtime = Runtime::Current();
607 if (runtime->IsVerboseStartup()) {
608 LOG(INFO) << "ClassLinker::InitFromImage entering";
609 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700610 CHECK(!init_done_);
611
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700612 const std::vector<Space*>& spaces = Heap::GetSpaces();
613 for (size_t i = 0; i < spaces.size(); i++) {
614 Space* space = spaces[i] ;
615 if (space->IsImageSpace()) {
616 OatFile* oat_file = OpenOat(space);
617 CHECK(oat_file != NULL) << "Failed to open oat file for image";
618 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
619 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
620
621 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
622 static_cast<uint32_t>(dex_caches->GetLength()));
623 for (int i = 0; i < dex_caches->GetLength(); i++) {
624 DexCache* dex_cache = dex_caches->Get(i);
625 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
626
627 std::string dex_filename;
628 dex_filename += runtime->GetHostPrefix();
629 dex_filename += dex_file_location;
630 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
631 if (dex_file == NULL) {
632 LOG(FATAL) << "Failed to open dex file " << dex_filename
633 << " referenced from oat file as " << dex_file_location;
634 }
635
Brian Carlstromaded5f72011-10-07 17:15:04 -0700636 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
637 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700638
Brian Carlstromdf143242011-10-10 18:05:34 -0700639 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700640 }
641 }
642 }
643
Brian Carlstroma663ea52011-08-19 23:33:41 -0700644 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
645 DCHECK(heap_bitmap != NULL);
646
Brian Carlstroma663ea52011-08-19 23:33:41 -0700647 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700648 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700649
650 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700651 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
652 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700653
Elliott Hughes92f14b22011-10-06 12:29:54 -0700654 // reinit array_interfaces_ and array_iftable_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700655 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
656 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700657 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
658 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700659
Brian Carlstroma663ea52011-08-19 23:33:41 -0700660 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700661 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700662 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700663 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
664 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
665 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
666 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
667 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
668 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
669 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
670 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700671 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700672 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700673
674 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700675
676 if (runtime->IsVerboseStartup()) {
677 LOG(INFO) << "ClassLinker::InitFromImage exiting";
678 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700679}
680
Brian Carlstrom78128a62011-09-15 17:21:19 -0700681void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700682 DCHECK(obj != NULL);
683 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700684 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700685
Brian Carlstromc74255f2011-09-11 22:47:39 -0700686 if (obj->IsString()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700687 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700688 return;
689 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700690 if (obj->IsClass()) {
691 // restore class to ClassLinker::classes_ table
692 Class* klass = obj->AsClass();
693 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
694 class_linker->InsertClass(descriptor, klass);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700695 return;
696 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700697}
698
699// Keep in sync with InitCallback. Anything we visit, we need to
700// reinit references to when reinitializing a ClassLinker from a
701// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700702void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
703 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700704
705 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700706 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700707 }
708
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700709 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700710 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700711 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700712 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700713 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700714 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700715 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700716
Elliott Hughes410c0c82011-09-01 17:58:25 -0700717 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700718}
719
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700720ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700721 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700722 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700723 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700724 BooleanArray::ResetArrayClass();
725 ByteArray::ResetArrayClass();
726 CharArray::ResetArrayClass();
727 DoubleArray::ResetArrayClass();
728 FloatArray::ResetArrayClass();
729 IntArray::ResetArrayClass();
730 LongArray::ResetArrayClass();
731 ShortArray::ResetArrayClass();
732 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700733 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700734 STLDeleteElements(&boot_class_path_);
735 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700736}
737
738DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700739 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700740 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700741 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700742 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700743 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700744 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700745 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
746 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700747 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700748}
749
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700750CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
751 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700752}
753
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700754InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
755 DCHECK(interface->IsInterface());
756 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
757 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
758 interface_entry->SetInterface(interface);
759 return interface_entry;
760}
761
Brian Carlstrom4873d462011-08-21 15:23:39 -0700762Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
763 DCHECK_GE(class_size, sizeof(Class));
764 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700765 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
766 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700767 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700768}
769
Brian Carlstrom4873d462011-08-21 15:23:39 -0700770Class* ClassLinker::AllocClass(size_t class_size) {
771 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700772}
773
Jesse Wilson35baaab2011-08-10 16:18:03 -0400774Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700775 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700776}
777
778Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700779 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700780}
781
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700782ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
783 return ObjectArray<StackTraceElement>::Alloc(
784 GetClassRoot(kJavaLangStackTraceElementArrayClass),
785 length);
786}
787
Brian Carlstromaded5f72011-10-07 17:15:04 -0700788Class* EnsureResolved(Class* klass) {
789 DCHECK(klass != NULL);
790 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700791 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700792 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700793 ObjectLock lock(klass);
794 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700795 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700796 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700797 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700798 return NULL;
799 }
800 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700801 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700802 lock.Wait();
803 }
804 }
805 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700806 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700807 return NULL;
808 }
809 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700810 CHECK(klass->IsResolved()) << PrettyClass(klass);
811 CHECK(!self->IsExceptionPending())
812 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
813 return klass;
814}
815
816Class* ClassLinker::FindClass(const std::string& descriptor,
817 const ClassLoader* class_loader) {
818 CHECK_NE(descriptor.size(), 0U);
819 Thread* self = Thread::Current();
820 DCHECK(self != NULL);
821 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
822 // Find the class in the loaded classes table.
823 Class* klass = LookupClass(descriptor, class_loader);
824 if (klass != NULL) {
825 return EnsureResolved(klass);
826 }
827 if (descriptor.size() == 1) {
828 // only the descriptors of primitive types should be 1 character long
829 return FindPrimitiveClass(descriptor[0]);
830 }
831 // Class is not yet loaded.
832 if (descriptor[0] == '[') {
833 return CreateArrayClass(descriptor, class_loader);
834 }
835 if (class_loader == NULL) {
836 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
837 if (pair.second == NULL) {
838 std::string name(PrintableString(descriptor));
839 ThrowNoClassDefFoundError("Class %s not found in boot class loader", name.c_str());
840 return NULL;
841 }
842 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
843 }
844
845 if (ClassLoader::UseCompileTimeClassPath()) {
846 const std::vector<const DexFile*>& class_path
847 = ClassLoader::GetCompileTimeClassPath(class_loader);
848 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
849 if (pair.second == NULL) {
850 return FindSystemClass(descriptor);
851 }
852 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
853 }
854
855 std::string class_name_string = DescriptorToDot(descriptor);
856 ScopedThreadStateChange(self, Thread::kNative);
857 JNIEnv* env = self->GetJniEnv();
Brian Carlstromdf143242011-10-10 18:05:34 -0700858 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
859 CHECK(c.get() != NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700860 // TODO: cache method?
Brian Carlstromdf143242011-10-10 18:05:34 -0700861 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700862 CHECK(mid != NULL);
Brian Carlstromdf143242011-10-10 18:05:34 -0700863 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700864 if (class_name_string == NULL) {
865 return NULL;
866 }
Brian Carlstromdf143242011-10-10 18:05:34 -0700867 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
868 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
869 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700870}
871
872Class* ClassLinker::DefineClass(const std::string& descriptor,
873 const ClassLoader* class_loader,
874 const DexFile& dex_file,
875 const DexFile::ClassDef& dex_class_def) {
876 Class* klass;
877 // Load the class from the dex file.
878 if (!init_done_) {
879 // finish up init of hand crafted class_roots_
880 if (descriptor == "Ljava/lang/Object;") {
881 klass = GetClassRoot(kJavaLangObject);
882 } else if (descriptor == "Ljava/lang/Class;") {
883 klass = GetClassRoot(kJavaLangClass);
884 } else if (descriptor == "Ljava/lang/String;") {
885 klass = GetClassRoot(kJavaLangString);
886 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
887 klass = GetClassRoot(kJavaLangReflectConstructor);
888 } else if (descriptor == "Ljava/lang/reflect/Field;") {
889 klass = GetClassRoot(kJavaLangReflectField);
890 } else if (descriptor == "Ljava/lang/reflect/Method;") {
891 klass = GetClassRoot(kJavaLangReflectMethod);
892 } else {
893 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
894 }
895 } else {
896 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
897 }
898 klass->SetDexCache(FindDexCache(dex_file));
899 LoadClass(dex_file, dex_class_def, klass, class_loader);
900 // Check for a pending exception during load
901 Thread* self = Thread::Current();
902 if (self->IsExceptionPending()) {
903 return NULL;
904 }
905 ObjectLock lock(klass);
906 klass->SetClinitThreadId(self->GetTid());
907 // Add the newly loaded class to the loaded classes table.
908 bool success = InsertClass(descriptor, klass); // TODO: just return collision
909 if (!success) {
910 // We may fail to insert if we raced with another thread.
911 klass->SetClinitThreadId(0);
912 klass = LookupClass(descriptor, class_loader);
913 CHECK(klass != NULL);
914 return klass;
915 }
916 // Finish loading (if necessary) by finding parents
917 CHECK(!klass->IsLoaded());
918 if (!LoadSuperAndInterfaces(klass, dex_file)) {
919 // Loading failed.
920 CHECK(self->IsExceptionPending());
921 lock.NotifyAll();
922 return NULL;
923 }
924 CHECK(klass->IsLoaded());
925 // Link the class (if necessary)
926 CHECK(!klass->IsResolved());
927 if (!LinkClass(klass)) {
928 // Linking failed.
929 CHECK(self->IsExceptionPending());
930 lock.NotifyAll();
931 return NULL;
932 }
933 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700934 return klass;
935}
936
Brian Carlstrom4873d462011-08-21 15:23:39 -0700937// Precomputes size that will be needed for Class, matching LinkStaticFields
938size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
939 const DexFile::ClassDef& dex_class_def) {
940 const byte* class_data = dex_file.GetClassData(dex_class_def);
941 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
942 size_t num_static_fields = header.static_fields_size_;
943 size_t num_ref = 0;
944 size_t num_32 = 0;
945 size_t num_64 = 0;
946 if (num_static_fields != 0) {
947 uint32_t last_idx = 0;
948 for (size_t i = 0; i < num_static_fields; ++i) {
949 DexFile::Field dex_field;
950 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
951 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
952 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
953 char c = descriptor[0];
954 if (c == 'L' || c == '[') {
955 num_ref++;
956 } else if (c == 'J' || c == 'D') {
957 num_64++;
958 } else {
959 num_32++;
960 }
961 }
962 }
963
964 // start with generic class data
965 size_t size = sizeof(Class);
966 // follow with reference fields which must be contiguous at start
967 size += (num_ref * sizeof(uint32_t));
968 // if there are 64-bit fields to add, make sure they are aligned
969 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
970 if (num_32 != 0) {
971 // use an available 32-bit field for padding
972 num_32--;
973 }
974 size += sizeof(uint32_t); // either way, we are adding a word
975 DCHECK_EQ(size, RoundUp(size, 8));
976 }
977 // tack on any 64-bit fields now that alignment is assured
978 size += (num_64 * sizeof(uint64_t));
979 // tack on any remaining 32-bit fields
980 size += (num_32 * sizeof(uint32_t));
981 return size;
982}
983
Brian Carlstrom92827a52011-10-10 15:50:01 -0700984void LinkCode(Method* method, const OatFile::OatClass* oat_class, uint32_t method_index) {
985 // Every kind of method should at least get an invoke stub from the oat_method.
986 // non-abstract methods also get their code pointers.
987 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
988 oat_method.LinkMethod(method);
989
990 if (method->IsAbstract()) {
991 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
992 return;
993 }
994 if (method->IsNative()) {
995 // unregistering restores the dlsym lookup stub
996 method->UnregisterNative();
997 return;
998 }
999}
1000
Brian Carlstromf615a612011-07-23 12:50:34 -07001001void ClassLinker::LoadClass(const DexFile& dex_file,
1002 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001003 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001004 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001005 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001006 CHECK(klass->GetDexCache() != NULL);
1007 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001008 const byte* class_data = dex_file.GetClassData(dex_class_def);
1009 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001010
Brian Carlstromf615a612011-07-23 12:50:34 -07001011 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001012 CHECK(descriptor != NULL);
1013
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001014 klass->SetClass(GetClassRoot(kJavaLangClass));
1015 if (klass->GetDescriptor() != NULL) {
1016 DCHECK(klass->GetDescriptor()->Equals(descriptor));
1017 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001018 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001019 }
1020 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001021 // Make sure that none of our runtime-only flags are set.
1022 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001023 klass->SetAccessFlags(access_flags);
1024 klass->SetClassLoader(class_loader);
1025 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
1026 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001027
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001028 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001029
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001030 size_t num_static_fields = header.static_fields_size_;
1031 size_t num_instance_fields = header.instance_fields_size_;
1032 size_t num_direct_methods = header.direct_methods_size_;
1033 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001034
Jesse Wilson6384f642011-10-07 18:08:35 -04001035 const char* source_file = dex_file.dexGetSourceFile(dex_class_def);
1036 if (source_file != NULL) {
1037 klass->SetSourceFile(intern_table_->InternStrong(source_file));
1038 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001039
1040 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -07001041 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001042
1043 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001044 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001045 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001046 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001047 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001048 DexFile::Field dex_field;
1049 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001050 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001051 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001052 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001053 }
1054 }
1055
1056 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001057 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001058 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001059 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001060 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001061 DexFile::Field dex_field;
1062 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001063 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001064 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001065 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001066 }
1067 }
1068
Brian Carlstromaded5f72011-10-07 17:15:04 -07001069 UniquePtr<const OatFile::OatClass> oat_class;
1070 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
1071 const OatFile* oat_file = FindOatFile(dex_file);
1072 if (oat_file != NULL) {
1073 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1074 if (oat_dex_file != NULL) {
1075 uint32_t class_def_index;
1076 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1077 CHECK(found) << descriptor;
1078 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001079 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001080 }
1081 }
1082 }
1083 size_t method_index = 0;
1084
Brian Carlstrom934486c2011-07-12 23:42:50 -07001085 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001086 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001087 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001088 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001089 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001090 for (size_t i = 0; i < num_direct_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001091 DexFile::Method dex_method;
1092 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom92827a52011-10-10 15:50:01 -07001093 Method* method = AllocMethod();
1094 klass->SetDirectMethod(i, method);
1095 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001096 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001097 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001098 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001099 }
1100 }
1101
1102 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001103 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001104 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001105 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001106 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001107 for (size_t i = 0; i < num_virtual_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001108 DexFile::Method dex_method;
1109 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom92827a52011-10-10 15:50:01 -07001110 Method* method = AllocMethod();
1111 klass->SetVirtualMethod(i, method);
1112 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001113 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001114 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001115 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001116 }
1117 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001118}
1119
Brian Carlstromf615a612011-07-23 12:50:34 -07001120void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1121 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001122 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001123 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001124 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001125 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001126 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1127 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001128 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001129 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001130 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001131 }
1132 }
1133}
1134
Brian Carlstromf615a612011-07-23 12:50:34 -07001135void ClassLinker::LoadField(const DexFile& dex_file,
1136 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001137 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001138 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001139 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001140 dst->SetDeclaringClass(klass);
1141 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1142 dst->SetTypeIdx(field_id.type_idx_);
1143 dst->SetAccessFlags(src.access_flags_);
1144
1145 // In order to access primitive types using GetTypeDuringLinking we need to
1146 // ensure they are resolved into the dex cache
1147 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1148 if (descriptor[1] == '\0') {
1149 // only the descriptors of primitive types should be 1 character long
1150 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
1151 DCHECK(resolved->IsPrimitive());
1152 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001153}
1154
Brian Carlstromf615a612011-07-23 12:50:34 -07001155void ClassLinker::LoadMethod(const DexFile& dex_file,
1156 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001157 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001158 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001159 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001160 dst->SetDeclaringClass(klass);
Elliott Hughes20cde902011-10-04 17:37:27 -07001161
Elliott Hughes80609252011-09-23 17:24:51 -07001162 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
1163 dst->SetName(method_name);
1164 if (method_name->Equals("<init>")) {
1165 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1166 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001167
1168 int32_t utf16_length;
1169 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
1170 dst->SetSignature(intern_table_->InternStrong(utf16_length, signature.c_str()));
1171
1172 if (method_name->Equals("finalize") && signature == "()V") {
1173 /*
1174 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1175 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1176 * exclude it here.
1177 *
1178 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1179 */
1180 if (klass->GetClassLoader() != NULL ||
1181 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1182 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1183 klass->SetFinalizable();
1184 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001185 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001186
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001187 dst->SetProtoIdx(method_id.proto_idx_);
1188 dst->SetCodeItemOffset(src.code_off_);
1189 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -07001190 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001191 dst->SetAccessFlags(src.access_flags_);
1192 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001193
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001194 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1195 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1196 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1197 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1198 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1199 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001200
Brian Carlstrom934486c2011-07-12 23:42:50 -07001201 // TODO: check for finalize method
1202
Brian Carlstromf615a612011-07-23 12:50:34 -07001203 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001204 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001205 dst->SetNumRegisters(code_item->registers_size_);
1206 dst->SetNumIns(code_item->ins_size_);
1207 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001208 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001209 uint16_t num_args = Method::NumArgRegisters(shorty);
1210 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001211 ++num_args;
1212 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001213 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001214 // TODO: native methods
1215 }
1216}
1217
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001218void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001219 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1220}
1221
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001222void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001223 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001224 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001225 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001226}
1227
Brian Carlstromaded5f72011-10-07 17:15:04 -07001228bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
1229 lock_.AssertHeld();
1230 for (size_t i = 0; i != dex_files_.size(); ++i) {
1231 if (dex_files_[i] == &dex_file) {
1232 return true;
1233 }
1234 }
1235 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001236}
1237
Brian Carlstromaded5f72011-10-07 17:15:04 -07001238bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001239 MutexLock mu(lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001240 return IsDexFileRegistered(dex_file);
1241}
1242
1243void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, DexCache* dex_cache) {
1244 lock_.AssertHeld();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001245 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1246 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001247 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001248 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001249}
1250
Brian Carlstromaded5f72011-10-07 17:15:04 -07001251void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
1252 MutexLock mu(lock_);
1253 if (IsDexFileRegisteredLocked(dex_file)) {
1254 return;
1255 }
1256 RegisterDexFileLocked(dex_file, AllocDexCache(dex_file));
1257}
1258
1259void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
1260 MutexLock mu(lock_);
1261 RegisterDexFileLocked(dex_file, dex_cache);
1262}
1263
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001264const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001265 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001266 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1267 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001268 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001269 }
1270 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001271 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001272 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001273}
1274
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001275DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001276 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001277 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001278 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001279 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001280 }
1281 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001282 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001283 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001284}
1285
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001286Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1287 const char* descriptor,
1288 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001289 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001290 CHECK(primitive_class != NULL);
1291 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1292 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
1293 primitive_class->SetPrimitiveType(type);
1294 primitive_class->SetStatus(Class::kStatusInitialized);
1295 bool success = InsertClass(descriptor, primitive_class);
1296 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1297 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001298}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001299
Brian Carlstrombe977852011-07-19 14:54:54 -07001300// Create an array class (i.e. the class object for the array, not the
1301// array itself). "descriptor" looks like "[C" or "[[[[B" or
1302// "[Ljava/lang/String;".
1303//
1304// If "descriptor" refers to an array of primitives, look up the
1305// primitive type's internally-generated class object.
1306//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001307// "class_loader" is the class loader of the class that's referring to
1308// us. It's used to ensure that we're looking for the element type in
1309// the right context. It does NOT become the class loader for the
1310// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001311//
1312// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001313Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001314 const ClassLoader* class_loader) {
1315 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001316
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001317 // Identify the underlying component type
1318 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001319 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001320 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001321 return NULL;
1322 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001323
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001324 // See if the component type is already loaded. Array classes are
1325 // always associated with the class loader of their underlying
1326 // element type -- an array of Strings goes with the loader for
1327 // java/lang/String -- so we need to look for it there. (The
1328 // caller should have checked for the existence of the class
1329 // before calling here, but they did so with *their* class loader,
1330 // not the component type's loader.)
1331 //
1332 // If we find it, the caller adds "loader" to the class' initiating
1333 // loader list, which should prevent us from going through this again.
1334 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001335 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001336 // are the same, because our caller (FindClass) just did the
1337 // lookup. (Even if we get this wrong we still have correct behavior,
1338 // because we effectively do this lookup again when we add the new
1339 // class to the hash table --- necessary because of possible races with
1340 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001341 if (class_loader != component_type->GetClassLoader()) {
1342 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001343 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001344 return new_class;
1345 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001346 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001347
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001348 // Fill out the fields in the Class.
1349 //
1350 // It is possible to execute some methods against arrays, because
1351 // all arrays are subclasses of java_lang_Object_, so we need to set
1352 // up a vtable. We can just point at the one in java_lang_Object_.
1353 //
1354 // Array classes are simple enough that we don't need to do a full
1355 // link step.
1356
1357 Class* new_class = NULL;
1358 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001359 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001360 if (descriptor == "[Ljava/lang/Class;") {
1361 new_class = GetClassRoot(kClassArrayClass);
1362 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001363 new_class = GetClassRoot(kObjectArrayClass);
1364 } else if (descriptor == "[C") {
1365 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001366 } else if (descriptor == "[I") {
1367 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001368 }
1369 }
1370 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001371 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001372 if (new_class == NULL) {
1373 return NULL;
1374 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001375 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001376 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001377 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001378 if (new_class->GetDescriptor() != NULL) {
1379 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1380 } else {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001381 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001382 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001383 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001384 new_class->SetSuperClass(java_lang_Object);
1385 new_class->SetVTable(java_lang_Object->GetVTable());
1386 new_class->SetPrimitiveType(Class::kPrimNot);
1387 new_class->SetClassLoader(component_type->GetClassLoader());
1388 new_class->SetStatus(Class::kStatusInitialized);
1389 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001390 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001391
1392
1393 // All arrays have java/lang/Cloneable and java/io/Serializable as
1394 // interfaces. We need to set that up here, so that stuff like
1395 // "instanceof" works right.
1396 //
1397 // Note: The GC could run during the call to FindSystemClass,
1398 // so we need to make sure the class object is GC-valid while we're in
1399 // there. Do this by clearing the interface list so the GC will just
1400 // think that the entries are null.
1401
1402
1403 // Use the single, global copies of "interfaces" and "iftable"
1404 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001405 CHECK(array_interfaces_ != NULL);
1406 CHECK(array_iftable_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001407 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001408 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001409
1410 // Inherit access flags from the component type. Arrays can't be
1411 // used as a superclass or interface, so we want to add "final"
1412 // and remove "interface".
1413 //
1414 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001415 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001416 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001417 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1418 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001419
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001420 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001421 return new_class;
1422 }
1423 // Another thread must have loaded the class after we
1424 // started but before we finished. Abandon what we've
1425 // done.
1426 //
1427 // (Yes, this happens.)
1428
1429 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001430 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001431 DCHECK(other_class != NULL);
1432 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001433}
1434
1435Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001436 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001437 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001438 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001439 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001440 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001441 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001442 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001443 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001444 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001445 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001446 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001447 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001448 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001449 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001450 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001451 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001452 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001453 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001454 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001455 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001456 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001457 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001458 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001459}
1460
Brian Carlstromaded5f72011-10-07 17:15:04 -07001461bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001462 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001463 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001464 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001465 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001466}
1467
Brian Carlstromaded5f72011-10-07 17:15:04 -07001468Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001469 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001470 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001471 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001472 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001473 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001474 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001475 return klass;
1476 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001477 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001478 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001479}
1480
jeffhao98eacac2011-09-14 16:11:53 -07001481void ClassLinker::VerifyClass(Class* klass) {
1482 if (klass->IsVerified()) {
1483 return;
1484 }
1485
1486 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001487 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001488
jeffhao5cfd6fb2011-09-27 13:54:29 -07001489 if (DexVerifier::VerifyClass(klass)) {
1490 klass->SetStatus(Class::kStatusVerified);
1491 } else {
1492 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001493 Thread* self = Thread::Current();
1494 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1495 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
1496 PrettyDescriptor(klass->GetDescriptor()).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001497 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001498 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001499 }
jeffhao98eacac2011-09-14 16:11:53 -07001500}
1501
Brian Carlstrom25c33252011-09-18 15:58:35 -07001502bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001503 CHECK(klass->IsResolved() || klass->IsErroneous())
1504 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001505
Carl Shapirob5573532011-07-12 18:22:59 -07001506 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001507
Brian Carlstrom25c33252011-09-18 15:58:35 -07001508 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001509 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001510 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001511 ObjectLock lock(klass);
1512
Brian Carlstromd1422f82011-09-28 11:37:09 -07001513 if (klass->GetStatus() == Class::kStatusInitialized) {
1514 return true;
1515 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001516
Brian Carlstromd1422f82011-09-28 11:37:09 -07001517 if (klass->IsErroneous()) {
1518 ThrowEarlierClassFailure(klass);
1519 return false;
1520 }
1521
1522 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001523 VerifyClass(klass);
1524 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001525 return false;
1526 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001527 }
1528
Brian Carlstrom25c33252011-09-18 15:58:35 -07001529 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1530 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001531 // if the class has a <clinit> but we can't run it during compilation,
1532 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001533 return false;
1534 }
1535
Brian Carlstromd1422f82011-09-28 11:37:09 -07001536 // If the class is kStatusInitializing, either this thread is
1537 // initializing higher up the stack or another thread has beat us
1538 // to initializing and we need to wait. Either way, this
1539 // invocation of InitializeClass will not be responsible for
1540 // running <clinit> and will return.
1541 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001542 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001543 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001544 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001545 return true;
1546 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001547 // No. That's fine. Wait for another thread to finish initializing.
1548 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001549 }
1550
1551 if (!ValidateSuperClassDescriptors(klass)) {
1552 klass->SetStatus(Class::kStatusError);
1553 return false;
1554 }
1555
Brian Carlstromd1422f82011-09-28 11:37:09 -07001556 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001557
Elliott Hughesdcc24742011-09-07 14:02:44 -07001558 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001559 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001560 }
1561
Brian Carlstrom25c33252011-09-18 15:58:35 -07001562 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001563 return false;
1564 }
1565
1566 InitializeStaticFields(klass);
1567
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001568 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001569 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001570 }
1571
1572 {
1573 ObjectLock lock(klass);
1574
1575 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001576 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001577 klass->SetStatus(Class::kStatusError);
1578 } else {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001579 ++Runtime::Current()->GetStats()->class_init_count;
1580 ++self->GetStats()->class_init_count;
1581 // TODO: class_init_time_ns
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001582 klass->SetStatus(Class::kStatusInitialized);
1583 }
1584 lock.NotifyAll();
1585 }
1586
1587 return true;
1588}
1589
Brian Carlstromd1422f82011-09-28 11:37:09 -07001590bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1591 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001592 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001593 lock.Wait();
1594
1595 // When we wake up, repeat the test for init-in-progress. If
1596 // there's an exception pending (only possible if
1597 // "interruptShouldThrow" was set), bail out.
1598 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001599 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001600 klass->SetStatus(Class::kStatusError);
1601 return false;
1602 }
1603 // Spurious wakeup? Go back to waiting.
1604 if (klass->GetStatus() == Class::kStatusInitializing) {
1605 continue;
1606 }
1607 if (klass->IsErroneous()) {
1608 // The caller wants an exception, but it was thrown in a
1609 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001610 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
1611 PrettyDescriptor(klass->GetDescriptor()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001612 return false;
1613 }
1614 if (klass->IsInitialized()) {
1615 return true;
1616 }
1617 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1618 }
1619 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1620}
1621
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001622bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1623 if (klass->IsInterface()) {
1624 return true;
1625 }
1626 // begin with the methods local to the superclass
1627 if (klass->HasSuperClass() &&
1628 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1629 const Class* super = klass->GetSuperClass();
1630 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001631 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001632 if (method != super->GetVirtualMethod(i) &&
1633 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001634 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1635
1636 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 -07001637 return false;
1638 }
1639 }
1640 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001641 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1642 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1643 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001644 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1645 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001646 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001647 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001648 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001649 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1650
1651 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 -07001652 return false;
1653 }
1654 }
1655 }
1656 }
1657 return true;
1658}
1659
1660bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001661 const Class* klass1,
1662 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001663 if (method->IsMiranda()) {
1664 return true;
1665 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001666 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001667 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001668 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001669 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001670 const char* descriptor = it->GetDescriptor();
1671 if (descriptor == NULL) {
1672 break;
1673 }
1674 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1675 // Found a non-primitive type.
1676 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1677 return false;
1678 }
1679 }
1680 }
1681 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001682 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001683 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001684 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001685 return false;
1686 }
1687 }
1688 return true;
1689}
1690
1691// Returns true if classes referenced by the descriptor are the
1692// same classes in klass1 as they are in klass2.
1693bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001694 const Class* klass1,
1695 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001696 CHECK(descriptor != NULL);
1697 CHECK(klass1 != NULL);
1698 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001699 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001700 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001701 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001702 // TODO: found2 == NULL
1703 // TODO: lookup found1 in initiating loader list
1704 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001705 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001706 if (found1 == found2) {
1707 return true;
1708 } else {
1709 return false;
1710 }
1711 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001712 return true;
1713}
1714
Brian Carlstrom25c33252011-09-18 15:58:35 -07001715bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001716 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001717 if (!klass->IsInterface() && klass->HasSuperClass()) {
1718 Class* super_class = klass->GetSuperClass();
1719 if (super_class->GetStatus() != Class::kStatusInitialized) {
1720 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001721 Thread* self = Thread::Current();
1722 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001723 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001724 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001725 // TODO: check for a pending exception
1726 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001727 if (!can_run_clinit) {
1728 // Don't set status to error when we can't run <clinit>.
1729 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1730 klass->SetStatus(Class::kStatusVerified);
1731 return false;
1732 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001733 klass->SetStatus(Class::kStatusError);
1734 klass->NotifyAll();
1735 return false;
1736 }
1737 }
1738 }
1739 return true;
1740}
1741
Brian Carlstrom25c33252011-09-18 15:58:35 -07001742bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001743 CHECK(c != NULL);
1744 if (c->IsInitialized()) {
1745 return true;
1746 }
1747
Elliott Hughes5f791332011-09-15 17:45:30 -07001748 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001749 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001750 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001751 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001752}
1753
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001754void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1755 Class* c, std::map<int, Field*>& field_map) {
1756 const ClassLoader* cl = c->GetClassLoader();
1757 const byte* class_data = dex_file.GetClassData(dex_class_def);
1758 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1759 uint32_t last_idx = 0;
1760 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1761 DexFile::Field dex_field;
1762 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1763 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1764 }
1765}
1766
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001767void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001768 size_t num_static_fields = klass->NumStaticFields();
1769 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001770 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001771 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001772 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001773 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001774 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001775 return;
1776 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001777 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001778 const DexFile& dex_file = FindDexFile(dex_cache);
1779 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001780 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001781
1782 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1783 std::map<int, Field*> field_map;
1784 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1785
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001786 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001787 if (addr == NULL) {
1788 // All this class' static fields have default values.
1789 return;
1790 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001791 size_t array_size = DecodeUnsignedLeb128(&addr);
1792 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001793 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001794 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001795 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001796 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001797 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001798 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001799 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001800 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001801 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001802 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001803 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001804 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001805 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001806 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001807 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001808 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001809 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001810 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001811 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001812 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001813 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001814 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001815 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001816 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001817 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001818 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001819 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001820 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001821 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001822 break;
1823 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001824 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001825 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001826 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001827 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001828 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001829 break;
1830 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001831 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001832 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001833 }
1834}
1835
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001836bool ClassLinker::LinkClass(Class* klass) {
1837 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001838 if (!LinkSuperClass(klass)) {
1839 return false;
1840 }
1841 if (!LinkMethods(klass)) {
1842 return false;
1843 }
1844 if (!LinkInstanceFields(klass)) {
1845 return false;
1846 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001847 if (!LinkStaticFields(klass)) {
1848 return false;
1849 }
1850 CreateReferenceInstanceOffsets(klass);
1851 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001852 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1853 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001854 return true;
1855}
1856
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001857bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001858 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1859 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1860 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001861 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001862 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001863 return false;
1864 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001865 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001866 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001867 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1868 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07001869 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001870 klass->SetInterface(i, interface);
1871 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001872 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001873 return false;
1874 }
1875 // Verify
1876 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001877 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001878 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001879 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001880 PrettyDescriptor(interface->GetDescriptor()).c_str(),
1881 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001882 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001883 }
1884 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001885 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001886 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001887 return true;
1888}
1889
1890bool ClassLinker::LinkSuperClass(Class* klass) {
1891 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001892 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001893 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001894 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001895 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001896 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001897 return false;
1898 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001899 return true;
1900 }
1901 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001902 ThrowLinkageError("No superclass defined for class %s",
1903 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001904 return false;
1905 }
1906 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001907 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001908 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001909 "Superclass %s of %s is %s",
1910 PrettyDescriptor(super->GetDescriptor()).c_str(),
1911 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001912 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001913 return false;
1914 }
1915 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001916 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001917 "Superclass %s is inaccessible by %s",
1918 PrettyDescriptor(super->GetDescriptor()).c_str(),
1919 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001920 return false;
1921 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001922
1923 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
1924 if (super->IsFinalizable()) {
1925 klass->SetFinalizable();
1926 }
1927
Elliott Hughes2da50362011-10-10 16:57:08 -07001928 // Inherit reference flags (if any) from the superclass.
1929 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
1930 if (reference_flags != 0) {
1931 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
1932 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07001933 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07001934 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07001935 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
1936 PrettyDescriptor(klass->GetDescriptor()).c_str());
1937 return false;
1938 }
Elliott Hughes2da50362011-10-10 16:57:08 -07001939
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001940#ifndef NDEBUG
1941 // Ensure super classes are fully resolved prior to resolving fields..
1942 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001943 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001944 super = super->GetSuperClass();
1945 }
1946#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001947 return true;
1948}
1949
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001950// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001951bool ClassLinker::LinkMethods(Class* klass) {
1952 if (klass->IsInterface()) {
1953 // No vtable.
1954 size_t count = klass->NumVirtualMethods();
1955 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001956 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001957 return false;
1958 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001959 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001960 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001961 }
jeffhaobdb76512011-09-07 11:43:16 -07001962 // Link interface method tables
Elliott Hughesbc258fa2011-10-06 14:45:21 -07001963 return LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001964 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07001965 // Link virtual and interface method tables
1966 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967 }
1968 return true;
1969}
1970
1971bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001972 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001973 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1974 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001975 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001976 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001977 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001978 // See if any of our virtual methods override the superclass.
1979 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001980 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001981 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001982 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001983 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001984 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001985 // Verify
1986 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001987 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001988 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1989 local_method->GetName()->ToModifiedUtf8().c_str(),
1990 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001991 return false;
1992 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001993 vtable->Set(j, local_method);
1994 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001995 break;
1996 }
1997 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001998 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001999 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002000 vtable->Set(actual_count, local_method);
2001 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002002 actual_count += 1;
2003 }
2004 }
2005 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002006 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002007 return false;
2008 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002009 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002010 CHECK_LE(actual_count, max_count);
2011 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002012 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002013 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002014 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002015 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002016 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002017 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002018 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002019 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 return false;
2021 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002022 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002023 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002024 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2025 vtable->Set(i, virtual_method);
2026 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002027 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002028 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002029 }
2030 return true;
2031}
2032
2033bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002034 size_t super_ifcount;
2035 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002036 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002037 } else {
2038 super_ifcount = 0;
2039 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002040 size_t ifcount = super_ifcount;
2041 ifcount += klass->NumInterfaces();
2042 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002043 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002044 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002045 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002046 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002047 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002048 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002049 return true;
2050 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002051 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002052 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002053 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2054 for (size_t i = 0; i < super_ifcount; i++) {
2055 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2056 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002057 }
2058 // Flatten the interface inheritance hierarchy.
2059 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002060 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002061 Class* interface = klass->GetInterface(i);
2062 DCHECK(interface != NULL);
2063 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002064 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002065 "Class %s implements non-interface class %s",
2066 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2067 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002068 return false;
2069 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002070 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002071 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002072 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002073 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2074 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002075 }
2076 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002077 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002078 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002079
2080 // If we're an interface, we don't need the vtable pointers, so we're done.
2081 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002082 return true;
2083 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002084 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002085 for (size_t i = 0; i < ifcount; ++i) {
2086 InterfaceEntry* interface_entry = iftable->Get(i);
2087 Class* interface = interface_entry->GetInterface();
2088 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2089 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002090 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002091 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2092 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002093 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002094 // For each method listed in the interface's method list, find the
2095 // matching method in our class's method list. We want to favor the
2096 // subclass over the superclass, which just requires walking
2097 // back from the end of the vtable. (This only matters if the
2098 // superclass defines a private method and this class redefines
2099 // it -- otherwise it would use the same vtable slot. In .dex files
2100 // those don't end up in the virtual method table, so it shouldn't
2101 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002102 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2103 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002104 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
2105 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002106 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002107 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002108 return false;
2109 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002110 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002111 break;
2112 }
2113 }
2114 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002115 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07002116 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
2117 if (miranda_list[mir]->HasSameNameAndDescriptor(interface_method)) {
2118 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002119 break;
2120 }
2121 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002122 if (miranda_method == NULL) {
2123 // point the interface table at a phantom slot
2124 miranda_method = AllocMethod();
2125 memcpy(miranda_method, interface_method, sizeof(Method));
2126 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002127 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002128 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002129 }
2130 }
2131 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002132 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002133 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002134 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002135 klass->SetVirtualMethods((old_method_count == 0)
2136 ? AllocObjectArray<Method>(new_method_count)
2137 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002138
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002139 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2140 CHECK(vtable != NULL);
2141 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002142 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002143 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002144 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002145 Method* method = miranda_list[i];
2146 method->SetDeclaringClass(klass);
2147 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2148 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2149 klass->SetVirtualMethod(old_method_count + i, method);
2150 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002151 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002152 // TODO: do not assign to the vtable field until it is fully constructed.
2153 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002154 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002155
2156 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2157 for (int i = 0; i < vtable->GetLength(); ++i) {
2158 CHECK(vtable->Get(i) != NULL);
2159 }
2160
2161// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2162
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002163 return true;
2164}
2165
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002166bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002167 CHECK(klass != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002168 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002169}
2170
2171bool ClassLinker::LinkStaticFields(Class* klass) {
2172 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002173 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002174 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002175 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002176 return success;
2177}
2178
Brian Carlstromdbc05252011-09-09 01:59:59 -07002179struct LinkFieldsComparator {
2180 bool operator()(const Field* field1, const Field* field2){
2181
2182 // First come reference fields, then 64-bit, and finally 32-bit
2183 const Class* type1 = field1->GetTypeDuringLinking();
2184 const Class* type2 = field2->GetTypeDuringLinking();
2185 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2186 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2187 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2188 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2189 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2190 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2191 if (order1 != order2) {
2192 return order1 < order2;
2193 }
2194
2195 // same basic group? then sort by string.
2196 std::string name1 = field1->GetName()->ToModifiedUtf8();
2197 std::string name2 = field2->GetName()->ToModifiedUtf8();
2198 return name1 < name2;
2199 }
2200};
2201
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002202bool ClassLinker::LinkFields(Class* klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002203 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002204 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002205
2206 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002207 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002208
2209 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002210 size_t size;
2211 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002212 if (is_static) {
2213 size = klass->GetClassSize();
2214 field_offset = Class::FieldsOffset();
2215 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002216 Class* super_class = klass->GetSuperClass();
2217 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002218 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002219 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002220 }
2221 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002222 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002223
Brian Carlstromdbc05252011-09-09 01:59:59 -07002224 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002225
Brian Carlstromdbc05252011-09-09 01:59:59 -07002226 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002227 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002228 std::deque<Field*> grouped_and_sorted_fields;
2229 for (size_t i = 0; i < num_fields; i++) {
2230 grouped_and_sorted_fields.push_back(fields->Get(i));
2231 }
2232 std::sort(grouped_and_sorted_fields.begin(),
2233 grouped_and_sorted_fields.end(),
2234 LinkFieldsComparator());
2235
2236 // References should be at the front.
2237 size_t current_field = 0;
2238 size_t num_reference_fields = 0;
2239 for (; current_field < num_fields; current_field++) {
2240 Field* field = grouped_and_sorted_fields.front();
2241 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002242 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002243 bool isPrimitive = type != NULL && type->IsPrimitive();
2244 if (isPrimitive) {
2245 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002246 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002247 grouped_and_sorted_fields.pop_front();
2248 num_reference_fields++;
2249 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002250 field->SetOffset(field_offset);
2251 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002252 }
2253
2254 // Now we want to pack all of the double-wide fields together. If
2255 // we're not aligned, though, we want to shuffle one 32-bit field
2256 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002257 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2258 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2259 Field* field = grouped_and_sorted_fields[i];
2260 const Class* type = field->GetTypeDuringLinking();
2261 CHECK(type != NULL); // should only be working on primitive types
2262 DCHECK(type->IsPrimitive());
2263 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2264 continue;
2265 }
2266 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002267 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002268 // drop the consumed field
2269 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2270 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002271 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002272 // whether we found a 32-bit field for padding or not, we advance
2273 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002274 }
2275
2276 // Alignment is good, shuffle any double-wide fields forward, and
2277 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002278 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2279 while (!grouped_and_sorted_fields.empty()) {
2280 Field* field = grouped_and_sorted_fields.front();
2281 grouped_and_sorted_fields.pop_front();
2282 const Class* type = field->GetTypeDuringLinking();
2283 CHECK(type != NULL); // should only be working on primitive types
2284 DCHECK(type->IsPrimitive());
2285 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002286 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002287 field_offset = MemberOffset(field_offset.Uint32Value() +
2288 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2289 ? sizeof(uint64_t)
2290 : sizeof(uint32_t)));
2291 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002292 }
2293
Elliott Hughesadb460d2011-10-05 17:02:34 -07002294 // 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 -07002295 if (!is_static && klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002296 // We know there are no non-reference fields in the Reference classes, and we know
2297 // that 'referent' is alphabetically last, so this is easy...
2298 CHECK_EQ(num_reference_fields, num_fields);
2299 CHECK(fields->Get(num_fields - 1)->GetName()->Equals("referent"));
2300 --num_reference_fields;
2301 }
2302
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002303#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002304 // Make sure that all reference fields appear before
2305 // non-reference fields, and all double-wide fields are aligned.
2306 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002307 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002308 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002309 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002310 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002311 << " class=" << PrettyClass(klass)
2312 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002313 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2314 }
2315 const Class* type = field->GetTypeDuringLinking();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002316 bool is_primitive = (type != NULL && type->IsPrimitive());
2317 if (klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;") && field->GetName()->Equals("referent")) {
2318 is_primitive = true; // We lied above, so we have to expect a lie here.
2319 }
2320 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002321 if (!seen_non_ref) {
2322 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002323 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002324 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002325 } else {
2326 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002327 }
2328 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002329 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002330 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002331 }
2332#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002333 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002334 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002335 if (is_static) {
2336 klass->SetNumReferenceStaticFields(num_reference_fields);
2337 klass->SetClassSize(size);
2338 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002339 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002340 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002341 klass->SetObjectSize(size);
2342 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002343 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002344 return true;
2345}
2346
2347// Set the bitmap of reference offsets, refOffsets, from the ifields
2348// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002349void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002350 uint32_t reference_offsets = 0;
2351 Class* super_class = klass->GetSuperClass();
2352 if (super_class != NULL) {
2353 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002354 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002355 if (reference_offsets == CLASS_WALK_SUPER) {
2356 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002357 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002359 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002360 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002361}
2362
2363void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002364 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002365}
2366
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002367void ClassLinker::CreateReferenceOffsets(Class* klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002368 uint32_t reference_offsets) {
2369 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002370 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2371 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002372 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002373 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002374 // All of the fields that contain object references are guaranteed
2375 // to be at the beginning of the fields list.
2376 for (size_t i = 0; i < num_reference_fields; ++i) {
2377 // Note that byte_offset is the offset from the beginning of
2378 // object, not the offset into instance data
2379 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002380 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002381 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2382 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2383 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002384 CHECK_NE(new_bit, 0U);
2385 reference_offsets |= new_bit;
2386 } else {
2387 reference_offsets = CLASS_WALK_SUPER;
2388 break;
2389 }
2390 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002391 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002392 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002393 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002394 } else {
2395 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002396 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002397}
2398
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002399String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002400 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002401 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002402 if (resolved != NULL) {
2403 return resolved;
2404 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002405 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2406 int32_t utf16_length = dex_file.GetStringLength(string_id);
2407 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002408 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002409 dex_cache->SetResolvedString(string_idx, string);
2410 return string;
2411}
2412
2413Class* ClassLinker::ResolveType(const DexFile& dex_file,
2414 uint32_t type_idx,
2415 DexCache* dex_cache,
2416 const ClassLoader* class_loader) {
2417 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002418 if (resolved == NULL) {
2419 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002420 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002421 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002422 Class* check = resolved;
2423 while (check->IsArrayClass()) {
2424 check = check->GetComponentType();
2425 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002426 if (dex_cache != check->GetDexCache()) {
2427 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002428 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002429 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002430 resolved = NULL;
2431 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002432 }
2433 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002434 if (resolved != NULL) {
2435 dex_cache->SetResolvedType(type_idx, resolved);
2436 } else {
2437 DCHECK(Thread::Current()->IsExceptionPending());
2438 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002439 }
2440 return resolved;
2441}
2442
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002443Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2444 uint32_t method_idx,
2445 DexCache* dex_cache,
2446 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002447 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002448 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2449 if (resolved != NULL) {
2450 return resolved;
2451 }
2452 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2453 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2454 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002455 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002456 return NULL;
2457 }
2458
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002459 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002460 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002461 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002462 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002463 } else if (klass->IsInterface()) {
2464 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002465 } else {
2466 resolved = klass->FindVirtualMethod(name, signature);
2467 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002468 if (resolved != NULL) {
2469 dex_cache->SetResolvedMethod(method_idx, resolved);
2470 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002471 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002472 }
2473 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002474}
2475
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002476Field* ClassLinker::ResolveField(const DexFile& dex_file,
2477 uint32_t field_idx,
2478 DexCache* dex_cache,
2479 const ClassLoader* class_loader,
2480 bool is_static) {
2481 Field* resolved = dex_cache->GetResolvedField(field_idx);
2482 if (resolved != NULL) {
2483 return resolved;
2484 }
2485 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2486 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2487 if (klass == NULL) {
2488 return NULL;
2489 }
2490
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002491 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002492 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002493 if (field_type == NULL) {
2494 // TODO: LinkageError?
2495 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2496 << " in " << PrettyClass(klass);
2497 return NULL;
2498}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002499 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002500 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002501 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002502 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002503 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002504 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002505 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002506 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002507 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002508 }
2509 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002510}
2511
Ian Rogersad25ac52011-10-04 19:13:33 -07002512const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2513 Class* declaring_class = referrer->GetDeclaringClass();
2514 DexCache* dex_cache = declaring_class->GetDexCache();
2515 const DexFile& dex_file = FindDexFile(dex_cache);
2516 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2517 return dex_file.GetShorty(method_id.proto_idx_);
2518}
2519
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002520void ClassLinker::DumpAllClasses(int flags) const {
2521 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2522 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2523 std::vector<Class*> all_classes;
2524 {
2525 MutexLock mu(lock_);
2526 typedef Table::const_iterator It; // TODO: C++0x auto
2527 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2528 all_classes.push_back(it->second);
2529 }
2530 }
2531
2532 for (size_t i = 0; i < all_classes.size(); ++i) {
2533 all_classes[i]->DumpClass(std::cerr, flags);
2534 }
2535}
2536
Elliott Hughese27955c2011-08-26 15:21:24 -07002537size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002538 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002539 return classes_.size();
2540}
2541
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002542} // namespace art