blob: 53bcf7e93fc61e439943b7c64a3666e4a0ee971b [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"
Ian Rogers466bb252011-10-14 03:29:56 -070022#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070023#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070024#include "space.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070025#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070026#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070027#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070028#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070029
30namespace art {
31
Elliott Hughes4a2b4172011-09-20 17:08:25 -070032namespace {
33
34void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
35void ThrowNoClassDefFoundError(const char* fmt, ...) {
36 va_list args;
37 va_start(args, fmt);
38 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
39 va_end(args);
40}
41
Elliott Hughese555dc02011-09-25 10:46:35 -070042void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
43void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070044 va_list args;
45 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070046 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070047 va_end(args);
48}
49
50void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__ (__printf__, 1, 2)));
51void ThrowLinkageError(const char* fmt, ...) {
52 va_list args;
53 va_start(args, fmt);
54 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
55 va_end(args);
56}
57
Elliott Hughescc5f9a92011-09-28 19:17:29 -070058void ThrowNoSuchMethodError(const char* kind,
59 Class* c, const StringPiece& name, const StringPiece& signature) {
60 DexCache* dex_cache = c->GetDexCache();
61 std::stringstream msg;
62 msg << "no " << kind << " method " << name << "." << signature
63 << " in class " << c->GetDescriptor()->ToModifiedUtf8()
64 << " or its superclasses";
65 if (dex_cache) {
66 msg << " (defined in " << dex_cache->GetLocation()->ToModifiedUtf8() << ")";
67 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070068 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070069}
70
Elliott Hughes4a2b4172011-09-20 17:08:25 -070071void ThrowEarlierClassFailure(Class* c) {
72 /*
73 * The class failed to initialize on a previous attempt, so we want to throw
74 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
75 * failed in verification, in which case v2 5.4.1 says we need to re-throw
76 * the previous error.
77 */
78 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
79
80 if (c->GetVerifyErrorClass() != NULL) {
81 // TODO: change the verifier to store an _instance_, with a useful detail message?
82 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070083 Thread::Current()->ThrowNewException(error_descriptor.c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -070084 PrettyDescriptor(c->GetDescriptor()).c_str());
85 } else {
86 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
87 }
88}
89
Elliott Hughes4d0207c2011-10-03 19:14:34 -070090void WrapExceptionInInitializer() {
91 JNIEnv* env = Thread::Current()->GetJniEnv();
92
93 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
94 CHECK(cause.get() != NULL);
95
96 env->ExceptionClear();
97
98 // TODO: add java.lang.Error to JniConstants?
99 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
100 CHECK(error_class.get() != NULL);
101 if (env->IsInstanceOf(cause.get(), error_class.get())) {
102 // We only wrap non-Error exceptions; an Error can just be used as-is.
103 env->Throw(cause.get());
104 return;
105 }
106
107 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
108 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
109 CHECK(eiie_class.get() != NULL);
110
111 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
112 CHECK(mid != NULL);
113
114 ScopedLocalRef<jthrowable> eiie(env,
115 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
116 env->Throw(eiie.get());
117}
118
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700119}
120
Elliott Hughes418d20f2011-09-22 14:00:39 -0700121const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700122 "Ljava/lang/Class;",
123 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700124 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700125 "[Ljava/lang/Object;",
126 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700127 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700128 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700129 "Ljava/lang/reflect/Field;",
130 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700131 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700132 "Ljava/lang/ClassLoader;",
133 "Ldalvik/system/BaseDexClassLoader;",
134 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700135 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700136 "Z",
137 "B",
138 "C",
139 "D",
140 "F",
141 "I",
142 "J",
143 "S",
144 "V",
145 "[Z",
146 "[B",
147 "[C",
148 "[D",
149 "[F",
150 "[I",
151 "[J",
152 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700153 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700154};
155
Elliott Hughes5f791332011-09-15 17:45:30 -0700156class ObjectLock {
157 public:
158 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
159 CHECK(object != NULL);
160 obj_->MonitorEnter(self_);
161 }
162
163 ~ObjectLock() {
164 obj_->MonitorExit(self_);
165 }
166
167 void Wait() {
168 return Monitor::Wait(self_, obj_, 0, 0, false);
169 }
170
171 void Notify() {
172 obj_->Notify();
173 }
174
175 void NotifyAll() {
176 obj_->NotifyAll();
177 }
178
179 private:
180 Thread* self_;
181 Object* obj_;
182 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
183};
184
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700185ClassLinker* ClassLinker::Create(const std::string& boot_class_path,
186 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700187 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700188 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700189 class_linker->Init(boot_class_path);
190 return class_linker.release();
191}
192
193ClassLinker* ClassLinker::Create(InternTable* intern_table) {
194 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
195 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700196 return class_linker.release();
197}
198
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700199ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom16192862011-09-12 17:50:06 -0700200 : lock_("ClassLinker lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700201 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700202 array_interfaces_(NULL),
203 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700204 init_done_(false),
205 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700206 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700207}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700208
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700209void CreateClassPath(const std::string& class_path,
210 std::vector<const DexFile*>& class_path_vector) {
211 std::vector<std::string> parsed;
212 Split(class_path, ':', parsed);
213 for (size_t i = 0; i < parsed.size(); ++i) {
214 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
215 if (dex_file != NULL) {
216 class_path_vector.push_back(dex_file);
217 }
218 }
219}
220
221void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700222 const Runtime* runtime = Runtime::Current();
223 if (runtime->IsVerboseStartup()) {
224 LOG(INFO) << "ClassLinker::InitFrom entering";
225 }
226
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700227 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700228
Elliott Hughes30646832011-10-13 16:59:46 -0700229 // java_lang_Class comes first, it's needed for AllocClass
230 Class* java_lang_Class = down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700231 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700232 java_lang_Class->SetClass(java_lang_Class);
233 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700234 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700235
Elliott Hughes418d20f2011-09-22 14:00:39 -0700236 // Class[] is used for reflection support.
237 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
238 class_array_class->SetComponentType(java_lang_Class);
239
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700240 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700241 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700242 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700243 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700244 java_lang_Class->SetSuperClass(java_lang_Object);
245 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700246
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700247 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700248 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700249 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700250
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700251 // Setup the char class to be used for char[]
252 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
253
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700255 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700256 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700257 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700258
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700259 // Setup String
260 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
261 String::SetClass(java_lang_String);
262 java_lang_String->SetObjectSize(sizeof(String));
263 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400264
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700265 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700266 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
267 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700268 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700269 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
270 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
271 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700272
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700273 // Create storage for root classes, save away our work so far (requires
274 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700275 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700276 CHECK(class_roots_ != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700277 SetClassRoot(kJavaLangClass, java_lang_Class);
278 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700279 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700280 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700281 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700282 SetClassRoot(kJavaLangString, java_lang_String);
283
284 // Setup the primitive type classes.
285 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
286 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700287 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
288 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
289 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
290 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
291 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
292 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
293
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700295 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700296 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297
298 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
299 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700300 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
302 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700303 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700304
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700305 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700306
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700307 // setup boot_class_path_ and register class_path now that we can
308 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700309 std::vector<const DexFile*> boot_class_path_vector;
310 CreateClassPath(boot_class_path, boot_class_path_vector);
311 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
312 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700313 CHECK(dex_file != NULL);
314 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700315 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700316
Elliott Hughes80609252011-09-23 17:24:51 -0700317 // Constructor, Field, and Method are necessary so that FindClass can link members
318 Class* java_lang_reflect_Constructor = AllocClass(java_lang_Class, sizeof(MethodClass));
319 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
320 CHECK(java_lang_reflect_Constructor != NULL);
321 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
322 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor);
323 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
324
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700325 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
326 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700327 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700328 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
329 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
330 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
331 Field::SetClass(java_lang_reflect_Field);
332
333 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Elliott Hughes80609252011-09-23 17:24:51 -0700334 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700335 CHECK(java_lang_reflect_Method != NULL);
336 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
337 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
338 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Elliott Hughes80609252011-09-23 17:24:51 -0700339 Method::SetClasses(java_lang_reflect_Constructor, java_lang_reflect_Method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700340
341 // now we can use FindSystemClass
342
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700343 // run char class through InitializePrimitiveClass to finish init
344 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
345 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
346
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700347 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348 java_lang_Object->SetStatus(Class::kStatusNotReady);
349 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
350 CHECK_EQ(java_lang_Object, Object_class);
351 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
352 java_lang_String->SetStatus(Class::kStatusNotReady);
353 Class* String_class = FindSystemClass("Ljava/lang/String;");
354 CHECK_EQ(java_lang_String, String_class);
355 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
356
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700357 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
359 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
360
361 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
362 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
363
364 Class* found_char_array_class = FindSystemClass("[C");
365 CHECK_EQ(char_array_class, found_char_array_class);
366
367 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
368 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
369
370 Class* found_int_array_class = FindSystemClass("[I");
371 CHECK_EQ(int_array_class, found_int_array_class);
372
373 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
374 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
375
376 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
377 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
378
379 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
380 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
381
Elliott Hughes418d20f2011-09-22 14:00:39 -0700382 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
383 CHECK_EQ(class_array_class, found_class_array_class);
384
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700385 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
386 CHECK_EQ(object_array_class, found_object_array_class);
387
388 // Setup the single, global copies of "interfaces" and "iftable"
389 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
390 CHECK(java_lang_Cloneable != NULL);
391 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
392 CHECK(java_io_Serializable != NULL);
393 CHECK(array_interfaces_ != NULL);
394 array_interfaces_->Set(0, java_lang_Cloneable);
395 array_interfaces_->Set(1, java_io_Serializable);
396 // We assume that Cloneable/Serializable don't have superinterfaces --
397 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700398 // supers as well.
399 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
400 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700401
Elliott Hughes418d20f2011-09-22 14:00:39 -0700402 // Sanity check Class[] and Object[]'s interfaces
403 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
404 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700405 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
406 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700407
Elliott Hughes80609252011-09-23 17:24:51 -0700408 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700409 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700410 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700411 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700412
Elliott Hughes80609252011-09-23 17:24:51 -0700413 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
414 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
415 CHECK_EQ(java_lang_reflect_Constructor, Constructor_class);
416
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700417 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700418 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700419 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700420
421 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700422 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700423 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700424
Ian Rogers466bb252011-10-14 03:29:56 -0700425 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
426
427 // Create java.lang.reflect.Proxy root
428 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
429 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
430
Brian Carlstrom1f870082011-08-23 16:02:11 -0700431 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700432 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
433 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700434 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700435 java_lang_ref_FinalizerReference->SetAccessFlags(
436 java_lang_ref_FinalizerReference->GetAccessFlags() |
437 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700438 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700439 java_lang_ref_PhantomReference->SetAccessFlags(
440 java_lang_ref_PhantomReference->GetAccessFlags() |
441 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700442 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700443 java_lang_ref_SoftReference->SetAccessFlags(
444 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700445 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700446 java_lang_ref_WeakReference->SetAccessFlags(
447 java_lang_ref_WeakReference->GetAccessFlags() |
448 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700449
Brian Carlstromaded5f72011-10-07 17:15:04 -0700450 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700451 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700452 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700453 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
454
455 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
456 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
457 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
458
459 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
460 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
461 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
462 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
463
464 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700465 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
466 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700467 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700468
Brian Carlstroma663ea52011-08-19 23:33:41 -0700469 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700470
471 if (runtime->IsVerboseStartup()) {
472 LOG(INFO) << "ClassLinker::InitFrom exiting";
473 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700474}
475
476void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700477 const Runtime* runtime = Runtime::Current();
478 if (runtime->IsVerboseStartup()) {
479 LOG(INFO) << "ClassLinker::FinishInit entering";
480 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700481
482 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700483 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700484 // as the types of the field can't be resolved prior to the runtime being
485 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700486 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700487 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700488 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
489
Elliott Hughesadb460d2011-10-05 17:02:34 -0700490 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
491
Brian Carlstrom16192862011-09-12 17:50:06 -0700492 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
493 CHECK(pendingNext->GetName()->Equals("pendingNext"));
494 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
495
496 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
497 CHECK(queue->GetName()->Equals("queue"));
Elliott Hughesadb460d2011-10-05 17:02:34 -0700498 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue), java_lang_ref_ReferenceQueue);
Brian Carlstrom16192862011-09-12 17:50:06 -0700499
500 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
501 CHECK(queueNext->GetName()->Equals("queueNext"));
502 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
503
504 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
505 CHECK(referent->GetName()->Equals("referent"));
506 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
507
508 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
509 CHECK(zombie->GetName()->Equals("zombie"));
510 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
511
512 Heap::SetReferenceOffsets(referent->GetOffset(),
513 queue->GetOffset(),
514 queueNext->GetOffset(),
515 pendingNext->GetOffset(),
516 zombie->GetOffset());
517
Brian Carlstroma663ea52011-08-19 23:33:41 -0700518 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700519 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700520 ClassRoot class_root = static_cast<ClassRoot>(i);
521 Class* klass = GetClassRoot(class_root);
522 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700523 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700524 // note SetClassRoot does additional validation.
525 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700526 }
527
Elliott Hughes92f14b22011-10-06 12:29:54 -0700528 CHECK(array_iftable_ != NULL);
529 CHECK(array_interfaces_ != NULL);
530
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700531 // disable the slow paths in FindClass and CreatePrimitiveClass now
532 // that Object, Class, and Object[] are setup
533 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700534
535 if (runtime->IsVerboseStartup()) {
536 LOG(INFO) << "ClassLinker::FinishInit exiting";
537 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700538}
539
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700540void ClassLinker::RunRootClinits() {
541 Thread* self = Thread::Current();
542 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
543 Class* c = GetClassRoot(ClassRoot(i));
544 if (!c->IsArrayClass() && !c->IsPrimitive()) {
545 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700546 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700547 }
548 }
549}
550
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700551OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700552 MutexLock mu(lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700553 const Runtime* runtime = Runtime::Current();
554 if (runtime->IsVerboseStartup()) {
555 LOG(INFO) << "ClassLinker::OpenOat entering";
556 }
557 const ImageHeader& image_header = space->GetImageHeader();
558 String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
559 std::string oat_filename;
560 oat_filename += runtime->GetHostPrefix();
561 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700562 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700563 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700564 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700565 return NULL;
566 }
567 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
568 uint32_t image_oat_checksum = image_header.GetOatChecksum();
569 if (oat_checksum != image_oat_checksum) {
570 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
571 << " to expected oat checksum " << std::hex << oat_checksum
572 << " in image";
573 return NULL;
574 }
575 oat_files_.push_back(oat_file);
576 if (runtime->IsVerboseStartup()) {
577 LOG(INFO) << "ClassLinker::OpenOat exiting";
578 }
579 return oat_file;
580}
581
Brian Carlstromaded5f72011-10-07 17:15:04 -0700582const OatFile* ClassLinker::FindOatFile(const DexFile& dex_file) {
583 MutexLock mu(lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700584 // TODO: check if dex_file matches an OatDexFile location and checksum
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700585 return FindOatFile(OatFile::DexFileToOatFilename(dex_file));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700586}
587
588const OatFile* ClassLinker::FindOatFile(const std::string& location) {
589 for (size_t i = 0; i < oat_files_.size(); i++) {
590 const OatFile* oat_file = oat_files_[i];
591 DCHECK(oat_file != NULL);
592 if (oat_file->GetLocation() == location) {
593 return oat_file;
594 }
595 }
596
597 const OatFile* oat_file = OatFile::Open(location, "", NULL);
598 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700599 if (location.empty() || location[0] != '/') {
600 LOG(ERROR) << "Failed to open oat file from " << location;
601 return NULL;
602 }
603 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700604 std::string cache_location = GetArtCacheOatFilenameOrDie(location);
Brian Carlstroma9f19782011-10-13 00:14:47 -0700605 oat_file = OatFile::Open(cache_location, "", NULL);
606 if (oat_file == NULL) {
607 LOG(ERROR) << "Failed to open oat file from " << location << " or " << cache_location << ".";
608 return NULL;
609 }
610
611
Brian Carlstromaded5f72011-10-07 17:15:04 -0700612 }
613 return oat_file;
614}
615
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700616void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700617 const Runtime* runtime = Runtime::Current();
618 if (runtime->IsVerboseStartup()) {
619 LOG(INFO) << "ClassLinker::InitFromImage entering";
620 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700621 CHECK(!init_done_);
622
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700623 const std::vector<Space*>& spaces = Heap::GetSpaces();
624 for (size_t i = 0; i < spaces.size(); i++) {
625 Space* space = spaces[i] ;
626 if (space->IsImageSpace()) {
627 OatFile* oat_file = OpenOat(space);
628 CHECK(oat_file != NULL) << "Failed to open oat file for image";
629 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
630 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
631
632 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
633 static_cast<uint32_t>(dex_caches->GetLength()));
634 for (int i = 0; i < dex_caches->GetLength(); i++) {
635 DexCache* dex_cache = dex_caches->Get(i);
636 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
637
638 std::string dex_filename;
639 dex_filename += runtime->GetHostPrefix();
640 dex_filename += dex_file_location;
641 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
642 if (dex_file == NULL) {
643 LOG(FATAL) << "Failed to open dex file " << dex_filename
644 << " referenced from oat file as " << dex_file_location;
645 }
646
Brian Carlstromaded5f72011-10-07 17:15:04 -0700647 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
648 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700649
Brian Carlstromdf143242011-10-10 18:05:34 -0700650 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700651 }
652 }
653 }
654
Brian Carlstroma663ea52011-08-19 23:33:41 -0700655 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
656 DCHECK(heap_bitmap != NULL);
657
Brian Carlstroma663ea52011-08-19 23:33:41 -0700658 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700659 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700660
661 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700662 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
663 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700664
Elliott Hughes92f14b22011-10-06 12:29:54 -0700665 // reinit array_interfaces_ and array_iftable_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700666 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
667 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700668 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
669 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700670
Brian Carlstroma663ea52011-08-19 23:33:41 -0700671 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700672 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700673 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700674 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
675 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
676 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
677 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
678 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
679 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
680 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
681 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700682 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700683 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700684
685 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700686
687 if (runtime->IsVerboseStartup()) {
688 LOG(INFO) << "ClassLinker::InitFromImage exiting";
689 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700690}
691
Brian Carlstrom78128a62011-09-15 17:21:19 -0700692void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700693 DCHECK(obj != NULL);
694 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700695 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700696
Brian Carlstromc74255f2011-09-11 22:47:39 -0700697 if (obj->IsString()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700698 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700699 return;
700 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700701 if (obj->IsClass()) {
702 // restore class to ClassLinker::classes_ table
703 Class* klass = obj->AsClass();
704 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
705 class_linker->InsertClass(descriptor, klass);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700706 return;
707 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700708}
709
710// Keep in sync with InitCallback. Anything we visit, we need to
711// reinit references to when reinitializing a ClassLinker from a
712// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700713void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
714 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700715
716 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700717 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700718 }
719
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700720 {
Brian Carlstrom16192862011-09-12 17:50:06 -0700721 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700722 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700723 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700724 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700725 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700726 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700727
Elliott Hughes410c0c82011-09-01 17:58:25 -0700728 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700729}
730
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700731ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700732 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700733 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700734 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700735 BooleanArray::ResetArrayClass();
736 ByteArray::ResetArrayClass();
737 CharArray::ResetArrayClass();
738 DoubleArray::ResetArrayClass();
739 FloatArray::ResetArrayClass();
740 IntArray::ResetArrayClass();
741 LongArray::ResetArrayClass();
742 ShortArray::ResetArrayClass();
743 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700744 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700745 STLDeleteElements(&boot_class_path_);
746 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700747}
748
749DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Elliott Hughes30646832011-10-13 16:59:46 -0700750 String* location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
751 if (location == NULL) {
752 return NULL;
753 }
Brian Carlstrom83db7722011-08-26 17:32:56 -0700754 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Elliott Hughes30646832011-10-13 16:59:46 -0700755 if (dex_cache == NULL) {
756 return NULL;
757 }
758 // TODO: lots of missing null checks hidden in this call...
759 dex_cache->Init(location,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700760 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700761 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700762 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700763 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700764 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
765 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700766 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700767}
768
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700769CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
770 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700771}
772
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700773InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
774 DCHECK(interface->IsInterface());
775 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
776 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
777 interface_entry->SetInterface(interface);
778 return interface_entry;
779}
780
Brian Carlstrom4873d462011-08-21 15:23:39 -0700781Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
782 DCHECK_GE(class_size, sizeof(Class));
783 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700784 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
785 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700786 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700787}
788
Brian Carlstrom4873d462011-08-21 15:23:39 -0700789Class* ClassLinker::AllocClass(size_t class_size) {
790 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700791}
792
Jesse Wilson35baaab2011-08-10 16:18:03 -0400793Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700794 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700795}
796
797Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700798 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700799}
800
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700801ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
802 return ObjectArray<StackTraceElement>::Alloc(
803 GetClassRoot(kJavaLangStackTraceElementArrayClass),
804 length);
805}
806
Brian Carlstromaded5f72011-10-07 17:15:04 -0700807Class* EnsureResolved(Class* klass) {
808 DCHECK(klass != NULL);
809 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700810 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700811 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700812 ObjectLock lock(klass);
813 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700814 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700815 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700816 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700817 return NULL;
818 }
819 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700820 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700821 lock.Wait();
822 }
823 }
824 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700825 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700826 return NULL;
827 }
828 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700829 CHECK(klass->IsResolved()) << PrettyClass(klass);
830 CHECK(!self->IsExceptionPending())
831 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
832 return klass;
833}
834
835Class* ClassLinker::FindClass(const std::string& descriptor,
836 const ClassLoader* class_loader) {
837 CHECK_NE(descriptor.size(), 0U);
838 Thread* self = Thread::Current();
839 DCHECK(self != NULL);
840 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
841 // Find the class in the loaded classes table.
842 Class* klass = LookupClass(descriptor, class_loader);
843 if (klass != NULL) {
844 return EnsureResolved(klass);
845 }
846 if (descriptor.size() == 1) {
847 // only the descriptors of primitive types should be 1 character long
848 return FindPrimitiveClass(descriptor[0]);
849 }
850 // Class is not yet loaded.
851 if (descriptor[0] == '[') {
852 return CreateArrayClass(descriptor, class_loader);
853 }
854 if (class_loader == NULL) {
855 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
856 if (pair.second == NULL) {
857 std::string name(PrintableString(descriptor));
858 ThrowNoClassDefFoundError("Class %s not found in boot class loader", name.c_str());
859 return NULL;
860 }
861 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
862 }
863
864 if (ClassLoader::UseCompileTimeClassPath()) {
865 const std::vector<const DexFile*>& class_path
866 = ClassLoader::GetCompileTimeClassPath(class_loader);
867 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
868 if (pair.second == NULL) {
869 return FindSystemClass(descriptor);
870 }
871 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
872 }
873
874 std::string class_name_string = DescriptorToDot(descriptor);
875 ScopedThreadStateChange(self, Thread::kNative);
876 JNIEnv* env = self->GetJniEnv();
Brian Carlstromdf143242011-10-10 18:05:34 -0700877 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
878 CHECK(c.get() != NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700879 // TODO: cache method?
Brian Carlstromdf143242011-10-10 18:05:34 -0700880 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700881 CHECK(mid != NULL);
Brian Carlstromdf143242011-10-10 18:05:34 -0700882 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -0700883 if (class_name_object.get() == NULL) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700884 return NULL;
885 }
Brian Carlstromdf143242011-10-10 18:05:34 -0700886 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
887 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
888 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700889}
890
891Class* ClassLinker::DefineClass(const std::string& descriptor,
892 const ClassLoader* class_loader,
893 const DexFile& dex_file,
894 const DexFile::ClassDef& dex_class_def) {
895 Class* klass;
896 // Load the class from the dex file.
897 if (!init_done_) {
898 // finish up init of hand crafted class_roots_
899 if (descriptor == "Ljava/lang/Object;") {
900 klass = GetClassRoot(kJavaLangObject);
901 } else if (descriptor == "Ljava/lang/Class;") {
902 klass = GetClassRoot(kJavaLangClass);
903 } else if (descriptor == "Ljava/lang/String;") {
904 klass = GetClassRoot(kJavaLangString);
905 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
906 klass = GetClassRoot(kJavaLangReflectConstructor);
907 } else if (descriptor == "Ljava/lang/reflect/Field;") {
908 klass = GetClassRoot(kJavaLangReflectField);
909 } else if (descriptor == "Ljava/lang/reflect/Method;") {
910 klass = GetClassRoot(kJavaLangReflectMethod);
911 } else {
912 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
913 }
914 } else {
915 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
916 }
917 klass->SetDexCache(FindDexCache(dex_file));
918 LoadClass(dex_file, dex_class_def, klass, class_loader);
919 // Check for a pending exception during load
920 Thread* self = Thread::Current();
921 if (self->IsExceptionPending()) {
922 return NULL;
923 }
924 ObjectLock lock(klass);
925 klass->SetClinitThreadId(self->GetTid());
926 // Add the newly loaded class to the loaded classes table.
927 bool success = InsertClass(descriptor, klass); // TODO: just return collision
928 if (!success) {
929 // We may fail to insert if we raced with another thread.
930 klass->SetClinitThreadId(0);
931 klass = LookupClass(descriptor, class_loader);
932 CHECK(klass != NULL);
933 return klass;
934 }
935 // Finish loading (if necessary) by finding parents
936 CHECK(!klass->IsLoaded());
937 if (!LoadSuperAndInterfaces(klass, dex_file)) {
938 // Loading failed.
939 CHECK(self->IsExceptionPending());
940 lock.NotifyAll();
941 return NULL;
942 }
943 CHECK(klass->IsLoaded());
944 // Link the class (if necessary)
945 CHECK(!klass->IsResolved());
946 if (!LinkClass(klass)) {
947 // Linking failed.
948 CHECK(self->IsExceptionPending());
949 lock.NotifyAll();
950 return NULL;
951 }
952 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700953 return klass;
954}
955
Brian Carlstrom4873d462011-08-21 15:23:39 -0700956// Precomputes size that will be needed for Class, matching LinkStaticFields
957size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
958 const DexFile::ClassDef& dex_class_def) {
959 const byte* class_data = dex_file.GetClassData(dex_class_def);
960 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
961 size_t num_static_fields = header.static_fields_size_;
962 size_t num_ref = 0;
963 size_t num_32 = 0;
964 size_t num_64 = 0;
965 if (num_static_fields != 0) {
966 uint32_t last_idx = 0;
967 for (size_t i = 0; i < num_static_fields; ++i) {
968 DexFile::Field dex_field;
969 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
970 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
971 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
972 char c = descriptor[0];
973 if (c == 'L' || c == '[') {
974 num_ref++;
975 } else if (c == 'J' || c == 'D') {
976 num_64++;
977 } else {
978 num_32++;
979 }
980 }
981 }
982
983 // start with generic class data
984 size_t size = sizeof(Class);
985 // follow with reference fields which must be contiguous at start
986 size += (num_ref * sizeof(uint32_t));
987 // if there are 64-bit fields to add, make sure they are aligned
988 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
989 if (num_32 != 0) {
990 // use an available 32-bit field for padding
991 num_32--;
992 }
993 size += sizeof(uint32_t); // either way, we are adding a word
994 DCHECK_EQ(size, RoundUp(size, 8));
995 }
996 // tack on any 64-bit fields now that alignment is assured
997 size += (num_64 * sizeof(uint64_t));
998 // tack on any remaining 32-bit fields
999 size += (num_32 * sizeof(uint32_t));
1000 return size;
1001}
1002
Brian Carlstrom92827a52011-10-10 15:50:01 -07001003void LinkCode(Method* method, const OatFile::OatClass* oat_class, uint32_t method_index) {
1004 // Every kind of method should at least get an invoke stub from the oat_method.
1005 // non-abstract methods also get their code pointers.
1006 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
1007 oat_method.LinkMethod(method);
1008
1009 if (method->IsAbstract()) {
1010 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1011 return;
1012 }
1013 if (method->IsNative()) {
1014 // unregistering restores the dlsym lookup stub
1015 method->UnregisterNative();
1016 return;
1017 }
1018}
1019
Brian Carlstromf615a612011-07-23 12:50:34 -07001020void ClassLinker::LoadClass(const DexFile& dex_file,
1021 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001022 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001023 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001024 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001025 CHECK(klass->GetDexCache() != NULL);
1026 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001027 const byte* class_data = dex_file.GetClassData(dex_class_def);
1028 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001029
Brian Carlstromf615a612011-07-23 12:50:34 -07001030 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001031 CHECK(descriptor != NULL);
1032
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001033 klass->SetClass(GetClassRoot(kJavaLangClass));
1034 if (klass->GetDescriptor() != NULL) {
1035 DCHECK(klass->GetDescriptor()->Equals(descriptor));
1036 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001037 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001038 if (klass->GetDescriptor() == NULL) {
1039 return;
1040 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001041 }
1042 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001043 // Make sure that none of our runtime-only flags are set.
1044 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001045 klass->SetAccessFlags(access_flags);
1046 klass->SetClassLoader(class_loader);
1047 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
1048 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001049
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001050 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001051
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001052 size_t num_static_fields = header.static_fields_size_;
1053 size_t num_instance_fields = header.instance_fields_size_;
1054 size_t num_direct_methods = header.direct_methods_size_;
1055 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001056
Jesse Wilson6384f642011-10-07 18:08:35 -04001057 const char* source_file = dex_file.dexGetSourceFile(dex_class_def);
1058 if (source_file != NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001059 String* source_file_string = intern_table_->InternStrong(source_file);
1060 if (source_file_string == NULL) {
1061 return;
1062 }
1063 klass->SetSourceFile(source_file_string);
Jesse Wilson6384f642011-10-07 18:08:35 -04001064 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001065
1066 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -07001067 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001068
1069 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001070 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001071 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001072 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001073 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001074 DexFile::Field dex_field;
1075 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001076 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001077 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001078 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001079 }
1080 }
1081
1082 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001083 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001084 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001085 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001086 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001087 DexFile::Field dex_field;
1088 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001089 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001090 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001091 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001092 }
1093 }
1094
Brian Carlstromaded5f72011-10-07 17:15:04 -07001095 UniquePtr<const OatFile::OatClass> oat_class;
1096 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
1097 const OatFile* oat_file = FindOatFile(dex_file);
1098 if (oat_file != NULL) {
1099 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1100 if (oat_dex_file != NULL) {
1101 uint32_t class_def_index;
1102 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1103 CHECK(found) << descriptor;
1104 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001105 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001106 }
1107 }
1108 }
1109 size_t method_index = 0;
1110
Brian Carlstrom934486c2011-07-12 23:42:50 -07001111 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001112 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001113 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001114 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001115 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001116 for (size_t i = 0; i < num_direct_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001117 DexFile::Method dex_method;
1118 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom92827a52011-10-10 15:50:01 -07001119 Method* method = AllocMethod();
1120 klass->SetDirectMethod(i, method);
1121 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001122 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001123 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001124 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001125 }
1126 }
1127
1128 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001129 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001130 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001131 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001132 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001133 for (size_t i = 0; i < num_virtual_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001134 DexFile::Method dex_method;
1135 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom92827a52011-10-10 15:50:01 -07001136 Method* method = AllocMethod();
1137 klass->SetVirtualMethod(i, method);
1138 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001139 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001140 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001141 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001142 }
1143 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001144}
1145
Brian Carlstromf615a612011-07-23 12:50:34 -07001146void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1147 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001148 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001149 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001150 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001151 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001152 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1153 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001154 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001155 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001156 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001157 }
1158 }
1159}
1160
Brian Carlstromf615a612011-07-23 12:50:34 -07001161void ClassLinker::LoadField(const DexFile& dex_file,
1162 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001163 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001164 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001165 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001166 dst->SetDeclaringClass(klass);
1167 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1168 dst->SetTypeIdx(field_id.type_idx_);
1169 dst->SetAccessFlags(src.access_flags_);
1170
1171 // In order to access primitive types using GetTypeDuringLinking we need to
1172 // ensure they are resolved into the dex cache
1173 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1174 if (descriptor[1] == '\0') {
1175 // only the descriptors of primitive types should be 1 character long
1176 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
1177 DCHECK(resolved->IsPrimitive());
1178 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001179}
1180
Brian Carlstromf615a612011-07-23 12:50:34 -07001181void ClassLinker::LoadMethod(const DexFile& dex_file,
1182 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001183 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001184 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001185 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001186 dst->SetDeclaringClass(klass);
Elliott Hughes20cde902011-10-04 17:37:27 -07001187
Elliott Hughes80609252011-09-23 17:24:51 -07001188 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Elliott Hughes30646832011-10-13 16:59:46 -07001189 if (method_name == NULL) {
1190 return;
1191 }
Elliott Hughes80609252011-09-23 17:24:51 -07001192 dst->SetName(method_name);
1193 if (method_name->Equals("<init>")) {
1194 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1195 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001196
1197 int32_t utf16_length;
1198 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Elliott Hughes30646832011-10-13 16:59:46 -07001199 String* signature_string = intern_table_->InternStrong(utf16_length, signature.c_str());
1200 if (signature_string == NULL) {
1201 return;
1202 }
1203 dst->SetSignature(signature_string);
Elliott Hughes20cde902011-10-04 17:37:27 -07001204
1205 if (method_name->Equals("finalize") && signature == "()V") {
1206 /*
1207 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1208 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1209 * exclude it here.
1210 *
1211 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1212 */
1213 if (klass->GetClassLoader() != NULL ||
1214 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1215 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1216 klass->SetFinalizable();
1217 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001218 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001219
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001220 dst->SetProtoIdx(method_id.proto_idx_);
1221 dst->SetCodeItemOffset(src.code_off_);
1222 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Elliott Hughes30646832011-10-13 16:59:46 -07001223 String* shorty_string = intern_table_->InternStrong(shorty);
1224 dst->SetShorty(shorty_string);
1225 if (shorty_string == NULL) {
1226 return;
1227 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001228 dst->SetAccessFlags(src.access_flags_);
1229 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001230
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001231 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1232 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1233 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1234 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1235 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1236 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001237
Brian Carlstrom934486c2011-07-12 23:42:50 -07001238 // TODO: check for finalize method
1239
Brian Carlstromf615a612011-07-23 12:50:34 -07001240 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001241 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001242 dst->SetNumRegisters(code_item->registers_size_);
1243 dst->SetNumIns(code_item->ins_size_);
1244 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001245 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001246 uint16_t num_args = Method::NumArgRegisters(shorty);
1247 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001248 ++num_args;
1249 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001250 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001251 // TODO: native methods
1252 }
1253}
1254
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001255void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001256 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1257}
1258
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001259void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001260 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001261 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001262 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001263}
1264
Brian Carlstromaded5f72011-10-07 17:15:04 -07001265bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
1266 lock_.AssertHeld();
1267 for (size_t i = 0; i != dex_files_.size(); ++i) {
1268 if (dex_files_[i] == &dex_file) {
1269 return true;
1270 }
1271 }
1272 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001273}
1274
Brian Carlstromaded5f72011-10-07 17:15:04 -07001275bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001276 MutexLock mu(lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001277 return IsDexFileRegistered(dex_file);
1278}
1279
1280void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, DexCache* dex_cache) {
1281 lock_.AssertHeld();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001282 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1283 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001284 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001285 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001286}
1287
Brian Carlstromaded5f72011-10-07 17:15:04 -07001288void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
1289 MutexLock mu(lock_);
1290 if (IsDexFileRegisteredLocked(dex_file)) {
1291 return;
1292 }
1293 RegisterDexFileLocked(dex_file, AllocDexCache(dex_file));
1294}
1295
1296void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
1297 MutexLock mu(lock_);
1298 RegisterDexFileLocked(dex_file, dex_cache);
1299}
1300
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001301const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001302 CHECK(dex_cache != NULL);
Brian Carlstrom16192862011-09-12 17:50:06 -07001303 MutexLock mu(lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001304 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1305 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001306 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001307 }
1308 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001309 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001310 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001311}
1312
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001313DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom16192862011-09-12 17:50:06 -07001314 MutexLock mu(lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001315 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001316 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001317 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001318 }
1319 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001320 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001321 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001322}
1323
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001324Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1325 const char* descriptor,
1326 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001327 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001328 CHECK(primitive_class != NULL);
1329 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1330 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001331 CHECK(primitive_class->GetDescriptor() != NULL);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001332 primitive_class->SetPrimitiveType(type);
1333 primitive_class->SetStatus(Class::kStatusInitialized);
1334 bool success = InsertClass(descriptor, primitive_class);
1335 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1336 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001337}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001338
Brian Carlstrombe977852011-07-19 14:54:54 -07001339// Create an array class (i.e. the class object for the array, not the
1340// array itself). "descriptor" looks like "[C" or "[[[[B" or
1341// "[Ljava/lang/String;".
1342//
1343// If "descriptor" refers to an array of primitives, look up the
1344// primitive type's internally-generated class object.
1345//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001346// "class_loader" is the class loader of the class that's referring to
1347// us. It's used to ensure that we're looking for the element type in
1348// the right context. It does NOT become the class loader for the
1349// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001350//
1351// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001352Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001353 const ClassLoader* class_loader) {
1354 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001355
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001356 // Identify the underlying component type
1357 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001358 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001359 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001360 return NULL;
1361 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001362
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001363 // See if the component type is already loaded. Array classes are
1364 // always associated with the class loader of their underlying
1365 // element type -- an array of Strings goes with the loader for
1366 // java/lang/String -- so we need to look for it there. (The
1367 // caller should have checked for the existence of the class
1368 // before calling here, but they did so with *their* class loader,
1369 // not the component type's loader.)
1370 //
1371 // If we find it, the caller adds "loader" to the class' initiating
1372 // loader list, which should prevent us from going through this again.
1373 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001374 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001375 // are the same, because our caller (FindClass) just did the
1376 // lookup. (Even if we get this wrong we still have correct behavior,
1377 // because we effectively do this lookup again when we add the new
1378 // class to the hash table --- necessary because of possible races with
1379 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001380 if (class_loader != component_type->GetClassLoader()) {
1381 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001382 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001383 return new_class;
1384 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001385 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001386
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001387 // Fill out the fields in the Class.
1388 //
1389 // It is possible to execute some methods against arrays, because
1390 // all arrays are subclasses of java_lang_Object_, so we need to set
1391 // up a vtable. We can just point at the one in java_lang_Object_.
1392 //
1393 // Array classes are simple enough that we don't need to do a full
1394 // link step.
1395
1396 Class* new_class = NULL;
1397 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001398 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001399 if (descriptor == "[Ljava/lang/Class;") {
1400 new_class = GetClassRoot(kClassArrayClass);
1401 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001402 new_class = GetClassRoot(kObjectArrayClass);
1403 } else if (descriptor == "[C") {
1404 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001405 } else if (descriptor == "[I") {
1406 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001407 }
1408 }
1409 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001410 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001411 if (new_class == NULL) {
1412 return NULL;
1413 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001414 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001415 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001416 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001417 if (new_class->GetDescriptor() != NULL) {
1418 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1419 } else {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001420 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001421 if (new_class->GetDescriptor() == NULL) {
1422 return NULL;
1423 }
Brian Carlstrom693267a2011-09-06 09:25:34 -07001424 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001425 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001426 new_class->SetSuperClass(java_lang_Object);
1427 new_class->SetVTable(java_lang_Object->GetVTable());
1428 new_class->SetPrimitiveType(Class::kPrimNot);
1429 new_class->SetClassLoader(component_type->GetClassLoader());
1430 new_class->SetStatus(Class::kStatusInitialized);
1431 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001432 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001433
1434
1435 // All arrays have java/lang/Cloneable and java/io/Serializable as
1436 // interfaces. We need to set that up here, so that stuff like
1437 // "instanceof" works right.
1438 //
1439 // Note: The GC could run during the call to FindSystemClass,
1440 // so we need to make sure the class object is GC-valid while we're in
1441 // there. Do this by clearing the interface list so the GC will just
1442 // think that the entries are null.
1443
1444
1445 // Use the single, global copies of "interfaces" and "iftable"
1446 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001447 CHECK(array_interfaces_ != NULL);
1448 CHECK(array_iftable_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001449 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001450 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001451
1452 // Inherit access flags from the component type. Arrays can't be
1453 // used as a superclass or interface, so we want to add "final"
1454 // and remove "interface".
1455 //
1456 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001457 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001458 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001459 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1460 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001461
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001462 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001463 return new_class;
1464 }
1465 // Another thread must have loaded the class after we
1466 // started but before we finished. Abandon what we've
1467 // done.
1468 //
1469 // (Yes, this happens.)
1470
1471 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001472 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001473 DCHECK(other_class != NULL);
1474 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001475}
1476
1477Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001478 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001479 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001480 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001481 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001482 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001483 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001484 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001485 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001486 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001487 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001488 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001489 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001490 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001491 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001492 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001493 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001494 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001495 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001496 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001497 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001498 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001499 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001500 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001501}
1502
Brian Carlstromaded5f72011-10-07 17:15:04 -07001503bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001504 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001505 MutexLock mu(lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001506 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001507 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001508}
1509
Brian Carlstromaded5f72011-10-07 17:15:04 -07001510Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001511 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom16192862011-09-12 17:50:06 -07001512 MutexLock mu(lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001513 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001514 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001515 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001516 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001517 return klass;
1518 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001519 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001520 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001521}
1522
jeffhao98eacac2011-09-14 16:11:53 -07001523void ClassLinker::VerifyClass(Class* klass) {
1524 if (klass->IsVerified()) {
1525 return;
1526 }
1527
1528 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001529 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001530
jeffhao5cfd6fb2011-09-27 13:54:29 -07001531 if (DexVerifier::VerifyClass(klass)) {
1532 klass->SetStatus(Class::kStatusVerified);
1533 } else {
1534 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001535 Thread* self = Thread::Current();
1536 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1537 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
1538 PrettyDescriptor(klass->GetDescriptor()).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001539 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001540 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001541 }
jeffhao98eacac2011-09-14 16:11:53 -07001542}
1543
Jesse Wilson95caa792011-10-12 18:14:17 -04001544Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers466bb252011-10-14 03:29:56 -07001545 ClassLoader* loader, ObjectArray<Method>* methods, ObjectArray<ObjectArray<Class> >* throws) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001546 Class* klass = AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass));
1547 CHECK(klass != NULL);
1548 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers466bb252011-10-14 03:29:56 -07001549 const char* descriptor = DotToDescriptor(name->ToModifiedUtf8().c_str()).c_str();;
1550 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Jesse Wilson95caa792011-10-12 18:14:17 -04001551 klass->SetAccessFlags(kAccPublic | kAccFinal);
1552 klass->SetClassLoader(loader);
Ian Rogers466bb252011-10-14 03:29:56 -07001553 klass->SetStatus(Class::kStatusInitialized); // no loading or initializing necessary
1554 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1555 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1556 klass->SetInterfaces(interfaces); // The interfaces are the array of interfaces specified
Jesse Wilson95caa792011-10-12 18:14:17 -04001557
Ian Rogers466bb252011-10-14 03:29:56 -07001558 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001559 klass->SetDirectMethods(AllocObjectArray<Method>(1));
1560 klass->SetDirectMethod(0, CreateProxyConstructor(klass));
1561
Ian Rogers466bb252011-10-14 03:29:56 -07001562 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001563 size_t num_virtual_methods = methods->GetLength();
1564 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1565 for (size_t i = 0; i < num_virtual_methods; ++i) {
1566 Method* prototype = methods->Get(i);
1567 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype, throws->Get(i)));
1568 }
Ian Rogers466bb252011-10-14 03:29:56 -07001569 // Link the virtual methods, creating vtable and iftables
Jesse Wilson95caa792011-10-12 18:14:17 -04001570 if (!LinkMethods(klass)) {
1571 DCHECK(Thread::Current()->IsExceptionPending());
1572 return NULL;
1573 }
Jesse Wilson95caa792011-10-12 18:14:17 -04001574 return klass;
1575}
1576
1577Method* ClassLinker::CreateProxyConstructor(Class* klass) {
Ian Rogers466bb252011-10-14 03:29:56 -07001578 // Create constructor for Proxy that must initialize h
1579 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1580 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
1581 CHECK_EQ(proxy_direct_methods->GetLength(), 12);
1582 Method* proxy_constructor = proxy_direct_methods->Get(2);
1583 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1584 // code_ too)
1585 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1586 // Make this constructor public and fix the class to be our Proxy version
1587 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Jesse Wilson95caa792011-10-12 18:14:17 -04001588 constructor->SetDeclaringClass(klass);
Ian Rogers466bb252011-10-14 03:29:56 -07001589 // Sanity checks
1590 CHECK(constructor->IsConstructor());
1591 CHECK(constructor->GetName()->Equals("<init>"));
1592 CHECK(constructor->GetSignature()->Equals("(Ljava/lang/reflect/InvocationHandler;)V"));
1593 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001594 return constructor;
1595}
1596
Ian Rogers466bb252011-10-14 03:29:56 -07001597Method* ClassLinker::CreateProxyMethod(Class* klass, Method* prototype,
1598 ObjectArray<Class>* throws) {
1599 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialise
1600 // as necessary
1601 Method* method = down_cast<Method*>(prototype->Clone());
1602
1603 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1604 // the intersection of throw exceptions as defined in Proxy
Jesse Wilson95caa792011-10-12 18:14:17 -04001605 method->SetDeclaringClass(klass);
Ian Rogers466bb252011-10-14 03:29:56 -07001606 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001607 method->SetExceptionTypes(throws);
1608
Ian Rogers466bb252011-10-14 03:29:56 -07001609 // At runtime the method looks like a reference and argument saving method, clone the code
1610 // related parameters from this method.
1611 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1612 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1613 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1614 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1615 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Jesse Wilson95caa792011-10-12 18:14:17 -04001616
Ian Rogers466bb252011-10-14 03:29:56 -07001617 // Basic sanity
1618 DCHECK(method->GetName()->Equals(prototype->GetName()));
1619 DCHECK(method->GetSignature()->Equals(prototype->GetSignature()));
1620 DCHECK(method->GetShorty()->Equals(prototype->GetShorty()));
1621
1622 // More complex sanity - via dex cache
1623 CHECK_EQ(method->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04001624
1625 return method;
1626}
1627
Brian Carlstrom25c33252011-09-18 15:58:35 -07001628bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001629 CHECK(klass->IsResolved() || klass->IsErroneous())
1630 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001631
Carl Shapirob5573532011-07-12 18:22:59 -07001632 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001633
Brian Carlstrom25c33252011-09-18 15:58:35 -07001634 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001635 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001636 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001637 ObjectLock lock(klass);
1638
Brian Carlstromd1422f82011-09-28 11:37:09 -07001639 if (klass->GetStatus() == Class::kStatusInitialized) {
1640 return true;
1641 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001642
Brian Carlstromd1422f82011-09-28 11:37:09 -07001643 if (klass->IsErroneous()) {
1644 ThrowEarlierClassFailure(klass);
1645 return false;
1646 }
1647
1648 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001649 VerifyClass(klass);
1650 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001651 return false;
1652 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001653 }
1654
Brian Carlstrom25c33252011-09-18 15:58:35 -07001655 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1656 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001657 // if the class has a <clinit> but we can't run it during compilation,
1658 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001659 return false;
1660 }
1661
Brian Carlstromd1422f82011-09-28 11:37:09 -07001662 // If the class is kStatusInitializing, either this thread is
1663 // initializing higher up the stack or another thread has beat us
1664 // to initializing and we need to wait. Either way, this
1665 // invocation of InitializeClass will not be responsible for
1666 // running <clinit> and will return.
1667 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001668 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001669 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001670 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001671 return true;
1672 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001673 // No. That's fine. Wait for another thread to finish initializing.
1674 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001675 }
1676
1677 if (!ValidateSuperClassDescriptors(klass)) {
1678 klass->SetStatus(Class::kStatusError);
1679 return false;
1680 }
1681
Brian Carlstromd1422f82011-09-28 11:37:09 -07001682 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001683
Elliott Hughesdcc24742011-09-07 14:02:44 -07001684 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001685 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001686 }
1687
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001688 uint64_t t0 = NanoTime();
1689
Brian Carlstrom25c33252011-09-18 15:58:35 -07001690 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001691 return false;
1692 }
1693
1694 InitializeStaticFields(klass);
1695
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001696 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001697 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001698 }
1699
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001700 uint64_t t1 = NanoTime();
1701
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001702 {
1703 ObjectLock lock(klass);
1704
1705 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001706 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001707 klass->SetStatus(Class::kStatusError);
1708 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001709 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1710 RuntimeStats* thread_stats = self->GetStats();
1711 ++global_stats->class_init_count;
1712 ++thread_stats->class_init_count;
1713 global_stats->class_init_time_ns += (t1 - t0);
1714 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001715 klass->SetStatus(Class::kStatusInitialized);
1716 }
1717 lock.NotifyAll();
1718 }
1719
1720 return true;
1721}
1722
Brian Carlstromd1422f82011-09-28 11:37:09 -07001723bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1724 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001725 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001726 lock.Wait();
1727
1728 // When we wake up, repeat the test for init-in-progress. If
1729 // there's an exception pending (only possible if
1730 // "interruptShouldThrow" was set), bail out.
1731 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001732 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001733 klass->SetStatus(Class::kStatusError);
1734 return false;
1735 }
1736 // Spurious wakeup? Go back to waiting.
1737 if (klass->GetStatus() == Class::kStatusInitializing) {
1738 continue;
1739 }
1740 if (klass->IsErroneous()) {
1741 // The caller wants an exception, but it was thrown in a
1742 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001743 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
1744 PrettyDescriptor(klass->GetDescriptor()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001745 return false;
1746 }
1747 if (klass->IsInitialized()) {
1748 return true;
1749 }
1750 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1751 }
1752 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1753}
1754
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001755bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1756 if (klass->IsInterface()) {
1757 return true;
1758 }
1759 // begin with the methods local to the superclass
1760 if (klass->HasSuperClass() &&
1761 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1762 const Class* super = klass->GetSuperClass();
1763 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001764 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001765 if (method != super->GetVirtualMethod(i) &&
1766 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001767 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1768
1769 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 -07001770 return false;
1771 }
1772 }
1773 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001774 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1775 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1776 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001777 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1778 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001779 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001780 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001781 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001782 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1783
1784 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 -07001785 return false;
1786 }
1787 }
1788 }
1789 }
1790 return true;
1791}
1792
1793bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001794 const Class* klass1,
1795 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001796 if (method->IsMiranda()) {
1797 return true;
1798 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001799 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001800 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001801 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001802 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001803 const char* descriptor = it->GetDescriptor();
1804 if (descriptor == NULL) {
1805 break;
1806 }
1807 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1808 // Found a non-primitive type.
1809 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1810 return false;
1811 }
1812 }
1813 }
1814 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001815 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001816 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001817 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001818 return false;
1819 }
1820 }
1821 return true;
1822}
1823
1824// Returns true if classes referenced by the descriptor are the
1825// same classes in klass1 as they are in klass2.
1826bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001827 const Class* klass1,
1828 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001829 CHECK(descriptor != NULL);
1830 CHECK(klass1 != NULL);
1831 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001832 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001833 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001834 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001835 // TODO: found2 == NULL
1836 // TODO: lookup found1 in initiating loader list
1837 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001838 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001839 if (found1 == found2) {
1840 return true;
1841 } else {
1842 return false;
1843 }
1844 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001845 return true;
1846}
1847
Brian Carlstrom25c33252011-09-18 15:58:35 -07001848bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001849 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001850 if (!klass->IsInterface() && klass->HasSuperClass()) {
1851 Class* super_class = klass->GetSuperClass();
1852 if (super_class->GetStatus() != Class::kStatusInitialized) {
1853 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001854 Thread* self = Thread::Current();
1855 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001856 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001857 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001858 // TODO: check for a pending exception
1859 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001860 if (!can_run_clinit) {
1861 // Don't set status to error when we can't run <clinit>.
1862 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1863 klass->SetStatus(Class::kStatusVerified);
1864 return false;
1865 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001866 klass->SetStatus(Class::kStatusError);
1867 klass->NotifyAll();
1868 return false;
1869 }
1870 }
1871 }
1872 return true;
1873}
1874
Brian Carlstrom25c33252011-09-18 15:58:35 -07001875bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001876 CHECK(c != NULL);
1877 if (c->IsInitialized()) {
1878 return true;
1879 }
1880
Elliott Hughes5f791332011-09-15 17:45:30 -07001881 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001882 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001883 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001884 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001885}
1886
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001887void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1888 Class* c, std::map<int, Field*>& field_map) {
1889 const ClassLoader* cl = c->GetClassLoader();
1890 const byte* class_data = dex_file.GetClassData(dex_class_def);
1891 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1892 uint32_t last_idx = 0;
1893 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1894 DexFile::Field dex_field;
1895 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1896 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1897 }
1898}
1899
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001900void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001901 size_t num_static_fields = klass->NumStaticFields();
1902 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001903 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001904 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001905 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001906 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001907 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001908 return;
1909 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001910 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001911 const DexFile& dex_file = FindDexFile(dex_cache);
1912 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001913 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001914
1915 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1916 std::map<int, Field*> field_map;
1917 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1918
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001919 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001920 if (addr == NULL) {
1921 // All this class' static fields have default values.
1922 return;
1923 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001924 size_t array_size = DecodeUnsignedLeb128(&addr);
1925 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001926 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001927 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001928 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001929 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001930 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001931 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001932 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001933 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001934 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001935 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001936 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001937 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001938 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001939 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001940 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001941 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001942 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001943 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001944 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001945 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001946 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001947 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001948 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001949 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001950 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001951 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001952 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001953 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001954 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001955 break;
1956 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001957 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001958 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001959 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001960 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001961 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001962 break;
1963 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001964 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001965 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001966 }
1967}
1968
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001969bool ClassLinker::LinkClass(Class* klass) {
1970 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001971 if (!LinkSuperClass(klass)) {
1972 return false;
1973 }
1974 if (!LinkMethods(klass)) {
1975 return false;
1976 }
1977 if (!LinkInstanceFields(klass)) {
1978 return false;
1979 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001980 if (!LinkStaticFields(klass)) {
1981 return false;
1982 }
1983 CreateReferenceInstanceOffsets(klass);
1984 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001985 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
1986 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001987 return true;
1988}
1989
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001990bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001991 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
1992 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
1993 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001994 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07001995 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001996 return false;
1997 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001998 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001999 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002000 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
2001 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07002002 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002003 klass->SetInterface(i, interface);
2004 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002005 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002006 return false;
2007 }
2008 // Verify
2009 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002010 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002011 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002012 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002013 PrettyDescriptor(interface->GetDescriptor()).c_str(),
2014 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002015 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002016 }
2017 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002018 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002019 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 return true;
2021}
2022
2023bool ClassLinker::LinkSuperClass(Class* klass) {
2024 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002025 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002026 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002027 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002028 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002029 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002030 return false;
2031 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002032 return true;
2033 }
2034 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002035 ThrowLinkageError("No superclass defined for class %s",
2036 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002037 return false;
2038 }
2039 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002040 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002041 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002042 "Superclass %s of %s is %s",
2043 PrettyDescriptor(super->GetDescriptor()).c_str(),
2044 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002045 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002046 return false;
2047 }
2048 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002049 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002050 "Superclass %s is inaccessible by %s",
2051 PrettyDescriptor(super->GetDescriptor()).c_str(),
2052 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002053 return false;
2054 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002055
2056 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2057 if (super->IsFinalizable()) {
2058 klass->SetFinalizable();
2059 }
2060
Elliott Hughes2da50362011-10-10 16:57:08 -07002061 // Inherit reference flags (if any) from the superclass.
2062 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2063 if (reference_flags != 0) {
2064 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2065 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002066 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002067 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002068 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
2069 PrettyDescriptor(klass->GetDescriptor()).c_str());
2070 return false;
2071 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002072
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002073#ifndef NDEBUG
2074 // Ensure super classes are fully resolved prior to resolving fields..
2075 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002076 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002077 super = super->GetSuperClass();
2078 }
2079#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002080 return true;
2081}
2082
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002083// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002084bool ClassLinker::LinkMethods(Class* klass) {
2085 if (klass->IsInterface()) {
2086 // No vtable.
2087 size_t count = klass->NumVirtualMethods();
2088 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002089 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002090 return false;
2091 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002092 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002093 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002094 }
jeffhaobdb76512011-09-07 11:43:16 -07002095 // Link interface method tables
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002096 return LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002097 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002098 // Link virtual and interface method tables
2099 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002100 }
2101 return true;
2102}
2103
2104bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002105 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002106 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2107 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002108 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002109 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002110 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002111 // See if any of our virtual methods override the superclass.
2112 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002113 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002114 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002115 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002116 Method* super_method = vtable->Get(j);
Ian Rogers466bb252011-10-14 03:29:56 -07002117 if (local_method->HasSameNameAndSignature(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118 // Verify
2119 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002120 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002121 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2122 local_method->GetName()->ToModifiedUtf8().c_str(),
2123 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002124 return false;
2125 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002126 vtable->Set(j, local_method);
2127 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002128 break;
2129 }
2130 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002131 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002132 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002133 vtable->Set(actual_count, local_method);
2134 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002135 actual_count += 1;
2136 }
2137 }
2138 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002139 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002140 return false;
2141 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002142 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002143 CHECK_LE(actual_count, max_count);
2144 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002145 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002146 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002147 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002148 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002149 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002150 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002151 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002152 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002153 return false;
2154 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002155 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002156 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002157 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2158 vtable->Set(i, virtual_method);
2159 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002160 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002161 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002162 }
2163 return true;
2164}
2165
2166bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002167 size_t super_ifcount;
2168 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002169 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002170 } else {
2171 super_ifcount = 0;
2172 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002173 size_t ifcount = super_ifcount;
2174 ifcount += klass->NumInterfaces();
2175 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002176 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002177 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002178 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002179 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002180 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002181 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002182 return true;
2183 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002184 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002185 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002186 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2187 for (size_t i = 0; i < super_ifcount; i++) {
2188 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2189 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002190 }
2191 // Flatten the interface inheritance hierarchy.
2192 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002193 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002194 Class* interface = klass->GetInterface(i);
2195 DCHECK(interface != NULL);
2196 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002197 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002198 "Class %s implements non-interface class %s",
2199 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2200 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002201 return false;
2202 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002203 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002204 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002205 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002206 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2207 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002208 }
2209 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002210 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002211 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002212
2213 // If we're an interface, we don't need the vtable pointers, so we're done.
2214 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002215 return true;
2216 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002217 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002218 for (size_t i = 0; i < ifcount; ++i) {
2219 InterfaceEntry* interface_entry = iftable->Get(i);
2220 Class* interface = interface_entry->GetInterface();
2221 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2222 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002223 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002224 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2225 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002226 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002227 // For each method listed in the interface's method list, find the
2228 // matching method in our class's method list. We want to favor the
2229 // subclass over the superclass, which just requires walking
2230 // back from the end of the vtable. (This only matters if the
2231 // superclass defines a private method and this class redefines
2232 // it -- otherwise it would use the same vtable slot. In .dex files
2233 // those don't end up in the virtual method table, so it shouldn't
2234 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002235 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2236 Method* vtable_method = vtable->Get(k);
Ian Rogers466bb252011-10-14 03:29:56 -07002237 if (interface_method->HasSameNameAndSignature(vtable_method)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002238 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002239 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002240 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002241 return false;
2242 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002243 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002244 break;
2245 }
2246 }
2247 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002248 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07002249 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers466bb252011-10-14 03:29:56 -07002250 if (miranda_list[mir]->HasSameNameAndSignature(interface_method)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002251 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002252 break;
2253 }
2254 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002255 if (miranda_method == NULL) {
2256 // point the interface table at a phantom slot
2257 miranda_method = AllocMethod();
2258 memcpy(miranda_method, interface_method, sizeof(Method));
2259 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002260 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002261 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002262 }
2263 }
2264 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002265 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002266 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002267 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002268 klass->SetVirtualMethods((old_method_count == 0)
2269 ? AllocObjectArray<Method>(new_method_count)
2270 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002271
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002272 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2273 CHECK(vtable != NULL);
2274 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002275 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002276 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002277 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002278 Method* method = miranda_list[i];
2279 method->SetDeclaringClass(klass);
2280 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2281 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2282 klass->SetVirtualMethod(old_method_count + i, method);
2283 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002284 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002285 // TODO: do not assign to the vtable field until it is fully constructed.
2286 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002287 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002288
2289 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2290 for (int i = 0; i < vtable->GetLength(); ++i) {
2291 CHECK(vtable->Get(i) != NULL);
2292 }
2293
2294// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2295
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002296 return true;
2297}
2298
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002300 CHECK(klass != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002301 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002302}
2303
2304bool ClassLinker::LinkStaticFields(Class* klass) {
2305 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002306 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002307 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002308 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002309 return success;
2310}
2311
Brian Carlstromdbc05252011-09-09 01:59:59 -07002312struct LinkFieldsComparator {
2313 bool operator()(const Field* field1, const Field* field2){
2314
2315 // First come reference fields, then 64-bit, and finally 32-bit
2316 const Class* type1 = field1->GetTypeDuringLinking();
2317 const Class* type2 = field2->GetTypeDuringLinking();
2318 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2319 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2320 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2321 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2322 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2323 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2324 if (order1 != order2) {
2325 return order1 < order2;
2326 }
2327
2328 // same basic group? then sort by string.
2329 std::string name1 = field1->GetName()->ToModifiedUtf8();
2330 std::string name2 = field2->GetName()->ToModifiedUtf8();
2331 return name1 < name2;
2332 }
2333};
2334
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002335bool ClassLinker::LinkFields(Class* klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002336 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002337 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002338
2339 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002340 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002341
2342 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002343 size_t size;
2344 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002345 if (is_static) {
2346 size = klass->GetClassSize();
2347 field_offset = Class::FieldsOffset();
2348 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002349 Class* super_class = klass->GetSuperClass();
2350 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002351 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002352 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002353 }
2354 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002355 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002356
Brian Carlstromdbc05252011-09-09 01:59:59 -07002357 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002358
Brian Carlstromdbc05252011-09-09 01:59:59 -07002359 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002360 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002361 std::deque<Field*> grouped_and_sorted_fields;
2362 for (size_t i = 0; i < num_fields; i++) {
2363 grouped_and_sorted_fields.push_back(fields->Get(i));
2364 }
2365 std::sort(grouped_and_sorted_fields.begin(),
2366 grouped_and_sorted_fields.end(),
2367 LinkFieldsComparator());
2368
2369 // References should be at the front.
2370 size_t current_field = 0;
2371 size_t num_reference_fields = 0;
2372 for (; current_field < num_fields; current_field++) {
2373 Field* field = grouped_and_sorted_fields.front();
2374 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002375 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002376 bool isPrimitive = type != NULL && type->IsPrimitive();
2377 if (isPrimitive) {
2378 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002379 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002380 grouped_and_sorted_fields.pop_front();
2381 num_reference_fields++;
2382 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002383 field->SetOffset(field_offset);
2384 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002385 }
2386
2387 // Now we want to pack all of the double-wide fields together. If
2388 // we're not aligned, though, we want to shuffle one 32-bit field
2389 // into place. If we can't find one, we'll have to pad it.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002390 if (current_field != num_fields && !IsAligned(field_offset.Uint32Value(), 8)) {
2391 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2392 Field* field = grouped_and_sorted_fields[i];
2393 const Class* type = field->GetTypeDuringLinking();
2394 CHECK(type != NULL); // should only be working on primitive types
2395 DCHECK(type->IsPrimitive());
2396 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2397 continue;
2398 }
2399 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002400 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002401 // drop the consumed field
2402 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2403 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002404 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002405 // whether we found a 32-bit field for padding or not, we advance
2406 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002407 }
2408
2409 // Alignment is good, shuffle any double-wide fields forward, and
2410 // finish assigning field offsets to all fields.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002411 DCHECK(current_field == num_fields || IsAligned(field_offset.Uint32Value(), 8));
2412 while (!grouped_and_sorted_fields.empty()) {
2413 Field* field = grouped_and_sorted_fields.front();
2414 grouped_and_sorted_fields.pop_front();
2415 const Class* type = field->GetTypeDuringLinking();
2416 CHECK(type != NULL); // should only be working on primitive types
2417 DCHECK(type->IsPrimitive());
2418 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002419 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002420 field_offset = MemberOffset(field_offset.Uint32Value() +
2421 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2422 ? sizeof(uint64_t)
2423 : sizeof(uint32_t)));
2424 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002425 }
2426
Elliott Hughesadb460d2011-10-05 17:02:34 -07002427 // 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 -07002428 if (!is_static && klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002429 // We know there are no non-reference fields in the Reference classes, and we know
2430 // that 'referent' is alphabetically last, so this is easy...
2431 CHECK_EQ(num_reference_fields, num_fields);
2432 CHECK(fields->Get(num_fields - 1)->GetName()->Equals("referent"));
2433 --num_reference_fields;
2434 }
2435
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002436#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002437 // Make sure that all reference fields appear before
2438 // non-reference fields, and all double-wide fields are aligned.
2439 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002440 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002441 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002442 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002443 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002444 << " class=" << PrettyClass(klass)
2445 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002446 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2447 }
2448 const Class* type = field->GetTypeDuringLinking();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002449 bool is_primitive = (type != NULL && type->IsPrimitive());
2450 if (klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;") && field->GetName()->Equals("referent")) {
2451 is_primitive = true; // We lied above, so we have to expect a lie here.
2452 }
2453 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002454 if (!seen_non_ref) {
2455 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002456 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002457 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002458 } else {
2459 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002460 }
2461 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002462 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002463 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002464 }
2465#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002466 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002467 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002468 if (is_static) {
2469 klass->SetNumReferenceStaticFields(num_reference_fields);
2470 klass->SetClassSize(size);
2471 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002472 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002473 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002474 klass->SetObjectSize(size);
2475 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002476 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002477 return true;
2478}
2479
2480// Set the bitmap of reference offsets, refOffsets, from the ifields
2481// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002482void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002483 uint32_t reference_offsets = 0;
2484 Class* super_class = klass->GetSuperClass();
2485 if (super_class != NULL) {
2486 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002487 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002488 if (reference_offsets == CLASS_WALK_SUPER) {
2489 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002490 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002491 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002492 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002493 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002494}
2495
2496void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002497 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002498}
2499
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002500void ClassLinker::CreateReferenceOffsets(Class* klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002501 uint32_t reference_offsets) {
2502 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002503 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2504 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002505 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002506 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002507 // All of the fields that contain object references are guaranteed
2508 // to be at the beginning of the fields list.
2509 for (size_t i = 0; i < num_reference_fields; ++i) {
2510 // Note that byte_offset is the offset from the beginning of
2511 // object, not the offset into instance data
2512 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002513 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002514 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2515 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2516 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002517 CHECK_NE(new_bit, 0U);
2518 reference_offsets |= new_bit;
2519 } else {
2520 reference_offsets = CLASS_WALK_SUPER;
2521 break;
2522 }
2523 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002524 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002525 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002526 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002527 } else {
2528 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002529 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002530}
2531
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002532String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002533 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002534 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002535 if (resolved != NULL) {
2536 return resolved;
2537 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002538 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2539 int32_t utf16_length = dex_file.GetStringLength(string_id);
2540 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002541 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002542 dex_cache->SetResolvedString(string_idx, string);
2543 return string;
2544}
2545
2546Class* ClassLinker::ResolveType(const DexFile& dex_file,
2547 uint32_t type_idx,
2548 DexCache* dex_cache,
2549 const ClassLoader* class_loader) {
2550 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002551 if (resolved == NULL) {
2552 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002553 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002554 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002555 Class* check = resolved;
2556 while (check->IsArrayClass()) {
2557 check = check->GetComponentType();
2558 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002559 if (dex_cache != check->GetDexCache()) {
2560 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002561 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002562 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002563 resolved = NULL;
2564 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002565 }
2566 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002567 if (resolved != NULL) {
2568 dex_cache->SetResolvedType(type_idx, resolved);
2569 } else {
2570 DCHECK(Thread::Current()->IsExceptionPending());
2571 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002572 }
2573 return resolved;
2574}
2575
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002576Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2577 uint32_t method_idx,
2578 DexCache* dex_cache,
2579 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002580 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002581 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2582 if (resolved != NULL) {
2583 return resolved;
2584 }
2585 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2586 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2587 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002588 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002589 return NULL;
2590 }
2591
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002592 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002593 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002594 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002595 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002596 } else if (klass->IsInterface()) {
2597 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002598 } else {
2599 resolved = klass->FindVirtualMethod(name, signature);
2600 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002601 if (resolved != NULL) {
2602 dex_cache->SetResolvedMethod(method_idx, resolved);
2603 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002604 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002605 }
2606 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002607}
2608
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002609Field* ClassLinker::ResolveField(const DexFile& dex_file,
2610 uint32_t field_idx,
2611 DexCache* dex_cache,
2612 const ClassLoader* class_loader,
2613 bool is_static) {
2614 Field* resolved = dex_cache->GetResolvedField(field_idx);
2615 if (resolved != NULL) {
2616 return resolved;
2617 }
2618 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2619 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2620 if (klass == NULL) {
2621 return NULL;
2622 }
2623
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002624 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002625 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002626 if (field_type == NULL) {
2627 // TODO: LinkageError?
2628 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2629 << " in " << PrettyClass(klass);
2630 return NULL;
2631}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002632 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002633 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002634 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002635 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002636 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002637 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002638 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002639 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002640 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002641 }
2642 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002643}
2644
Ian Rogersad25ac52011-10-04 19:13:33 -07002645const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2646 Class* declaring_class = referrer->GetDeclaringClass();
2647 DexCache* dex_cache = declaring_class->GetDexCache();
2648 const DexFile& dex_file = FindDexFile(dex_cache);
2649 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2650 return dex_file.GetShorty(method_id.proto_idx_);
2651}
2652
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002653void ClassLinker::DumpAllClasses(int flags) const {
2654 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2655 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2656 std::vector<Class*> all_classes;
2657 {
2658 MutexLock mu(lock_);
2659 typedef Table::const_iterator It; // TODO: C++0x auto
2660 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2661 all_classes.push_back(it->second);
2662 }
2663 }
2664
2665 for (size_t i = 0; i < all_classes.size(); ++i) {
2666 all_classes[i]->DumpClass(std::cerr, flags);
2667 }
2668}
2669
Elliott Hughese27955c2011-08-26 15:21:24 -07002670size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom16192862011-09-12 17:50:06 -07002671 MutexLock mu(lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002672 return classes_.size();
2673}
2674
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002675} // namespace art