blob: 3f30b9ef2dd6a80da85e3ace4f7c11313d995a7f [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004
Brian Carlstromdbc05252011-09-09 01:59:59 -07005#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070011#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070012#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070013#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "dex_verifier.h"
15#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070016#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070018#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070019#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070020#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070021#include "runtime.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070022#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070023#include "space.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070024#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070026#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070028
29namespace art {
30
Elliott Hughes4a2b4172011-09-20 17:08:25 -070031namespace {
32
33void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
34void ThrowNoClassDefFoundError(const char* fmt, ...) {
35 va_list args;
36 va_start(args, fmt);
37 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
38 va_end(args);
39}
40
Elliott Hughese555dc02011-09-25 10:46:35 -070041void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
42void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070043 va_list args;
44 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070045 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070046 va_end(args);
47}
48
49void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
50void ThrowLinkageError(const char* fmt, ...) {
51 va_list args;
52 va_start(args, fmt);
53 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
54 va_end(args);
55}
56
Elliott Hughescc5f9a92011-09-28 19:17:29 -070057void ThrowNoSuchMethodError(const char* kind,
58 Class* c, const StringPiece& name, const StringPiece& signature) {
59 DexCache* dex_cache = c->GetDexCache();
60 std::stringstream msg;
61 msg << "no " << kind << " method " << name << "." << signature
62 << " in class " << c->GetDescriptor()->ToModifiedUtf8()
63 << " or its superclasses";
64 if (dex_cache) {
65 msg << " (defined in " << dex_cache->GetLocation()->ToModifiedUtf8() << ")";
66 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070067 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070068}
69
Elliott Hughes4a2b4172011-09-20 17:08:25 -070070void ThrowEarlierClassFailure(Class* c) {
71 /*
72 * The class failed to initialize on a previous attempt, so we want to throw
73 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
74 * failed in verification, in which case v2 5.4.1 says we need to re-throw
75 * the previous error.
76 */
77 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
78
79 if (c->GetVerifyErrorClass() != NULL) {
80 // TODO: change the verifier to store an _instance_, with a useful detail message?
81 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070082 Thread::Current()->ThrowNewException(error_descriptor.c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -070083 PrettyDescriptor(c->GetDescriptor()).c_str());
84 } else {
85 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
86 }
87}
88
Elliott Hughes4d0207c2011-10-03 19:14:34 -070089void WrapExceptionInInitializer() {
90 JNIEnv* env = Thread::Current()->GetJniEnv();
91
92 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
93 CHECK(cause.get() != NULL);
94
95 env->ExceptionClear();
96
97 // TODO: add java.lang.Error to JniConstants?
98 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
99 CHECK(error_class.get() != NULL);
100 if (env->IsInstanceOf(cause.get(), error_class.get())) {
101 // We only wrap non-Error exceptions; an Error can just be used as-is.
102 env->Throw(cause.get());
103 return;
104 }
105
106 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
107 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
108 CHECK(eiie_class.get() != NULL);
109
110 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
111 CHECK(mid != NULL);
112
113 ScopedLocalRef<jthrowable> eiie(env,
114 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
115 env->Throw(eiie.get());
116}
117
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118}
119
Elliott Hughes418d20f2011-09-22 14:00:39 -0700120const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700121 "Ljava/lang/Class;",
122 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700123 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700124 "[Ljava/lang/Object;",
125 "Ljava/lang/String;",
Elliott Hughes80609252011-09-23 17:24:51 -0700126 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700127 "Ljava/lang/reflect/Field;",
128 "Ljava/lang/reflect/Method;",
129 "Ljava/lang/ClassLoader;",
130 "Ldalvik/system/BaseDexClassLoader;",
131 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700132 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700133 "Z",
134 "B",
135 "C",
136 "D",
137 "F",
138 "I",
139 "J",
140 "S",
141 "V",
142 "[Z",
143 "[B",
144 "[C",
145 "[D",
146 "[F",
147 "[I",
148 "[J",
149 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700150 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700151};
152
Elliott Hughes5f791332011-09-15 17:45:30 -0700153class ObjectLock {
154 public:
155 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
156 CHECK(object != NULL);
157 obj_->MonitorEnter(self_);
158 }
159
160 ~ObjectLock() {
161 obj_->MonitorExit(self_);
162 }
163
164 void Wait() {
165 return Monitor::Wait(self_, obj_, 0, 0, false);
166 }
167
168 void Notify() {
169 obj_->Notify();
170 }
171
172 void NotifyAll() {
173 obj_->NotifyAll();
174 }
175
176 private:
177 Thread* self_;
178 Object* obj_;
179 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
180};
181
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700182ClassLinker* ClassLinker::Create(const std::string& boot_class_path,
183 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700184 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700185 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700186 class_linker->Init(boot_class_path);
187 return class_linker.release();
188}
189
190ClassLinker* ClassLinker::Create(InternTable* intern_table) {
191 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
192 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700193 return class_linker.release();
194}
195
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700196ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700197 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700198 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700199 array_interfaces_(NULL),
200 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700201 init_done_(false),
202 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700203 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700204}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700205
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700206void CreateClassPath(const std::string& class_path,
207 std::vector<const DexFile*>& class_path_vector) {
208 std::vector<std::string> parsed;
209 Split(class_path, ':', parsed);
210 for (size_t i = 0; i < parsed.size(); ++i) {
211 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
212 if (dex_file != NULL) {
213 class_path_vector.push_back(dex_file);
214 }
215 }
216}
217
218void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700219 const Runtime* runtime = Runtime::Current();
220 if (runtime->IsVerboseStartup()) {
221 LOG(INFO) << "ClassLinker::InitFrom entering";
222 }
223
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700224 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700225
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700226 // java_lang_Class comes first, its needed for AllocClass
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700227 Class* java_lang_Class = down_cast<Class*>(
228 Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700229 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700230 java_lang_Class->SetClass(java_lang_Class);
231 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700232 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700233
Elliott Hughes418d20f2011-09-22 14:00:39 -0700234 // Class[] is used for reflection support.
235 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
236 class_array_class->SetComponentType(java_lang_Class);
237
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700238 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700239 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700240 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700241 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 java_lang_Class->SetSuperClass(java_lang_Object);
243 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700244
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700245 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700246 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700247 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700248
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700249 // Setup the char class to be used for char[]
250 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
251
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700252 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700253 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700254 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700255 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700256
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700257 // Setup String
258 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
259 String::SetClass(java_lang_String);
260 java_lang_String->SetObjectSize(sizeof(String));
261 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400262
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700264 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
265 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700266 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700267 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
268 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
269 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700270
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 // Create storage for root classes, save away our work so far (requires
272 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700273 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700274 SetClassRoot(kJavaLangClass, java_lang_Class);
275 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700276 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700277 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700278 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700279 SetClassRoot(kJavaLangString, java_lang_String);
280
281 // Setup the primitive type classes.
282 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
283 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
285 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
286 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
287 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
288 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
289 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
290
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700291 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700292 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700293 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294
295 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
296 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700297 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
299 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700300 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700302 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700303
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700304 // setup boot_class_path_ and register class_path now that we can
305 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700306 std::vector<const DexFile*> boot_class_path_vector;
307 CreateClassPath(boot_class_path, boot_class_path_vector);
308 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
309 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700310 CHECK(dex_file != NULL);
311 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700312 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313
Elliott Hughes80609252011-09-23 17:24:51 -0700314 // Constructor, Field, and Method are necessary so that FindClass can link members
315 Class* java_lang_reflect_Constructor = AllocClass(java_lang_Class, sizeof(MethodClass));
316 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
317 CHECK(java_lang_reflect_Constructor != NULL);
318 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
319 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor);
320 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
321
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
323 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700324 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700325 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
326 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
327 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
328 Field::SetClass(java_lang_reflect_Field);
329
330 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Elliott Hughes80609252011-09-23 17:24:51 -0700331 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332 CHECK(java_lang_reflect_Method != NULL);
333 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
334 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
335 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Elliott Hughes80609252011-09-23 17:24:51 -0700336 Method::SetClasses(java_lang_reflect_Constructor, java_lang_reflect_Method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337
338 // now we can use FindSystemClass
339
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700340 // run char class through InitializePrimitiveClass to finish init
341 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
342 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
343
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700344 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345 java_lang_Object->SetStatus(Class::kStatusNotReady);
346 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
347 CHECK_EQ(java_lang_Object, Object_class);
348 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
349 java_lang_String->SetStatus(Class::kStatusNotReady);
350 Class* String_class = FindSystemClass("Ljava/lang/String;");
351 CHECK_EQ(java_lang_String, String_class);
352 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
353
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700354 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
356 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
357
358 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
359 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
360
361 Class* found_char_array_class = FindSystemClass("[C");
362 CHECK_EQ(char_array_class, found_char_array_class);
363
364 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
365 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
366
367 Class* found_int_array_class = FindSystemClass("[I");
368 CHECK_EQ(int_array_class, found_int_array_class);
369
370 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
371 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
372
373 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
374 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
375
376 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
377 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
378
Elliott Hughes418d20f2011-09-22 14:00:39 -0700379 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
380 CHECK_EQ(class_array_class, found_class_array_class);
381
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
383 CHECK_EQ(object_array_class, found_object_array_class);
384
385 // Setup the single, global copies of "interfaces" and "iftable"
386 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
387 CHECK(java_lang_Cloneable != NULL);
388 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
389 CHECK(java_io_Serializable != NULL);
390 CHECK(array_interfaces_ != NULL);
391 array_interfaces_->Set(0, java_lang_Cloneable);
392 array_interfaces_->Set(1, java_io_Serializable);
393 // We assume that Cloneable/Serializable don't have superinterfaces --
394 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700395 // supers as well.
396 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
397 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398
Elliott Hughes418d20f2011-09-22 14:00:39 -0700399 // Sanity check Class[] and Object[]'s interfaces
400 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
401 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700402 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
403 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700404
Elliott Hughes80609252011-09-23 17:24:51 -0700405 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700406 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700407 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700408 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700409
Elliott Hughes80609252011-09-23 17:24:51 -0700410 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
411 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
412 CHECK_EQ(java_lang_reflect_Constructor, Constructor_class);
413
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700415 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700416 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700417
418 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700419 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700420 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700421
422 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
423 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700424 java_lang_ref_FinalizerReference->SetAccessFlags(
425 java_lang_ref_FinalizerReference->GetAccessFlags() |
426 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700427 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428 java_lang_ref_PhantomReference->SetAccessFlags(
429 java_lang_ref_PhantomReference->GetAccessFlags() |
430 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700431 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700432 java_lang_ref_SoftReference->SetAccessFlags(
433 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700434 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435 java_lang_ref_WeakReference->SetAccessFlags(
436 java_lang_ref_WeakReference->GetAccessFlags() |
437 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700438
Brian Carlstromaded5f72011-10-07 17:15:04 -0700439 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700441 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700442 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
443
444 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
445 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
446 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
447
448 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
449 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
450 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
451 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
452
453 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700454 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
455 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700456 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700457
Brian Carlstroma663ea52011-08-19 23:33:41 -0700458 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700459
460 if (runtime->IsVerboseStartup()) {
461 LOG(INFO) << "ClassLinker::InitFrom exiting";
462 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700463}
464
465void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700466 const Runtime* runtime = Runtime::Current();
467 if (runtime->IsVerboseStartup()) {
468 LOG(INFO) << "ClassLinker::FinishInit entering";
469 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700470
471 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700472 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700473 // as the types of the field can't be resolved prior to the runtime being
474 // fully initialized
475 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
Elliott Hughesadb460d2011-10-05 17:02:34 -0700476 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700477 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
478
Elliott Hughesadb460d2011-10-05 17:02:34 -0700479 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
480
Brian Carlstrom16192862011-09-12 17:50:06 -0700481 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
482 CHECK(pendingNext->GetName()->Equals("pendingNext"));
483 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
484
485 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
486 CHECK(queue->GetName()->Equals("queue"));
Elliott Hughesadb460d2011-10-05 17:02:34 -0700487 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue), java_lang_ref_ReferenceQueue);
Brian Carlstrom16192862011-09-12 17:50:06 -0700488
489 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
490 CHECK(queueNext->GetName()->Equals("queueNext"));
491 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
492
493 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
494 CHECK(referent->GetName()->Equals("referent"));
495 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
496
497 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
498 CHECK(zombie->GetName()->Equals("zombie"));
499 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
500
501 Heap::SetReferenceOffsets(referent->GetOffset(),
502 queue->GetOffset(),
503 queueNext->GetOffset(),
504 pendingNext->GetOffset(),
505 zombie->GetOffset());
506
Brian Carlstroma663ea52011-08-19 23:33:41 -0700507 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700508 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700509 ClassRoot class_root = static_cast<ClassRoot>(i);
510 Class* klass = GetClassRoot(class_root);
511 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700512 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700513 // note SetClassRoot does additional validation.
514 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700515 }
516
Elliott Hughes92f14b22011-10-06 12:29:54 -0700517 CHECK(array_iftable_ != NULL);
518 CHECK(array_interfaces_ != NULL);
519
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700520 // disable the slow paths in FindClass and CreatePrimitiveClass now
521 // that Object, Class, and Object[] are setup
522 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700523
524 if (runtime->IsVerboseStartup()) {
525 LOG(INFO) << "ClassLinker::FinishInit exiting";
526 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700527}
528
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700529void ClassLinker::RunRootClinits() {
530 Thread* self = Thread::Current();
531 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
532 Class* c = GetClassRoot(ClassRoot(i));
533 if (!c->IsArrayClass() && !c->IsPrimitive()) {
534 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700535 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700536 }
537 }
538}
539
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700540OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700541 MutexLock mu(lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700542 const Runtime* runtime = Runtime::Current();
543 if (runtime->IsVerboseStartup()) {
544 LOG(INFO) << "ClassLinker::OpenOat entering";
545 }
546 const ImageHeader& image_header = space->GetImageHeader();
547 String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
548 std::string oat_filename;
549 oat_filename += runtime->GetHostPrefix();
550 oat_filename += oat_location->ToModifiedUtf8();
551 OatFile* oat_file = OatFile::Open(std::string(oat_filename), "", image_header.GetOatBaseAddr());
552 if (oat_file == NULL) {
553 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image";
554 return NULL;
555 }
556 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
557 uint32_t image_oat_checksum = image_header.GetOatChecksum();
558 if (oat_checksum != image_oat_checksum) {
559 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
560 << " to expected oat checksum " << std::hex << oat_checksum
561 << " in image";
562 return NULL;
563 }
564 oat_files_.push_back(oat_file);
565 if (runtime->IsVerboseStartup()) {
566 LOG(INFO) << "ClassLinker::OpenOat exiting";
567 }
568 return oat_file;
569}
570
Brian Carlstromaded5f72011-10-07 17:15:04 -0700571const OatFile* ClassLinker::FindOatFile(const DexFile& dex_file) {
572 MutexLock mu(lock_);
573 std::string dex_file_location = dex_file.GetLocation();
574 std::string location(dex_file_location);
575 CHECK(StringPiece(location).ends_with(".dex")
576 || StringPiece(location).ends_with(".zip")
577 || StringPiece(location).ends_with(".jar")
578 || StringPiece(location).ends_with(".apk"));
579 location.erase(location.size()-3);
580 location += "oat";
581 // TODO: check if dex_file matches an OatDexFile location and checksum
582 return FindOatFile(location);
583}
584
585const OatFile* ClassLinker::FindOatFile(const std::string& location) {
586 for (size_t i = 0; i < oat_files_.size(); i++) {
587 const OatFile* oat_file = oat_files_[i];
588 DCHECK(oat_file != NULL);
589 if (oat_file->GetLocation() == location) {
590 return oat_file;
591 }
592 }
593
594 const OatFile* oat_file = OatFile::Open(location, "", NULL);
595 if (oat_file == NULL) {
596 LOG(ERROR) << "Failed to open oat file " << location;
597 return NULL;
598 }
599 return oat_file;
600}
601
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700602void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700603 const Runtime* runtime = Runtime::Current();
604 if (runtime->IsVerboseStartup()) {
605 LOG(INFO) << "ClassLinker::InitFromImage entering";
606 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700607 CHECK(!init_done_);
608
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700609 const std::vector<Space*>& spaces = Heap::GetSpaces();
610 for (size_t i = 0; i < spaces.size(); i++) {
611 Space* space = spaces[i] ;
612 if (space->IsImageSpace()) {
613 OatFile* oat_file = OpenOat(space);
614 CHECK(oat_file != NULL) << "Failed to open oat file for image";
615 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
616 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
617
618 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
619 static_cast<uint32_t>(dex_caches->GetLength()));
620 for (int i = 0; i < dex_caches->GetLength(); i++) {
621 DexCache* dex_cache = dex_caches->Get(i);
622 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
623
624 std::string dex_filename;
625 dex_filename += runtime->GetHostPrefix();
626 dex_filename += dex_file_location;
627 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
628 if (dex_file == NULL) {
629 LOG(FATAL) << "Failed to open dex file " << dex_filename
630 << " referenced from oat file as " << dex_file_location;
631 }
632
Brian Carlstromaded5f72011-10-07 17:15:04 -0700633 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
634 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700635
636 RegisterDexFile(*dex_file, dex_cache);
637 }
638 }
639 }
640
Brian Carlstroma663ea52011-08-19 23:33:41 -0700641 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
642 DCHECK(heap_bitmap != NULL);
643
Brian Carlstroma663ea52011-08-19 23:33:41 -0700644 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700645 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700646
647 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700648 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
649 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700650
Elliott Hughes92f14b22011-10-06 12:29:54 -0700651 // reinit array_interfaces_ and array_iftable_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700652 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
653 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700654 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
655 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700656
Brian Carlstroma663ea52011-08-19 23:33:41 -0700657 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700658 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700659 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700660 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
661 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
662 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
663 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
664 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
665 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
666 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
667 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700668 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700669 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700670
671 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700672
673 if (runtime->IsVerboseStartup()) {
674 LOG(INFO) << "ClassLinker::InitFromImage exiting";
675 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700676}
677
Brian Carlstrom78128a62011-09-15 17:21:19 -0700678void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700679 DCHECK(obj != NULL);
680 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700681 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700682
Brian Carlstromc74255f2011-09-11 22:47:39 -0700683 if (obj->IsString()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700684 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700685 return;
686 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700687 if (obj->IsClass()) {
688 // restore class to ClassLinker::classes_ table
689 Class* klass = obj->AsClass();
690 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
691 class_linker->InsertClass(descriptor, klass);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700692 return;
693 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700694}
695
696// Keep in sync with InitCallback. Anything we visit, we need to
697// reinit references to when reinitializing a ClassLinker from a
698// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700699void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
700 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700701
702 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700703 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700704 }
705
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700706 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700707 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700708 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700709 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700710 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700711 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700712 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700713
Elliott Hughes410c0c82011-09-01 17:58:25 -0700714 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700715}
716
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700717ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700718 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700719 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700720 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700721 BooleanArray::ResetArrayClass();
722 ByteArray::ResetArrayClass();
723 CharArray::ResetArrayClass();
724 DoubleArray::ResetArrayClass();
725 FloatArray::ResetArrayClass();
726 IntArray::ResetArrayClass();
727 LongArray::ResetArrayClass();
728 ShortArray::ResetArrayClass();
729 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700730 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700731 STLDeleteElements(&boot_class_path_);
732 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700733}
734
735DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom83db7722011-08-26 17:32:56 -0700736 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700737 dex_cache->Init(intern_table_->InternStrong(dex_file.GetLocation().c_str()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700738 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700739 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700740 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700741 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700742 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
743 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700744 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700745}
746
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700747CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
748 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700749}
750
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700751InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
752 DCHECK(interface->IsInterface());
753 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
754 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
755 interface_entry->SetInterface(interface);
756 return interface_entry;
757}
758
Brian Carlstrom4873d462011-08-21 15:23:39 -0700759Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
760 DCHECK_GE(class_size, sizeof(Class));
761 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700762 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
763 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700764 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700765}
766
Brian Carlstrom4873d462011-08-21 15:23:39 -0700767Class* ClassLinker::AllocClass(size_t class_size) {
768 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700769}
770
Jesse Wilson35baaab2011-08-10 16:18:03 -0400771Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700772 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700773}
774
775Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700776 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700777}
778
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700779ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
780 return ObjectArray<StackTraceElement>::Alloc(
781 GetClassRoot(kJavaLangStackTraceElementArrayClass),
782 length);
783}
784
Brian Carlstromaded5f72011-10-07 17:15:04 -0700785Class* EnsureResolved(Class* klass) {
786 DCHECK(klass != NULL);
787 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700788 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700789 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700790 ObjectLock lock(klass);
791 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700792 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700793 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700794 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700795 return NULL;
796 }
797 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700798 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700799 lock.Wait();
800 }
801 }
802 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700803 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700804 return NULL;
805 }
806 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700807 CHECK(klass->IsResolved()) << PrettyClass(klass);
808 CHECK(!self->IsExceptionPending())
809 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
810 return klass;
811}
812
813Class* ClassLinker::FindClass(const std::string& descriptor,
814 const ClassLoader* class_loader) {
815 CHECK_NE(descriptor.size(), 0U);
816 Thread* self = Thread::Current();
817 DCHECK(self != NULL);
818 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
819 // Find the class in the loaded classes table.
820 Class* klass = LookupClass(descriptor, class_loader);
821 if (klass != NULL) {
822 return EnsureResolved(klass);
823 }
824 if (descriptor.size() == 1) {
825 // only the descriptors of primitive types should be 1 character long
826 return FindPrimitiveClass(descriptor[0]);
827 }
828 // Class is not yet loaded.
829 if (descriptor[0] == '[') {
830 return CreateArrayClass(descriptor, class_loader);
831 }
832 if (class_loader == NULL) {
833 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
834 if (pair.second == NULL) {
835 std::string name(PrintableString(descriptor));
836 ThrowNoClassDefFoundError("Class %s not found in boot class loader", name.c_str());
837 return NULL;
838 }
839 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
840 }
841
842 if (ClassLoader::UseCompileTimeClassPath()) {
843 const std::vector<const DexFile*>& class_path
844 = ClassLoader::GetCompileTimeClassPath(class_loader);
845 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
846 if (pair.second == NULL) {
847 return FindSystemClass(descriptor);
848 }
849 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
850 }
851
852 std::string class_name_string = DescriptorToDot(descriptor);
853 ScopedThreadStateChange(self, Thread::kNative);
854 JNIEnv* env = self->GetJniEnv();
855 jclass c = AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader));
856 CHECK(c != NULL);
857 // TODO: cache method?
858 jmethodID mid = env->GetMethodID(c, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
859 CHECK(mid != NULL);
860 jobject class_name_object = env->NewStringUTF(class_name_string.c_str());
861 if (class_name_string == NULL) {
862 return NULL;
863 }
864 jobject class_loader_object = AddLocalReference<jobject>(env, class_loader);
865 jobject result = env->CallObjectMethod(class_loader_object, mid, class_name_object);
866 Class* klass_result = Decode<Class*>(env, result);
867 env->DeleteLocalRef(result);
868 env->DeleteLocalRef(class_name_object);
869 env->DeleteLocalRef(c);
870 return klass_result;
871}
872
873Class* ClassLinker::DefineClass(const std::string& descriptor,
874 const ClassLoader* class_loader,
875 const DexFile& dex_file,
876 const DexFile::ClassDef& dex_class_def) {
877 Class* klass;
878 // Load the class from the dex file.
879 if (!init_done_) {
880 // finish up init of hand crafted class_roots_
881 if (descriptor == "Ljava/lang/Object;") {
882 klass = GetClassRoot(kJavaLangObject);
883 } else if (descriptor == "Ljava/lang/Class;") {
884 klass = GetClassRoot(kJavaLangClass);
885 } else if (descriptor == "Ljava/lang/String;") {
886 klass = GetClassRoot(kJavaLangString);
887 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
888 klass = GetClassRoot(kJavaLangReflectConstructor);
889 } else if (descriptor == "Ljava/lang/reflect/Field;") {
890 klass = GetClassRoot(kJavaLangReflectField);
891 } else if (descriptor == "Ljava/lang/reflect/Method;") {
892 klass = GetClassRoot(kJavaLangReflectMethod);
893 } else {
894 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
895 }
896 } else {
897 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
898 }
899 klass->SetDexCache(FindDexCache(dex_file));
900 LoadClass(dex_file, dex_class_def, klass, class_loader);
901 // Check for a pending exception during load
902 Thread* self = Thread::Current();
903 if (self->IsExceptionPending()) {
904 return NULL;
905 }
906 ObjectLock lock(klass);
907 klass->SetClinitThreadId(self->GetTid());
908 // Add the newly loaded class to the loaded classes table.
909 bool success = InsertClass(descriptor, klass); // TODO: just return collision
910 if (!success) {
911 // We may fail to insert if we raced with another thread.
912 klass->SetClinitThreadId(0);
913 klass = LookupClass(descriptor, class_loader);
914 CHECK(klass != NULL);
915 return klass;
916 }
917 // Finish loading (if necessary) by finding parents
918 CHECK(!klass->IsLoaded());
919 if (!LoadSuperAndInterfaces(klass, dex_file)) {
920 // Loading failed.
921 CHECK(self->IsExceptionPending());
922 lock.NotifyAll();
923 return NULL;
924 }
925 CHECK(klass->IsLoaded());
926 // Link the class (if necessary)
927 CHECK(!klass->IsResolved());
928 if (!LinkClass(klass)) {
929 // Linking failed.
930 CHECK(self->IsExceptionPending());
931 lock.NotifyAll();
932 return NULL;
933 }
934 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700935 return klass;
936}
937
Brian Carlstrom4873d462011-08-21 15:23:39 -0700938// Precomputes size that will be needed for Class, matching LinkStaticFields
939size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
940 const DexFile::ClassDef& dex_class_def) {
941 const byte* class_data = dex_file.GetClassData(dex_class_def);
942 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
943 size_t num_static_fields = header.static_fields_size_;
944 size_t num_ref = 0;
945 size_t num_32 = 0;
946 size_t num_64 = 0;
947 if (num_static_fields != 0) {
948 uint32_t last_idx = 0;
949 for (size_t i = 0; i < num_static_fields; ++i) {
950 DexFile::Field dex_field;
951 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
952 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
953 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
954 char c = descriptor[0];
955 if (c == 'L' || c == '[') {
956 num_ref++;
957 } else if (c == 'J' || c == 'D') {
958 num_64++;
959 } else {
960 num_32++;
961 }
962 }
963 }
964
965 // start with generic class data
966 size_t size = sizeof(Class);
967 // follow with reference fields which must be contiguous at start
968 size += (num_ref * sizeof(uint32_t));
969 // if there are 64-bit fields to add, make sure they are aligned
970 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
971 if (num_32 != 0) {
972 // use an available 32-bit field for padding
973 num_32--;
974 }
975 size += sizeof(uint32_t); // either way, we are adding a word
976 DCHECK_EQ(size, RoundUp(size, 8));
977 }
978 // tack on any 64-bit fields now that alignment is assured
979 size += (num_64 * sizeof(uint64_t));
980 // tack on any remaining 32-bit fields
981 size += (num_32 * sizeof(uint32_t));
982 return size;
983}
984
Brian Carlstromf615a612011-07-23 12:50:34 -0700985void ClassLinker::LoadClass(const DexFile& dex_file,
986 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700987 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700988 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -0700989 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700990 CHECK(klass->GetDexCache() != NULL);
991 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -0700992 const byte* class_data = dex_file.GetClassData(dex_class_def);
993 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700994
Brian Carlstromf615a612011-07-23 12:50:34 -0700995 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -0700996 CHECK(descriptor != NULL);
997
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700998 klass->SetClass(GetClassRoot(kJavaLangClass));
999 if (klass->GetDescriptor() != NULL) {
1000 DCHECK(klass->GetDescriptor()->Equals(descriptor));
1001 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001002 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001003 }
1004 uint32_t access_flags = dex_class_def.access_flags_;
Brian Carlstrom34f426c2011-10-04 12:58:02 -07001005 // Make sure there aren't any "bonus" flags set, since we use them for runtime state.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001006 CHECK_EQ(access_flags & ~kAccClassFlagsMask, 0U);
1007 klass->SetAccessFlags(access_flags);
1008 klass->SetClassLoader(class_loader);
1009 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
1010 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001011
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001012 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001013
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001014 size_t num_static_fields = header.static_fields_size_;
1015 size_t num_instance_fields = header.instance_fields_size_;
1016 size_t num_direct_methods = header.direct_methods_size_;
1017 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001018
Jesse Wilson6384f642011-10-07 18:08:35 -04001019 const char* source_file = dex_file.dexGetSourceFile(dex_class_def);
1020 if (source_file != NULL) {
1021 klass->SetSourceFile(intern_table_->InternStrong(source_file));
1022 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001023
1024 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -07001025 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001026
1027 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001028 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001029 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001030 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001031 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001032 DexFile::Field dex_field;
1033 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001034 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001035 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001036 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001037 }
1038 }
1039
1040 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001041 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001042 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001043 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001044 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001045 DexFile::Field dex_field;
1046 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001047 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001048 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001049 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001050 }
1051 }
1052
Brian Carlstromaded5f72011-10-07 17:15:04 -07001053 UniquePtr<const OatFile::OatClass> oat_class;
1054 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
1055 const OatFile* oat_file = FindOatFile(dex_file);
1056 if (oat_file != NULL) {
1057 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1058 if (oat_dex_file != NULL) {
1059 uint32_t class_def_index;
1060 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1061 CHECK(found) << descriptor;
1062 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
1063 }
1064 }
1065 }
1066 size_t method_index = 0;
1067
Brian Carlstrom934486c2011-07-12 23:42:50 -07001068 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001069 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001070 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001071 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001072 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001073 for (size_t i = 0; i < num_direct_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001074 DexFile::Method dex_method;
1075 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -07001076 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001077 klass->SetDirectMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001078 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001079 if (oat_class.get() != NULL) {
1080 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
1081 oat_method.LinkMethod(meth);
1082 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001083 }
1084 }
1085
1086 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001087 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001088 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001089 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001090 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001091 for (size_t i = 0; i < num_virtual_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001092 DexFile::Method dex_method;
1093 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstroma0808032011-07-18 00:39:23 -07001094 Method* meth = AllocMethod();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001095 klass->SetVirtualMethod(i, meth);
Brian Carlstrom1f870082011-08-23 16:02:11 -07001096 LoadMethod(dex_file, dex_method, klass, meth);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001097 if (oat_class.get() != NULL) {
1098 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
1099 oat_method.LinkMethod(meth);
1100 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001101 }
1102 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001103}
1104
Brian Carlstromf615a612011-07-23 12:50:34 -07001105void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1106 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001107 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001108 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001109 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001110 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001111 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1112 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001113 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001114 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001115 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001116 }
1117 }
1118}
1119
Brian Carlstromf615a612011-07-23 12:50:34 -07001120void ClassLinker::LoadField(const DexFile& dex_file,
1121 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001122 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001123 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001124 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001125 dst->SetDeclaringClass(klass);
1126 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1127 dst->SetTypeIdx(field_id.type_idx_);
1128 dst->SetAccessFlags(src.access_flags_);
1129
1130 // In order to access primitive types using GetTypeDuringLinking we need to
1131 // ensure they are resolved into the dex cache
1132 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1133 if (descriptor[1] == '\0') {
1134 // only the descriptors of primitive types should be 1 character long
1135 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
1136 DCHECK(resolved->IsPrimitive());
1137 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001138}
1139
Brian Carlstromf615a612011-07-23 12:50:34 -07001140void ClassLinker::LoadMethod(const DexFile& dex_file,
1141 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001142 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001143 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001144 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001145 dst->SetDeclaringClass(klass);
Elliott Hughes20cde902011-10-04 17:37:27 -07001146
Elliott Hughes80609252011-09-23 17:24:51 -07001147 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
1148 dst->SetName(method_name);
1149 if (method_name->Equals("<init>")) {
1150 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1151 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001152
1153 int32_t utf16_length;
1154 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
1155 dst->SetSignature(intern_table_->InternStrong(utf16_length, signature.c_str()));
1156
1157 if (method_name->Equals("finalize") && signature == "()V") {
1158 /*
1159 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1160 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1161 * exclude it here.
1162 *
1163 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1164 */
1165 if (klass->GetClassLoader() != NULL ||
1166 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1167 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1168 klass->SetFinalizable();
1169 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001170 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001171
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001172 dst->SetProtoIdx(method_id.proto_idx_);
1173 dst->SetCodeItemOffset(src.code_off_);
1174 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Brian Carlstromc74255f2011-09-11 22:47:39 -07001175 dst->SetShorty(intern_table_->InternStrong(shorty));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001176 dst->SetAccessFlags(src.access_flags_);
1177 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001178
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001179 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1180 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1181 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1182 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1183 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1184 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001185
Brian Carlstrom934486c2011-07-12 23:42:50 -07001186 // TODO: check for finalize method
1187
Brian Carlstromf615a612011-07-23 12:50:34 -07001188 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001189 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001190 dst->SetNumRegisters(code_item->registers_size_);
1191 dst->SetNumIns(code_item->ins_size_);
1192 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001193 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001194 uint16_t num_args = Method::NumArgRegisters(shorty);
1195 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001196 ++num_args;
1197 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001198 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001199 // TODO: native methods
1200 }
1201}
1202
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001203void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001204 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1205}
1206
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001207void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001208 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001209 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001210 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001211}
1212
Brian Carlstromaded5f72011-10-07 17:15:04 -07001213bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
1214 lock_.AssertHeld();
1215 for (size_t i = 0; i != dex_files_.size(); ++i) {
1216 if (dex_files_[i] == &dex_file) {
1217 return true;
1218 }
1219 }
1220 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001221}
1222
Brian Carlstromaded5f72011-10-07 17:15:04 -07001223bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001224 MutexLock mu(lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001225 return IsDexFileRegistered(dex_file);
1226}
1227
1228void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, DexCache* dex_cache) {
1229 lock_.AssertHeld();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001230 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1231 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001232 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001233 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001234}
1235
Brian Carlstromaded5f72011-10-07 17:15:04 -07001236void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
1237 MutexLock mu(lock_);
1238 if (IsDexFileRegisteredLocked(dex_file)) {
1239 return;
1240 }
1241 RegisterDexFileLocked(dex_file, AllocDexCache(dex_file));
1242}
1243
1244void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
1245 MutexLock mu(lock_);
1246 RegisterDexFileLocked(dex_file, dex_cache);
1247}
1248
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001249const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001250 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001251 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1252 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001253 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001254 }
1255 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001256 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001257 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001258}
1259
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001260DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001261 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001262 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001263 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001264 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001265 }
1266 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001267 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001268 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001269}
1270
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001271Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1272 const char* descriptor,
1273 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001274 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001275 CHECK(primitive_class != NULL);
1276 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1277 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
1278 primitive_class->SetPrimitiveType(type);
1279 primitive_class->SetStatus(Class::kStatusInitialized);
1280 bool success = InsertClass(descriptor, primitive_class);
1281 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1282 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001283}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001284
Brian Carlstrombe977852011-07-19 14:54:54 -07001285// Create an array class (i.e. the class object for the array, not the
1286// array itself). "descriptor" looks like "[C" or "[[[[B" or
1287// "[Ljava/lang/String;".
1288//
1289// If "descriptor" refers to an array of primitives, look up the
1290// primitive type's internally-generated class object.
1291//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001292// "class_loader" is the class loader of the class that's referring to
1293// us. It's used to ensure that we're looking for the element type in
1294// the right context. It does NOT become the class loader for the
1295// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001296//
1297// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001298Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001299 const ClassLoader* class_loader) {
1300 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001301
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001302 // Identify the underlying component type
1303 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001304 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001305 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001306 return NULL;
1307 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001308
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001309 // See if the component type is already loaded. Array classes are
1310 // always associated with the class loader of their underlying
1311 // element type -- an array of Strings goes with the loader for
1312 // java/lang/String -- so we need to look for it there. (The
1313 // caller should have checked for the existence of the class
1314 // before calling here, but they did so with *their* class loader,
1315 // not the component type's loader.)
1316 //
1317 // If we find it, the caller adds "loader" to the class' initiating
1318 // loader list, which should prevent us from going through this again.
1319 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001320 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001321 // are the same, because our caller (FindClass) just did the
1322 // lookup. (Even if we get this wrong we still have correct behavior,
1323 // because we effectively do this lookup again when we add the new
1324 // class to the hash table --- necessary because of possible races with
1325 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001326 if (class_loader != component_type->GetClassLoader()) {
1327 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001328 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001329 return new_class;
1330 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001331 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001332
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001333 // Fill out the fields in the Class.
1334 //
1335 // It is possible to execute some methods against arrays, because
1336 // all arrays are subclasses of java_lang_Object_, so we need to set
1337 // up a vtable. We can just point at the one in java_lang_Object_.
1338 //
1339 // Array classes are simple enough that we don't need to do a full
1340 // link step.
1341
1342 Class* new_class = NULL;
1343 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001344 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001345 if (descriptor == "[Ljava/lang/Class;") {
1346 new_class = GetClassRoot(kClassArrayClass);
1347 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001348 new_class = GetClassRoot(kObjectArrayClass);
1349 } else if (descriptor == "[C") {
1350 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001351 } else if (descriptor == "[I") {
1352 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001353 }
1354 }
1355 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001356 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001357 if (new_class == NULL) {
1358 return NULL;
1359 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001360 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001361 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001362 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001363 if (new_class->GetDescriptor() != NULL) {
1364 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1365 } else {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001366 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.c_str()));
Brian Carlstrom693267a2011-09-06 09:25:34 -07001367 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001368 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001369 new_class->SetSuperClass(java_lang_Object);
1370 new_class->SetVTable(java_lang_Object->GetVTable());
1371 new_class->SetPrimitiveType(Class::kPrimNot);
1372 new_class->SetClassLoader(component_type->GetClassLoader());
1373 new_class->SetStatus(Class::kStatusInitialized);
1374 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001375 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001376
1377
1378 // All arrays have java/lang/Cloneable and java/io/Serializable as
1379 // interfaces. We need to set that up here, so that stuff like
1380 // "instanceof" works right.
1381 //
1382 // Note: The GC could run during the call to FindSystemClass,
1383 // so we need to make sure the class object is GC-valid while we're in
1384 // there. Do this by clearing the interface list so the GC will just
1385 // think that the entries are null.
1386
1387
1388 // Use the single, global copies of "interfaces" and "iftable"
1389 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001390 CHECK(array_interfaces_ != NULL);
1391 CHECK(array_iftable_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001392 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001393 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001394
1395 // Inherit access flags from the component type. Arrays can't be
1396 // used as a superclass or interface, so we want to add "final"
1397 // and remove "interface".
1398 //
1399 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001400 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001401 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001402 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1403 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001404
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001405 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001406 return new_class;
1407 }
1408 // Another thread must have loaded the class after we
1409 // started but before we finished. Abandon what we've
1410 // done.
1411 //
1412 // (Yes, this happens.)
1413
1414 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001415 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001416 DCHECK(other_class != NULL);
1417 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001418}
1419
1420Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001421 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001422 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001423 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001424 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001425 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001426 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001427 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001428 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001429 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001430 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001431 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001432 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001433 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001434 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001435 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001436 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001437 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001438 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001439 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001440 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001441 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001442 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001443 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001444}
1445
Brian Carlstromaded5f72011-10-07 17:15:04 -07001446bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001447 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001448 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001449 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001450 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001451}
1452
Brian Carlstromaded5f72011-10-07 17:15:04 -07001453Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001454 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001455 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001456 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001457 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001458 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001459 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001460 return klass;
1461 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001462 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001463 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001464}
1465
jeffhao98eacac2011-09-14 16:11:53 -07001466void ClassLinker::VerifyClass(Class* klass) {
1467 if (klass->IsVerified()) {
1468 return;
1469 }
1470
1471 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001472 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001473
jeffhao5cfd6fb2011-09-27 13:54:29 -07001474 if (DexVerifier::VerifyClass(klass)) {
1475 klass->SetStatus(Class::kStatusVerified);
1476 } else {
1477 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001478 Thread* self = Thread::Current();
1479 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1480 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
1481 PrettyDescriptor(klass->GetDescriptor()).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001482 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001483 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001484 }
jeffhao98eacac2011-09-14 16:11:53 -07001485}
1486
Brian Carlstrom25c33252011-09-18 15:58:35 -07001487bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001488 CHECK(klass->IsResolved() || klass->IsErroneous())
1489 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001490
Carl Shapirob5573532011-07-12 18:22:59 -07001491 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001492
Brian Carlstrom25c33252011-09-18 15:58:35 -07001493 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001494 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001495 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001496 ObjectLock lock(klass);
1497
Brian Carlstromd1422f82011-09-28 11:37:09 -07001498 if (klass->GetStatus() == Class::kStatusInitialized) {
1499 return true;
1500 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001501
Brian Carlstromd1422f82011-09-28 11:37:09 -07001502 if (klass->IsErroneous()) {
1503 ThrowEarlierClassFailure(klass);
1504 return false;
1505 }
1506
1507 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001508 VerifyClass(klass);
1509 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001510 return false;
1511 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001512 }
1513
Brian Carlstrom25c33252011-09-18 15:58:35 -07001514 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1515 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001516 // if the class has a <clinit> but we can't run it during compilation,
1517 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001518 return false;
1519 }
1520
Brian Carlstromd1422f82011-09-28 11:37:09 -07001521 // If the class is kStatusInitializing, either this thread is
1522 // initializing higher up the stack or another thread has beat us
1523 // to initializing and we need to wait. Either way, this
1524 // invocation of InitializeClass will not be responsible for
1525 // running <clinit> and will return.
1526 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001527 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001528 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001529 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001530 return true;
1531 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001532 // No. That's fine. Wait for another thread to finish initializing.
1533 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001534 }
1535
1536 if (!ValidateSuperClassDescriptors(klass)) {
1537 klass->SetStatus(Class::kStatusError);
1538 return false;
1539 }
1540
Brian Carlstromd1422f82011-09-28 11:37:09 -07001541 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001542
Elliott Hughesdcc24742011-09-07 14:02:44 -07001543 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001544 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001545 }
1546
Brian Carlstrom25c33252011-09-18 15:58:35 -07001547 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001548 return false;
1549 }
1550
1551 InitializeStaticFields(klass);
1552
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001553 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001554 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001555 }
1556
1557 {
1558 ObjectLock lock(klass);
1559
1560 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001561 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001562 klass->SetStatus(Class::kStatusError);
1563 } else {
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07001564 ++Runtime::Current()->GetStats()->class_init_count;
1565 ++self->GetStats()->class_init_count;
1566 // TODO: class_init_time_ns
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001567 klass->SetStatus(Class::kStatusInitialized);
1568 }
1569 lock.NotifyAll();
1570 }
1571
1572 return true;
1573}
1574
Brian Carlstromd1422f82011-09-28 11:37:09 -07001575bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1576 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001577 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001578 lock.Wait();
1579
1580 // When we wake up, repeat the test for init-in-progress. If
1581 // there's an exception pending (only possible if
1582 // "interruptShouldThrow" was set), bail out.
1583 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001584 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001585 klass->SetStatus(Class::kStatusError);
1586 return false;
1587 }
1588 // Spurious wakeup? Go back to waiting.
1589 if (klass->GetStatus() == Class::kStatusInitializing) {
1590 continue;
1591 }
1592 if (klass->IsErroneous()) {
1593 // The caller wants an exception, but it was thrown in a
1594 // different thread. Synthesize one here.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001595 self->ThrowNewExceptionF("Ljava/lang/NoClassDefFoundError;",
Brian Carlstromd1422f82011-09-28 11:37:09 -07001596 "<clinit> failed for class %s; see exception in other thread",
1597 PrettyDescriptor(klass->GetDescriptor()).c_str());
1598 return false;
1599 }
1600 if (klass->IsInitialized()) {
1601 return true;
1602 }
1603 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1604 }
1605 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1606}
1607
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001608bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1609 if (klass->IsInterface()) {
1610 return true;
1611 }
1612 // begin with the methods local to the superclass
1613 if (klass->HasSuperClass() &&
1614 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1615 const Class* super = klass->GetSuperClass();
1616 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001617 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001618 if (method != super->GetVirtualMethod(i) &&
1619 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001620 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1621
1622 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 -07001623 return false;
1624 }
1625 }
1626 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001627 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1628 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1629 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001630 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1631 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001632 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001633 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001634 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001635 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1636
1637 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 -07001638 return false;
1639 }
1640 }
1641 }
1642 }
1643 return true;
1644}
1645
1646bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001647 const Class* klass1,
1648 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001649 if (method->IsMiranda()) {
1650 return true;
1651 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001652 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001653 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001654 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001655 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001656 const char* descriptor = it->GetDescriptor();
1657 if (descriptor == NULL) {
1658 break;
1659 }
1660 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1661 // Found a non-primitive type.
1662 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1663 return false;
1664 }
1665 }
1666 }
1667 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001668 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001669 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001670 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001671 return false;
1672 }
1673 }
1674 return true;
1675}
1676
1677// Returns true if classes referenced by the descriptor are the
1678// same classes in klass1 as they are in klass2.
1679bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001680 const Class* klass1,
1681 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001682 CHECK(descriptor != NULL);
1683 CHECK(klass1 != NULL);
1684 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001685 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001686 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001687 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001688 // TODO: found2 == NULL
1689 // TODO: lookup found1 in initiating loader list
1690 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001691 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001692 if (found1 == found2) {
1693 return true;
1694 } else {
1695 return false;
1696 }
1697 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001698 return true;
1699}
1700
Brian Carlstrom25c33252011-09-18 15:58:35 -07001701bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001702 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001703 if (!klass->IsInterface() && klass->HasSuperClass()) {
1704 Class* super_class = klass->GetSuperClass();
1705 if (super_class->GetStatus() != Class::kStatusInitialized) {
1706 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001707 Thread* self = Thread::Current();
1708 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001709 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001710 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001711 // TODO: check for a pending exception
1712 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001713 if (!can_run_clinit) {
1714 // Don't set status to error when we can't run <clinit>.
1715 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1716 klass->SetStatus(Class::kStatusVerified);
1717 return false;
1718 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001719 klass->SetStatus(Class::kStatusError);
1720 klass->NotifyAll();
1721 return false;
1722 }
1723 }
1724 }
1725 return true;
1726}
1727
Brian Carlstrom25c33252011-09-18 15:58:35 -07001728bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001729 CHECK(c != NULL);
1730 if (c->IsInitialized()) {
1731 return true;
1732 }
1733
Elliott Hughes5f791332011-09-15 17:45:30 -07001734 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001735 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001736 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001737 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001738}
1739
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001740void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1741 Class* c, std::map<int, Field*>& field_map) {
1742 const ClassLoader* cl = c->GetClassLoader();
1743 const byte* class_data = dex_file.GetClassData(dex_class_def);
1744 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1745 uint32_t last_idx = 0;
1746 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1747 DexFile::Field dex_field;
1748 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1749 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1750 }
1751}
1752
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001753void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001754 size_t num_static_fields = klass->NumStaticFields();
1755 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001756 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001757 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001758 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001759 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001760 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001761 return;
1762 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001763 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001764 const DexFile& dex_file = FindDexFile(dex_cache);
1765 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001766 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001767
1768 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1769 std::map<int, Field*> field_map;
1770 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1771
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001772 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001773 if (addr == NULL) {
1774 // All this class' static fields have default values.
1775 return;
1776 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001777 size_t array_size = DecodeUnsignedLeb128(&addr);
1778 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001779 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001780 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001781 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001782 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001783 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001784 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001785 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001786 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001787 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001788 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001789 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001790 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001791 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001792 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001793 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001794 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001795 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001796 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001797 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001798 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001799 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001800 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001801 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001802 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001803 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001804 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001805 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001806 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001807 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001808 break;
1809 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001810 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001811 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001812 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001813 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001814 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001815 break;
1816 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001817 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001818 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001819 }
1820}
1821
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001822bool ClassLinker::LinkClass(Class* klass) {
1823 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001824 if (!LinkSuperClass(klass)) {
1825 return false;
1826 }
1827 if (!LinkMethods(klass)) {
1828 return false;
1829 }
1830 if (!LinkInstanceFields(klass)) {
1831 return false;
1832 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001833 if (!LinkStaticFields(klass)) {
1834 return false;
1835 }
1836 CreateReferenceInstanceOffsets(klass);
1837 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001838 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1839 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001840 return true;
1841}
1842
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001843bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001844 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1845 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1846 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001847 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001848 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001849 return false;
1850 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001851 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001852 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001853 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
1854 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07001855 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001856 klass->SetInterface(i, interface);
1857 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001858 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001859 return false;
1860 }
1861 // Verify
1862 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001863 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001864 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001865 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001866 PrettyDescriptor(interface->GetDescriptor()).c_str(),
1867 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001868 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001869 }
1870 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001871 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001872 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001873 return true;
1874}
1875
1876bool ClassLinker::LinkSuperClass(Class* klass) {
1877 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001878 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001879 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001880 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001881 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001882 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001883 return false;
1884 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001885 return true;
1886 }
1887 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001888 ThrowLinkageError("No superclass defined for class %s",
1889 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001890 return false;
1891 }
1892 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001893 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001894 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001895 "Superclass %s of %s is %s",
1896 PrettyDescriptor(super->GetDescriptor()).c_str(),
1897 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001898 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001899 return false;
1900 }
1901 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001902 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07001903 "Superclass %s is inaccessible by %s",
1904 PrettyDescriptor(super->GetDescriptor()).c_str(),
1905 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001906 return false;
1907 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001908
1909 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
1910 if (super->IsFinalizable()) {
1911 klass->SetFinalizable();
1912 }
1913
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001914#ifndef NDEBUG
1915 // Ensure super classes are fully resolved prior to resolving fields..
1916 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001917 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001918 super = super->GetSuperClass();
1919 }
1920#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001921 return true;
1922}
1923
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001924// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001925bool ClassLinker::LinkMethods(Class* klass) {
1926 if (klass->IsInterface()) {
1927 // No vtable.
1928 size_t count = klass->NumVirtualMethods();
1929 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001930 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001931 return false;
1932 }
Carl Shapiro565f5072011-07-10 13:39:43 -07001933 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001934 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001935 }
jeffhaobdb76512011-09-07 11:43:16 -07001936 // Link interface method tables
Elliott Hughesbc258fa2011-10-06 14:45:21 -07001937 return LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001938 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07001939 // Link virtual and interface method tables
1940 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001941 }
1942 return true;
1943}
1944
1945bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001946 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001947 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
1948 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001949 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001950 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001951 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001952 // See if any of our virtual methods override the superclass.
1953 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001954 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001955 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001956 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001957 Method* super_method = vtable->Get(j);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07001958 if (local_method->HasSameNameAndDescriptor(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001959 // Verify
1960 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001961 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001962 PrettyDescriptor(klass->GetDescriptor()).c_str(),
1963 local_method->GetName()->ToModifiedUtf8().c_str(),
1964 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001965 return false;
1966 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001967 vtable->Set(j, local_method);
1968 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001969 break;
1970 }
1971 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07001972 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001973 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001974 vtable->Set(actual_count, local_method);
1975 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001976 actual_count += 1;
1977 }
1978 }
1979 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001980 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001981 return false;
1982 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001983 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001984 CHECK_LE(actual_count, max_count);
1985 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001986 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001987 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001988 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001989 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001990 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001991 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001992 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07001993 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001994 return false;
1995 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001996 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07001997 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001998 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
1999 vtable->Set(i, virtual_method);
2000 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002001 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002002 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002003 }
2004 return true;
2005}
2006
2007bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002008 size_t super_ifcount;
2009 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002010 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002011 } else {
2012 super_ifcount = 0;
2013 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002014 size_t ifcount = super_ifcount;
2015 ifcount += klass->NumInterfaces();
2016 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002017 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002018 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002019 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002020 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002021 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002022 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002023 return true;
2024 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002025 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002026 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002027 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2028 for (size_t i = 0; i < super_ifcount; i++) {
2029 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2030 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002031 }
2032 // Flatten the interface inheritance hierarchy.
2033 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002034 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002035 Class* interface = klass->GetInterface(i);
2036 DCHECK(interface != NULL);
2037 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002038 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002039 "Class %s implements non-interface class %s",
2040 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2041 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002042 return false;
2043 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002044 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002045 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002046 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002047 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2048 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002049 }
2050 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002051 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002052 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002053
2054 // If we're an interface, we don't need the vtable pointers, so we're done.
2055 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002056 return true;
2057 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002058 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002059 for (size_t i = 0; i < ifcount; ++i) {
2060 InterfaceEntry* interface_entry = iftable->Get(i);
2061 Class* interface = interface_entry->GetInterface();
2062 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2063 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002064 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002065 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2066 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002067 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002068 // For each method listed in the interface's method list, find the
2069 // matching method in our class's method list. We want to favor the
2070 // subclass over the superclass, which just requires walking
2071 // back from the end of the vtable. (This only matters if the
2072 // superclass defines a private method and this class redefines
2073 // it -- otherwise it would use the same vtable slot. In .dex files
2074 // those don't end up in the virtual method table, so it shouldn't
2075 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002076 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2077 Method* vtable_method = vtable->Get(k);
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002078 if (interface_method->HasSameNameAndDescriptor(vtable_method)) {
2079 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002080 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002081 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002082 return false;
2083 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002084 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002085 break;
2086 }
2087 }
2088 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002089 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07002090 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
2091 if (miranda_list[mir]->HasSameNameAndDescriptor(interface_method)) {
2092 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002093 break;
2094 }
2095 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002096 if (miranda_method == NULL) {
2097 // point the interface table at a phantom slot
2098 miranda_method = AllocMethod();
2099 memcpy(miranda_method, interface_method, sizeof(Method));
2100 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002101 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002102 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002103 }
2104 }
2105 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002106 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002107 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002108 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002109 klass->SetVirtualMethods((old_method_count == 0)
2110 ? AllocObjectArray<Method>(new_method_count)
2111 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002112
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002113 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2114 CHECK(vtable != NULL);
2115 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002116 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002117 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002118 for (size_t i = 0; i < miranda_list.size(); ++i) {
2119 Method* meth = miranda_list[i]; //AllocMethod();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002120 // TODO: this shouldn't be a memcpy
Elliott Hughes4681c802011-09-25 18:04:37 -07002121 //memcpy(meth, miranda_list[i], sizeof(Method));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002122 meth->SetDeclaringClass(klass);
2123 meth->SetAccessFlags(meth->GetAccessFlags() | kAccMiranda);
2124 meth->SetMethodIndex(0xFFFF & (old_vtable_count + i));
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002125 klass->SetVirtualMethod(old_method_count + i, meth);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002126 vtable->Set(old_vtable_count + i, meth);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002127 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002128 // TODO: do not assign to the vtable field until it is fully constructed.
2129 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002130 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002131
2132 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2133 for (int i = 0; i < vtable->GetLength(); ++i) {
2134 CHECK(vtable->Get(i) != NULL);
2135 }
2136
2137// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2138
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002139 return true;
2140}
2141
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002142bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002143 CHECK(klass != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002144 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002145}
2146
2147bool ClassLinker::LinkStaticFields(Class* klass) {
2148 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002149 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002150 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002151 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002152 return success;
2153}
2154
Brian Carlstromdbc05252011-09-09 01:59:59 -07002155struct LinkFieldsComparator {
2156 bool operator()(const Field* field1, const Field* field2){
2157
2158 // First come reference fields, then 64-bit, and finally 32-bit
2159 const Class* type1 = field1->GetTypeDuringLinking();
2160 const Class* type2 = field2->GetTypeDuringLinking();
2161 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2162 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2163 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2164 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2165 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2166 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2167 if (order1 != order2) {
2168 return order1 < order2;
2169 }
2170
2171 // same basic group? then sort by string.
2172 std::string name1 = field1->GetName()->ToModifiedUtf8();
2173 std::string name2 = field2->GetName()->ToModifiedUtf8();
2174 return name1 < name2;
2175 }
2176};
2177
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002178bool ClassLinker::LinkFields(Class* klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002179 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002180 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002181
2182 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002183 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002184
2185 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002186 size_t size;
2187 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002188 if (is_static) {
2189 size = klass->GetClassSize();
2190 field_offset = Class::FieldsOffset();
2191 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002192 Class* super_class = klass->GetSuperClass();
2193 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002194 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002195 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002196 }
2197 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002198 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002199
Brian Carlstromdbc05252011-09-09 01:59:59 -07002200 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002201
Brian Carlstromdbc05252011-09-09 01:59:59 -07002202 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002203 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002204 std::deque<Field*> grouped_and_sorted_fields;
2205 for (size_t i = 0; i < num_fields; i++) {
2206 grouped_and_sorted_fields.push_back(fields->Get(i));
2207 }
2208 std::sort(grouped_and_sorted_fields.begin(),
2209 grouped_and_sorted_fields.end(),
2210 LinkFieldsComparator());
2211
2212 // References should be at the front.
2213 size_t current_field = 0;
2214 size_t num_reference_fields = 0;
2215 for (; current_field < num_fields; current_field++) {
2216 Field* field = grouped_and_sorted_fields.front();
2217 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002218 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002219 bool isPrimitive = type != NULL && type->IsPrimitive();
2220 if (isPrimitive) {
2221 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002222 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002223 grouped_and_sorted_fields.pop_front();
2224 num_reference_fields++;
2225 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002226 field->SetOffset(field_offset);
2227 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002228 }
2229
2230 // Now we want to pack all of the double-wide fields together. If
2231 // we're not aligned, though, we want to shuffle one 32-bit field
2232 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002233 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2234 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2235 Field* field = grouped_and_sorted_fields[i];
2236 const Class* type = field->GetTypeDuringLinking();
2237 CHECK(type != NULL); // should only be working on primitive types
2238 DCHECK(type->IsPrimitive());
2239 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2240 continue;
2241 }
2242 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002243 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002244 // drop the consumed field
2245 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2246 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002247 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002248 // whether we found a 32-bit field for padding or not, we advance
2249 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002250 }
2251
2252 // Alignment is good, shuffle any double-wide fields forward, and
2253 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002254 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2255 while (!grouped_and_sorted_fields.empty()) {
2256 Field* field = grouped_and_sorted_fields.front();
2257 grouped_and_sorted_fields.pop_front();
2258 const Class* type = field->GetTypeDuringLinking();
2259 CHECK(type != NULL); // should only be working on primitive types
2260 DCHECK(type->IsPrimitive());
2261 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002262 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002263 field_offset = MemberOffset(field_offset.Uint32Value() +
2264 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2265 ? sizeof(uint64_t)
2266 : sizeof(uint32_t)));
2267 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002268 }
2269
Elliott Hughesadb460d2011-10-05 17:02:34 -07002270 // 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 -07002271 if (!is_static && klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002272 // We know there are no non-reference fields in the Reference classes, and we know
2273 // that 'referent' is alphabetically last, so this is easy...
2274 CHECK_EQ(num_reference_fields, num_fields);
2275 CHECK(fields->Get(num_fields - 1)->GetName()->Equals("referent"));
2276 --num_reference_fields;
2277 }
2278
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002279#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002280 // Make sure that all reference fields appear before
2281 // non-reference fields, and all double-wide fields are aligned.
2282 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002283 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002284 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002285 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002286 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002287 << " class=" << PrettyClass(klass)
2288 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002289 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2290 }
2291 const Class* type = field->GetTypeDuringLinking();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002292 bool is_primitive = (type != NULL && type->IsPrimitive());
2293 if (klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;") && field->GetName()->Equals("referent")) {
2294 is_primitive = true; // We lied above, so we have to expect a lie here.
2295 }
2296 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002297 if (!seen_non_ref) {
2298 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002299 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002300 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002301 } else {
2302 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002303 }
2304 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002305 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002306 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002307 }
2308#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002309 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002310 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002311 if (is_static) {
2312 klass->SetNumReferenceStaticFields(num_reference_fields);
2313 klass->SetClassSize(size);
2314 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002315 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002316 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002317 klass->SetObjectSize(size);
2318 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002319 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002320 return true;
2321}
2322
2323// Set the bitmap of reference offsets, refOffsets, from the ifields
2324// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002325void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002326 uint32_t reference_offsets = 0;
2327 Class* super_class = klass->GetSuperClass();
2328 if (super_class != NULL) {
2329 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002330 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002331 if (reference_offsets == CLASS_WALK_SUPER) {
2332 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002333 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002334 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002335 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002336 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002337}
2338
2339void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002340 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002341}
2342
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002343void ClassLinker::CreateReferenceOffsets(Class* klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002344 uint32_t reference_offsets) {
2345 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002346 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2347 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002348 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002349 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002350 // All of the fields that contain object references are guaranteed
2351 // to be at the beginning of the fields list.
2352 for (size_t i = 0; i < num_reference_fields; ++i) {
2353 // Note that byte_offset is the offset from the beginning of
2354 // object, not the offset into instance data
2355 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002356 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002357 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2358 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2359 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002360 CHECK_NE(new_bit, 0U);
2361 reference_offsets |= new_bit;
2362 } else {
2363 reference_offsets = CLASS_WALK_SUPER;
2364 break;
2365 }
2366 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002367 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002368 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002369 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002370 } else {
2371 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002372 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002373}
2374
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002375String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002376 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002377 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002378 if (resolved != NULL) {
2379 return resolved;
2380 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002381 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2382 int32_t utf16_length = dex_file.GetStringLength(string_id);
2383 const char* utf8_data = dex_file.GetStringData(string_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002384 // TODO: remote the const_cast below
2385 String* string = const_cast<String*>(intern_table_->InternStrong(utf16_length, utf8_data));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002386 dex_cache->SetResolvedString(string_idx, string);
2387 return string;
2388}
2389
2390Class* ClassLinker::ResolveType(const DexFile& dex_file,
2391 uint32_t type_idx,
2392 DexCache* dex_cache,
2393 const ClassLoader* class_loader) {
2394 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002395 if (resolved == NULL) {
2396 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002397 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002398 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002399 Class* check = resolved;
2400 while (check->IsArrayClass()) {
2401 check = check->GetComponentType();
2402 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002403 if (dex_cache != check->GetDexCache()) {
2404 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002405 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002406 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002407 resolved = NULL;
2408 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002409 }
2410 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002411 if (resolved != NULL) {
2412 dex_cache->SetResolvedType(type_idx, resolved);
2413 } else {
2414 DCHECK(Thread::Current()->IsExceptionPending());
2415 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002416 }
2417 return resolved;
2418}
2419
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002420Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2421 uint32_t method_idx,
2422 DexCache* dex_cache,
2423 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002424 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002425 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2426 if (resolved != NULL) {
2427 return resolved;
2428 }
2429 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2430 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2431 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002432 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002433 return NULL;
2434 }
2435
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002436 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002437 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002438 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002439 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002440 } else if (klass->IsInterface()) {
2441 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002442 } else {
2443 resolved = klass->FindVirtualMethod(name, signature);
2444 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002445 if (resolved != NULL) {
2446 dex_cache->SetResolvedMethod(method_idx, resolved);
2447 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002448 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002449 }
2450 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002451}
2452
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002453Field* ClassLinker::ResolveField(const DexFile& dex_file,
2454 uint32_t field_idx,
2455 DexCache* dex_cache,
2456 const ClassLoader* class_loader,
2457 bool is_static) {
2458 Field* resolved = dex_cache->GetResolvedField(field_idx);
2459 if (resolved != NULL) {
2460 return resolved;
2461 }
2462 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2463 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2464 if (klass == NULL) {
2465 return NULL;
2466 }
2467
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002468 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002469 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002470 if (field_type == NULL) {
2471 // TODO: LinkageError?
2472 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2473 << " in " << PrettyClass(klass);
2474 return NULL;
2475}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002476 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002477 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002478 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002479 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002480 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002481 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002482 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002483 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002484 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002485 }
2486 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002487}
2488
Ian Rogersad25ac52011-10-04 19:13:33 -07002489const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2490 Class* declaring_class = referrer->GetDeclaringClass();
2491 DexCache* dex_cache = declaring_class->GetDexCache();
2492 const DexFile& dex_file = FindDexFile(dex_cache);
2493 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2494 return dex_file.GetShorty(method_id.proto_idx_);
2495}
2496
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002497void ClassLinker::DumpAllClasses(int flags) const {
2498 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2499 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2500 std::vector<Class*> all_classes;
2501 {
2502 MutexLock mu(lock_);
2503 typedef Table::const_iterator It; // TODO: C++0x auto
2504 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2505 all_classes.push_back(it->second);
2506 }
2507 }
2508
2509 for (size_t i = 0; i < all_classes.size(); ++i) {
2510 all_classes[i]->DumpClass(std::cerr, flags);
2511 }
2512}
2513
Elliott Hughese27955c2011-08-26 15:21:24 -07002514size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002515 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002516 return classes_.size();
2517}
2518
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519} // namespace art