blob: 7ca036122933582baed66631cb246b0b8e07e093 [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
Elliott Hughes362f9bc2011-10-17 18:56:41 -070034void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070035void 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 Hughes362f9bc2011-10-17 18:56:41 -070042void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070043void 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
Elliott Hughes362f9bc2011-10-17 18:56:41 -070050void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070051void 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();
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070061 std::ostringstream msg;
Elliott Hughescc5f9a92011-09-28 19:17:29 -070062 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 Hughes362f9bc2011-10-17 18:56:41 -0700119} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700120
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 Carlstrom47d237a2011-10-18 15:08:33 -0700200 : dex_lock_("ClassLinker dex lock"),
201 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700202 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700203 array_interfaces_(NULL),
204 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700205 init_done_(false),
206 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700207 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700208}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700209
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700210void CreateClassPath(const std::string& class_path,
211 std::vector<const DexFile*>& class_path_vector) {
212 std::vector<std::string> parsed;
213 Split(class_path, ':', parsed);
214 for (size_t i = 0; i < parsed.size(); ++i) {
215 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
216 if (dex_file != NULL) {
217 class_path_vector.push_back(dex_file);
218 }
219 }
220}
221
222void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700223 const Runtime* runtime = Runtime::Current();
224 if (runtime->IsVerboseStartup()) {
225 LOG(INFO) << "ClassLinker::InitFrom entering";
226 }
227
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700228 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700229
Elliott Hughes30646832011-10-13 16:59:46 -0700230 // java_lang_Class comes first, it's needed for AllocClass
231 Class* java_lang_Class = down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass)));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700232 CHECK(java_lang_Class != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700233 java_lang_Class->SetClass(java_lang_Class);
234 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700235 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700236
Elliott Hughes418d20f2011-09-22 14:00:39 -0700237 // Class[] is used for reflection support.
238 Class* class_array_class = AllocClass(java_lang_Class, sizeof(Class));
239 class_array_class->SetComponentType(java_lang_Class);
240
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700241 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom4873d462011-08-21 15:23:39 -0700242 Class* java_lang_Object = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700243 CHECK(java_lang_Object != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700244 // backfill Object as the super class of Class
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700245 java_lang_Class->SetSuperClass(java_lang_Object);
246 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700247
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700248 // Object[] next to hold class roots
Brian Carlstrom4873d462011-08-21 15:23:39 -0700249 Class* object_array_class = AllocClass(java_lang_Class, sizeof(Class));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700250 object_array_class->SetComponentType(java_lang_Object);
Brian Carlstroma0808032011-07-18 00:39:23 -0700251
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700252 // Setup the char class to be used for char[]
253 Class* char_class = AllocClass(java_lang_Class, sizeof(Class));
254
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700255 // Setup the char[] class to be used for String
Brian Carlstrom4873d462011-08-21 15:23:39 -0700256 Class* char_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700257 char_array_class->SetComponentType(char_class);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700258 CharArray::SetArrayClass(char_array_class);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700259
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700260 // Setup String
261 Class* java_lang_String = AllocClass(java_lang_Class, sizeof(StringClass));
262 String::SetClass(java_lang_String);
263 java_lang_String->SetObjectSize(sizeof(String));
264 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400265
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700266 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700267 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
268 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700269 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700270 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
271 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
272 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700273
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700274 // Create storage for root classes, save away our work so far (requires
275 // descriptors)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700276 class_roots_ = ObjectArray<Class>::Alloc(object_array_class, kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700277 CHECK(class_roots_ != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700278 SetClassRoot(kJavaLangClass, java_lang_Class);
279 SetClassRoot(kJavaLangObject, java_lang_Object);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700280 SetClassRoot(kClassArrayClass, class_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700281 SetClassRoot(kObjectArrayClass, object_array_class);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700282 SetClassRoot(kCharArrayClass, char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283 SetClassRoot(kJavaLangString, java_lang_String);
284
285 // Setup the primitive type classes.
286 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Class::kPrimBoolean));
287 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Class::kPrimByte));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Class::kPrimShort));
289 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Class::kPrimInt));
290 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Class::kPrimLong));
291 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Class::kPrimFloat));
292 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Class::kPrimDouble));
293 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Class::kPrimVoid));
294
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700296 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700297 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298
299 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
300 Class* int_array_class = AllocClass(java_lang_Class, sizeof(Class));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700301 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
303 IntArray::SetArrayClass(int_array_class);
Elliott Hughesc1674ed2011-08-25 18:09:09 -0700304 SetClassRoot(kIntArrayClass, int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700306 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700307
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700308 // setup boot_class_path_ and register class_path now that we can
309 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700310 std::vector<const DexFile*> boot_class_path_vector;
311 CreateClassPath(boot_class_path, boot_class_path_vector);
312 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
313 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700314 CHECK(dex_file != NULL);
315 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700316 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700317
Elliott Hughes80609252011-09-23 17:24:51 -0700318 // Constructor, Field, and Method are necessary so that FindClass can link members
319 Class* java_lang_reflect_Constructor = AllocClass(java_lang_Class, sizeof(MethodClass));
320 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
321 CHECK(java_lang_reflect_Constructor != NULL);
322 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
323 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor);
324 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
325
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326 Class* java_lang_reflect_Field = AllocClass(java_lang_Class, sizeof(FieldClass));
327 CHECK(java_lang_reflect_Field != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700328 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700329 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
330 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field);
331 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
332 Field::SetClass(java_lang_reflect_Field);
333
334 Class* java_lang_reflect_Method = AllocClass(java_lang_Class, sizeof(MethodClass));
Elliott Hughes80609252011-09-23 17:24:51 -0700335 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700336 CHECK(java_lang_reflect_Method != NULL);
337 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
338 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method);
339 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Elliott Hughes80609252011-09-23 17:24:51 -0700340 Method::SetClasses(java_lang_reflect_Constructor, java_lang_reflect_Method);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341
342 // now we can use FindSystemClass
343
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700344 // run char class through InitializePrimitiveClass to finish init
345 InitializePrimitiveClass(char_class, "C", Class::kPrimChar);
346 SetClassRoot(kPrimitiveChar, char_class); // needs descriptor
347
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700348 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349 java_lang_Object->SetStatus(Class::kStatusNotReady);
350 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
351 CHECK_EQ(java_lang_Object, Object_class);
352 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
353 java_lang_String->SetStatus(Class::kStatusNotReady);
354 Class* String_class = FindSystemClass("Ljava/lang/String;");
355 CHECK_EQ(java_lang_String, String_class);
356 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
357
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700358 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
360 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
361
362 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
363 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
364
365 Class* found_char_array_class = FindSystemClass("[C");
366 CHECK_EQ(char_array_class, found_char_array_class);
367
368 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
369 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
370
371 Class* found_int_array_class = FindSystemClass("[I");
372 CHECK_EQ(int_array_class, found_int_array_class);
373
374 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
375 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
376
377 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
378 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
379
380 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
381 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
382
Elliott Hughes418d20f2011-09-22 14:00:39 -0700383 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
384 CHECK_EQ(class_array_class, found_class_array_class);
385
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
387 CHECK_EQ(object_array_class, found_object_array_class);
388
389 // Setup the single, global copies of "interfaces" and "iftable"
390 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
391 CHECK(java_lang_Cloneable != NULL);
392 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
393 CHECK(java_io_Serializable != NULL);
394 CHECK(array_interfaces_ != NULL);
395 array_interfaces_->Set(0, java_lang_Cloneable);
396 array_interfaces_->Set(1, java_io_Serializable);
397 // We assume that Cloneable/Serializable don't have superinterfaces --
398 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700399 // supers as well.
400 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
401 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700402
Elliott Hughes418d20f2011-09-22 14:00:39 -0700403 // Sanity check Class[] and Object[]'s interfaces
404 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
405 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
407 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700408
Elliott Hughes80609252011-09-23 17:24:51 -0700409 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700410 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700411 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700412 CHECK_EQ(java_lang_Class, Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
Elliott Hughes80609252011-09-23 17:24:51 -0700414 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
415 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
416 CHECK_EQ(java_lang_reflect_Constructor, Constructor_class);
417
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700419 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700420 CHECK_EQ(java_lang_reflect_Field, Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700421
422 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700423 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700424 CHECK_EQ(java_lang_reflect_Method, Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700425
Ian Rogers466bb252011-10-14 03:29:56 -0700426 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
427
428 // Create java.lang.reflect.Proxy root
429 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
430 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
431
Brian Carlstrom1f870082011-08-23 16:02:11 -0700432 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700433 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
434 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700435 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436 java_lang_ref_FinalizerReference->SetAccessFlags(
437 java_lang_ref_FinalizerReference->GetAccessFlags() |
438 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700439 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440 java_lang_ref_PhantomReference->SetAccessFlags(
441 java_lang_ref_PhantomReference->GetAccessFlags() |
442 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700443 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444 java_lang_ref_SoftReference->SetAccessFlags(
445 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700446 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700447 java_lang_ref_WeakReference->SetAccessFlags(
448 java_lang_ref_WeakReference->GetAccessFlags() |
449 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700450
Brian Carlstromaded5f72011-10-07 17:15:04 -0700451 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700453 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
455
456 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
457 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
458 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
459
460 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
461 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
462 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
463 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
464
465 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700466 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
467 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700468 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700469
Brian Carlstroma663ea52011-08-19 23:33:41 -0700470 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700471
472 if (runtime->IsVerboseStartup()) {
473 LOG(INFO) << "ClassLinker::InitFrom exiting";
474 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700475}
476
477void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700478 const Runtime* runtime = Runtime::Current();
479 if (runtime->IsVerboseStartup()) {
480 LOG(INFO) << "ClassLinker::FinishInit entering";
481 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700482
483 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700484 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700485 // as the types of the field can't be resolved prior to the runtime being
486 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700487 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700488 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700489 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
490
Elliott Hughesadb460d2011-10-05 17:02:34 -0700491 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
492
Brian Carlstrom16192862011-09-12 17:50:06 -0700493 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
494 CHECK(pendingNext->GetName()->Equals("pendingNext"));
495 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
496
497 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
498 CHECK(queue->GetName()->Equals("queue"));
Elliott Hughesadb460d2011-10-05 17:02:34 -0700499 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue), java_lang_ref_ReferenceQueue);
Brian Carlstrom16192862011-09-12 17:50:06 -0700500
501 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
502 CHECK(queueNext->GetName()->Equals("queueNext"));
503 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
504
505 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
506 CHECK(referent->GetName()->Equals("referent"));
507 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
508
509 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
510 CHECK(zombie->GetName()->Equals("zombie"));
511 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
512
513 Heap::SetReferenceOffsets(referent->GetOffset(),
514 queue->GetOffset(),
515 queueNext->GetOffset(),
516 pendingNext->GetOffset(),
517 zombie->GetOffset());
518
Brian Carlstroma663ea52011-08-19 23:33:41 -0700519 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700520 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700521 ClassRoot class_root = static_cast<ClassRoot>(i);
522 Class* klass = GetClassRoot(class_root);
523 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700524 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700525 // note SetClassRoot does additional validation.
526 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700527 }
528
Elliott Hughes92f14b22011-10-06 12:29:54 -0700529 CHECK(array_iftable_ != NULL);
530 CHECK(array_interfaces_ != NULL);
531
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700532 // disable the slow paths in FindClass and CreatePrimitiveClass now
533 // that Object, Class, and Object[] are setup
534 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700535
536 if (runtime->IsVerboseStartup()) {
537 LOG(INFO) << "ClassLinker::FinishInit exiting";
538 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700539}
540
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700541void ClassLinker::RunRootClinits() {
542 Thread* self = Thread::Current();
543 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
544 Class* c = GetClassRoot(ClassRoot(i));
545 if (!c->IsArrayClass() && !c->IsPrimitive()) {
546 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700547 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700548 }
549 }
550}
551
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700552OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700553 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700554 const Runtime* runtime = Runtime::Current();
555 if (runtime->IsVerboseStartup()) {
556 LOG(INFO) << "ClassLinker::OpenOat entering";
557 }
558 const ImageHeader& image_header = space->GetImageHeader();
559 String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
560 std::string oat_filename;
561 oat_filename += runtime->GetHostPrefix();
562 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700563 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700564 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700565 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700566 return NULL;
567 }
568 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
569 uint32_t image_oat_checksum = image_header.GetOatChecksum();
570 if (oat_checksum != image_oat_checksum) {
571 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
572 << " to expected oat checksum " << std::hex << oat_checksum
573 << " in image";
574 return NULL;
575 }
576 oat_files_.push_back(oat_file);
577 if (runtime->IsVerboseStartup()) {
578 LOG(INFO) << "ClassLinker::OpenOat exiting";
579 }
580 return oat_file;
581}
582
Brian Carlstromaded5f72011-10-07 17:15:04 -0700583const OatFile* ClassLinker::FindOatFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700584 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700585 // TODO: check if dex_file matches an OatDexFile location and checksum
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700586 return FindOatFile(OatFile::DexFileToOatFilename(dex_file));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700587}
588
Brian Carlstromfad71432011-10-16 20:25:10 -0700589const OatFile* ClassLinker::FindOpenedOatFile(const std::string& location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700590 for (size_t i = 0; i < oat_files_.size(); i++) {
591 const OatFile* oat_file = oat_files_[i];
592 DCHECK(oat_file != NULL);
593 if (oat_file->GetLocation() == location) {
594 return oat_file;
595 }
596 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700597 return NULL;
598}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700599
Brian Carlstromfad71432011-10-16 20:25:10 -0700600const OatFile* ClassLinker::FindOatFile(const std::string& location) {
601 const OatFile* oat_file = FindOpenedOatFile(location);
602 if (oat_file != NULL) {
603 return oat_file;
604 }
605
606 oat_file = OatFile::Open(location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700607 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700608 if (location.empty() || location[0] != '/') {
609 LOG(ERROR) << "Failed to open oat file from " << location;
610 return NULL;
611 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700612
Brian Carlstroma9f19782011-10-13 00:14:47 -0700613 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700614 std::string cache_location = GetArtCacheOatFilenameOrDie(location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700615 oat_file = FindOpenedOatFile(cache_location);
616 if (oat_file != NULL) {
617 return oat_file;
618 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700619 oat_file = OatFile::Open(cache_location, "", NULL);
620 if (oat_file == NULL) {
621 LOG(ERROR) << "Failed to open oat file from " << location << " or " << cache_location << ".";
622 return NULL;
623 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700624 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700625
626 CHECK(oat_file != NULL) << location;
627 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700628 return oat_file;
629}
630
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700631void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700632 const Runtime* runtime = Runtime::Current();
633 if (runtime->IsVerboseStartup()) {
634 LOG(INFO) << "ClassLinker::InitFromImage entering";
635 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700636 CHECK(!init_done_);
637
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700638 const std::vector<Space*>& spaces = Heap::GetSpaces();
639 for (size_t i = 0; i < spaces.size(); i++) {
640 Space* space = spaces[i] ;
641 if (space->IsImageSpace()) {
642 OatFile* oat_file = OpenOat(space);
643 CHECK(oat_file != NULL) << "Failed to open oat file for image";
644 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
645 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
646
647 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
648 static_cast<uint32_t>(dex_caches->GetLength()));
649 for (int i = 0; i < dex_caches->GetLength(); i++) {
650 DexCache* dex_cache = dex_caches->Get(i);
651 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
652
653 std::string dex_filename;
654 dex_filename += runtime->GetHostPrefix();
655 dex_filename += dex_file_location;
656 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
657 if (dex_file == NULL) {
658 LOG(FATAL) << "Failed to open dex file " << dex_filename
659 << " referenced from oat file as " << dex_file_location;
660 }
661
Brian Carlstromaded5f72011-10-07 17:15:04 -0700662 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
663 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700664
Brian Carlstromdf143242011-10-10 18:05:34 -0700665 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700666 }
667 }
668 }
669
Brian Carlstroma663ea52011-08-19 23:33:41 -0700670 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
671 DCHECK(heap_bitmap != NULL);
672
Brian Carlstroma663ea52011-08-19 23:33:41 -0700673 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700674 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700675
676 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700677 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
678 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700679
Elliott Hughes92f14b22011-10-06 12:29:54 -0700680 // reinit array_interfaces_ and array_iftable_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700681 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
682 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700683 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
684 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700685
Brian Carlstroma663ea52011-08-19 23:33:41 -0700686 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700687 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700688 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700689 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
690 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
691 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
692 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
693 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
694 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
695 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
696 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700697 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700698 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700699
700 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700701
702 if (runtime->IsVerboseStartup()) {
703 LOG(INFO) << "ClassLinker::InitFromImage exiting";
704 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700705}
706
Brian Carlstrom78128a62011-09-15 17:21:19 -0700707void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700708 DCHECK(obj != NULL);
709 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700710 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700711
Brian Carlstromc74255f2011-09-11 22:47:39 -0700712 if (obj->IsString()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700713 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700714 return;
715 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700716 if (obj->IsClass()) {
717 // restore class to ClassLinker::classes_ table
718 Class* klass = obj->AsClass();
719 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
720 class_linker->InsertClass(descriptor, klass);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700721 return;
722 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700723}
724
725// Keep in sync with InitCallback. Anything we visit, we need to
726// reinit references to when reinitializing a ClassLinker from a
727// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700728void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
729 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700730
731 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700732 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700733 }
734
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700735 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700736 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700737 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700738 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700739 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700740 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700741 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700742
Elliott Hughes410c0c82011-09-01 17:58:25 -0700743 visitor(array_interfaces_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700744}
745
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700746ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700747 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700748 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700749 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700750 BooleanArray::ResetArrayClass();
751 ByteArray::ResetArrayClass();
752 CharArray::ResetArrayClass();
753 DoubleArray::ResetArrayClass();
754 FloatArray::ResetArrayClass();
755 IntArray::ResetArrayClass();
756 LongArray::ResetArrayClass();
757 ShortArray::ResetArrayClass();
758 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700759 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700760 STLDeleteElements(&boot_class_path_);
761 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700762}
763
764DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Elliott Hughes30646832011-10-13 16:59:46 -0700765 String* location = intern_table_->InternStrong(dex_file.GetLocation().c_str());
766 if (location == NULL) {
767 return NULL;
768 }
Brian Carlstrom83db7722011-08-26 17:32:56 -0700769 DexCache* dex_cache = down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray()));
Elliott Hughes30646832011-10-13 16:59:46 -0700770 if (dex_cache == NULL) {
771 return NULL;
772 }
773 // TODO: lots of missing null checks hidden in this call...
774 dex_cache->Init(location,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700775 AllocObjectArray<String>(dex_file.NumStringIds()),
Elliott Hughes418d20f2011-09-22 14:00:39 -0700776 AllocClassArray(dex_file.NumTypeIds()),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700777 AllocObjectArray<Method>(dex_file.NumMethodIds()),
Brian Carlstrom83db7722011-08-26 17:32:56 -0700778 AllocObjectArray<Field>(dex_file.NumFieldIds()),
Brian Carlstrom1caa2c22011-08-28 13:02:33 -0700779 AllocCodeAndDirectMethods(dex_file.NumMethodIds()),
780 AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700781 return dex_cache;
Brian Carlstroma0808032011-07-18 00:39:23 -0700782}
783
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700784CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
785 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700786}
787
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700788InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
789 DCHECK(interface->IsInterface());
790 ObjectArray<Object>* array = AllocObjectArray<Object>(InterfaceEntry::LengthAsArray());
791 InterfaceEntry* interface_entry = down_cast<InterfaceEntry*>(array);
792 interface_entry->SetInterface(interface);
793 return interface_entry;
794}
795
Brian Carlstrom4873d462011-08-21 15:23:39 -0700796Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
797 DCHECK_GE(class_size, sizeof(Class));
798 Class* klass = Heap::AllocObject(java_lang_Class, class_size)->AsClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700799 klass->SetPrimitiveType(Class::kPrimNot); // default to not being primitive
800 klass->SetClassSize(class_size);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700801 return klass;
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700802}
803
Brian Carlstrom4873d462011-08-21 15:23:39 -0700804Class* ClassLinker::AllocClass(size_t class_size) {
805 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700806}
807
Jesse Wilson35baaab2011-08-10 16:18:03 -0400808Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700809 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700810}
811
812Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700813 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700814}
815
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700816ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
817 return ObjectArray<StackTraceElement>::Alloc(
818 GetClassRoot(kJavaLangStackTraceElementArrayClass),
819 length);
820}
821
Brian Carlstromaded5f72011-10-07 17:15:04 -0700822Class* EnsureResolved(Class* klass) {
823 DCHECK(klass != NULL);
824 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700825 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700826 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700827 ObjectLock lock(klass);
828 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700829 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700830 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700831 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700832 return NULL;
833 }
834 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700835 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700836 lock.Wait();
837 }
838 }
839 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700840 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700841 return NULL;
842 }
843 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700844 CHECK(klass->IsResolved()) << PrettyClass(klass);
845 CHECK(!self->IsExceptionPending())
846 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
847 return klass;
848}
849
850Class* ClassLinker::FindClass(const std::string& descriptor,
851 const ClassLoader* class_loader) {
852 CHECK_NE(descriptor.size(), 0U);
853 Thread* self = Thread::Current();
854 DCHECK(self != NULL);
855 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
856 // Find the class in the loaded classes table.
857 Class* klass = LookupClass(descriptor, class_loader);
858 if (klass != NULL) {
859 return EnsureResolved(klass);
860 }
861 if (descriptor.size() == 1) {
862 // only the descriptors of primitive types should be 1 character long
863 return FindPrimitiveClass(descriptor[0]);
864 }
865 // Class is not yet loaded.
866 if (descriptor[0] == '[') {
867 return CreateArrayClass(descriptor, class_loader);
868 }
869 if (class_loader == NULL) {
870 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
871 if (pair.second == NULL) {
872 std::string name(PrintableString(descriptor));
873 ThrowNoClassDefFoundError("Class %s not found in boot class loader", name.c_str());
874 return NULL;
875 }
876 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
877 }
878
879 if (ClassLoader::UseCompileTimeClassPath()) {
880 const std::vector<const DexFile*>& class_path
881 = ClassLoader::GetCompileTimeClassPath(class_loader);
882 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
883 if (pair.second == NULL) {
884 return FindSystemClass(descriptor);
885 }
886 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
887 }
888
889 std::string class_name_string = DescriptorToDot(descriptor);
890 ScopedThreadStateChange(self, Thread::kNative);
891 JNIEnv* env = self->GetJniEnv();
Brian Carlstromdf143242011-10-10 18:05:34 -0700892 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
893 CHECK(c.get() != NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700894 // TODO: cache method?
Brian Carlstromdf143242011-10-10 18:05:34 -0700895 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700896 CHECK(mid != NULL);
Brian Carlstromdf143242011-10-10 18:05:34 -0700897 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -0700898 if (class_name_object.get() == NULL) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700899 return NULL;
900 }
Brian Carlstromdf143242011-10-10 18:05:34 -0700901 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
902 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
903 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700904}
905
906Class* ClassLinker::DefineClass(const std::string& descriptor,
907 const ClassLoader* class_loader,
908 const DexFile& dex_file,
909 const DexFile::ClassDef& dex_class_def) {
910 Class* klass;
911 // Load the class from the dex file.
912 if (!init_done_) {
913 // finish up init of hand crafted class_roots_
914 if (descriptor == "Ljava/lang/Object;") {
915 klass = GetClassRoot(kJavaLangObject);
916 } else if (descriptor == "Ljava/lang/Class;") {
917 klass = GetClassRoot(kJavaLangClass);
918 } else if (descriptor == "Ljava/lang/String;") {
919 klass = GetClassRoot(kJavaLangString);
920 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
921 klass = GetClassRoot(kJavaLangReflectConstructor);
922 } else if (descriptor == "Ljava/lang/reflect/Field;") {
923 klass = GetClassRoot(kJavaLangReflectField);
924 } else if (descriptor == "Ljava/lang/reflect/Method;") {
925 klass = GetClassRoot(kJavaLangReflectMethod);
926 } else {
927 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
928 }
929 } else {
930 klass = AllocClass(SizeOfClass(dex_file, dex_class_def));
931 }
932 klass->SetDexCache(FindDexCache(dex_file));
933 LoadClass(dex_file, dex_class_def, klass, class_loader);
934 // Check for a pending exception during load
935 Thread* self = Thread::Current();
936 if (self->IsExceptionPending()) {
937 return NULL;
938 }
939 ObjectLock lock(klass);
940 klass->SetClinitThreadId(self->GetTid());
941 // Add the newly loaded class to the loaded classes table.
942 bool success = InsertClass(descriptor, klass); // TODO: just return collision
943 if (!success) {
944 // We may fail to insert if we raced with another thread.
945 klass->SetClinitThreadId(0);
946 klass = LookupClass(descriptor, class_loader);
947 CHECK(klass != NULL);
948 return klass;
949 }
950 // Finish loading (if necessary) by finding parents
951 CHECK(!klass->IsLoaded());
952 if (!LoadSuperAndInterfaces(klass, dex_file)) {
953 // Loading failed.
954 CHECK(self->IsExceptionPending());
955 lock.NotifyAll();
956 return NULL;
957 }
958 CHECK(klass->IsLoaded());
959 // Link the class (if necessary)
960 CHECK(!klass->IsResolved());
961 if (!LinkClass(klass)) {
962 // Linking failed.
963 CHECK(self->IsExceptionPending());
964 lock.NotifyAll();
965 return NULL;
966 }
967 CHECK(klass->IsResolved());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700968 return klass;
969}
970
Brian Carlstrom4873d462011-08-21 15:23:39 -0700971// Precomputes size that will be needed for Class, matching LinkStaticFields
972size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
973 const DexFile::ClassDef& dex_class_def) {
974 const byte* class_data = dex_file.GetClassData(dex_class_def);
975 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
976 size_t num_static_fields = header.static_fields_size_;
977 size_t num_ref = 0;
978 size_t num_32 = 0;
979 size_t num_64 = 0;
980 if (num_static_fields != 0) {
981 uint32_t last_idx = 0;
982 for (size_t i = 0; i < num_static_fields; ++i) {
983 DexFile::Field dex_field;
984 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
985 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
986 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
987 char c = descriptor[0];
988 if (c == 'L' || c == '[') {
989 num_ref++;
990 } else if (c == 'J' || c == 'D') {
991 num_64++;
992 } else {
993 num_32++;
994 }
995 }
996 }
997
998 // start with generic class data
999 size_t size = sizeof(Class);
1000 // follow with reference fields which must be contiguous at start
1001 size += (num_ref * sizeof(uint32_t));
1002 // if there are 64-bit fields to add, make sure they are aligned
1003 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1004 if (num_32 != 0) {
1005 // use an available 32-bit field for padding
1006 num_32--;
1007 }
1008 size += sizeof(uint32_t); // either way, we are adding a word
1009 DCHECK_EQ(size, RoundUp(size, 8));
1010 }
1011 // tack on any 64-bit fields now that alignment is assured
1012 size += (num_64 * sizeof(uint64_t));
1013 // tack on any remaining 32-bit fields
1014 size += (num_32 * sizeof(uint32_t));
1015 return size;
1016}
1017
Brian Carlstrom92827a52011-10-10 15:50:01 -07001018void LinkCode(Method* method, const OatFile::OatClass* oat_class, uint32_t method_index) {
1019 // Every kind of method should at least get an invoke stub from the oat_method.
1020 // non-abstract methods also get their code pointers.
1021 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
1022 oat_method.LinkMethod(method);
1023
1024 if (method->IsAbstract()) {
1025 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1026 return;
1027 }
1028 if (method->IsNative()) {
1029 // unregistering restores the dlsym lookup stub
1030 method->UnregisterNative();
1031 return;
1032 }
1033}
1034
Brian Carlstromf615a612011-07-23 12:50:34 -07001035void ClassLinker::LoadClass(const DexFile& dex_file,
1036 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001037 Class* klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001038 const ClassLoader* class_loader) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001039 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001040 CHECK(klass->GetDexCache() != NULL);
1041 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001042 const byte* class_data = dex_file.GetClassData(dex_class_def);
1043 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001044
Brian Carlstromf615a612011-07-23 12:50:34 -07001045 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001046 CHECK(descriptor != NULL);
1047
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001048 klass->SetClass(GetClassRoot(kJavaLangClass));
1049 if (klass->GetDescriptor() != NULL) {
1050 DCHECK(klass->GetDescriptor()->Equals(descriptor));
1051 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001052 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001053 if (klass->GetDescriptor() == NULL) {
1054 return;
1055 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001056 }
1057 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001058 // Make sure that none of our runtime-only flags are set.
1059 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001060 klass->SetAccessFlags(access_flags);
1061 klass->SetClassLoader(class_loader);
1062 DCHECK(klass->GetPrimitiveType() == Class::kPrimNot);
1063 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001064
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001065 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001066
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001067 size_t num_static_fields = header.static_fields_size_;
1068 size_t num_instance_fields = header.instance_fields_size_;
1069 size_t num_direct_methods = header.direct_methods_size_;
1070 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001071
Jesse Wilson6384f642011-10-07 18:08:35 -04001072 const char* source_file = dex_file.dexGetSourceFile(dex_class_def);
1073 if (source_file != NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001074 String* source_file_string = intern_table_->InternStrong(source_file);
1075 if (source_file_string == NULL) {
1076 return;
1077 }
1078 klass->SetSourceFile(source_file_string);
Jesse Wilson6384f642011-10-07 18:08:35 -04001079 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001080
1081 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -07001082 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001083
1084 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001085 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001086 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001087 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001088 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001089 DexFile::Field dex_field;
1090 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001091 Field* sfield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001092 klass->SetStaticField(i, sfield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001093 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001094 }
1095 }
1096
1097 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001098 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001099 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001100 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001101 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001102 DexFile::Field dex_field;
1103 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Jesse Wilson35baaab2011-08-10 16:18:03 -04001104 Field* ifield = AllocField();
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001105 klass->SetInstanceField(i, ifield);
Brian Carlstromf615a612011-07-23 12:50:34 -07001106 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001107 }
1108 }
1109
Brian Carlstromaded5f72011-10-07 17:15:04 -07001110 UniquePtr<const OatFile::OatClass> oat_class;
1111 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
1112 const OatFile* oat_file = FindOatFile(dex_file);
1113 if (oat_file != NULL) {
1114 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1115 if (oat_dex_file != NULL) {
1116 uint32_t class_def_index;
1117 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1118 CHECK(found) << descriptor;
1119 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001120 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 }
1122 }
1123 }
1124 size_t method_index = 0;
1125
Brian Carlstrom934486c2011-07-12 23:42:50 -07001126 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001127 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001128 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001129 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001130 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001131 for (size_t i = 0; i < num_direct_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001132 DexFile::Method dex_method;
1133 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom92827a52011-10-10 15:50:01 -07001134 Method* method = AllocMethod();
1135 klass->SetDirectMethod(i, method);
1136 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001137 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001138 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001139 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001140 }
1141 }
1142
1143 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001144 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001145 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001146 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001147 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001148 for (size_t i = 0; i < num_virtual_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001149 DexFile::Method dex_method;
1150 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom92827a52011-10-10 15:50:01 -07001151 Method* method = AllocMethod();
1152 klass->SetVirtualMethod(i, method);
1153 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001154 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001155 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001156 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001157 }
1158 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001159}
1160
Brian Carlstromf615a612011-07-23 12:50:34 -07001161void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1162 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001163 Class* klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001164 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001165 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001166 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001167 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1168 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001169 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001170 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001171 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001172 }
1173 }
1174}
1175
Brian Carlstromf615a612011-07-23 12:50:34 -07001176void ClassLinker::LoadField(const DexFile& dex_file,
1177 const DexFile::Field& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001178 Class* klass,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001179 Field* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001180 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001181 dst->SetDeclaringClass(klass);
1182 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1183 dst->SetTypeIdx(field_id.type_idx_);
1184 dst->SetAccessFlags(src.access_flags_);
1185
1186 // In order to access primitive types using GetTypeDuringLinking we need to
1187 // ensure they are resolved into the dex cache
1188 const char* descriptor = dex_file.dexStringByTypeIdx(field_id.type_idx_);
1189 if (descriptor[1] == '\0') {
1190 // only the descriptors of primitive types should be 1 character long
1191 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass);
1192 DCHECK(resolved->IsPrimitive());
1193 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001194}
1195
Brian Carlstromf615a612011-07-23 12:50:34 -07001196void ClassLinker::LoadMethod(const DexFile& dex_file,
1197 const DexFile::Method& src,
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001198 Class* klass,
Brian Carlstrom1f870082011-08-23 16:02:11 -07001199 Method* dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001200 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001201 dst->SetDeclaringClass(klass);
Elliott Hughes20cde902011-10-04 17:37:27 -07001202
Elliott Hughes80609252011-09-23 17:24:51 -07001203 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Elliott Hughes30646832011-10-13 16:59:46 -07001204 if (method_name == NULL) {
1205 return;
1206 }
Elliott Hughes80609252011-09-23 17:24:51 -07001207 dst->SetName(method_name);
1208 if (method_name->Equals("<init>")) {
1209 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1210 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001211
1212 int32_t utf16_length;
1213 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Elliott Hughes30646832011-10-13 16:59:46 -07001214 String* signature_string = intern_table_->InternStrong(utf16_length, signature.c_str());
1215 if (signature_string == NULL) {
1216 return;
1217 }
1218 dst->SetSignature(signature_string);
Elliott Hughes20cde902011-10-04 17:37:27 -07001219
1220 if (method_name->Equals("finalize") && signature == "()V") {
1221 /*
1222 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1223 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1224 * exclude it here.
1225 *
1226 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1227 */
1228 if (klass->GetClassLoader() != NULL ||
1229 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1230 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1231 klass->SetFinalizable();
1232 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001233 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001234
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001235 dst->SetProtoIdx(method_id.proto_idx_);
1236 dst->SetCodeItemOffset(src.code_off_);
1237 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Elliott Hughes30646832011-10-13 16:59:46 -07001238 String* shorty_string = intern_table_->InternStrong(shorty);
1239 dst->SetShorty(shorty_string);
1240 if (shorty_string == NULL) {
1241 return;
1242 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001243 dst->SetAccessFlags(src.access_flags_);
1244 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001245
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001246 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1247 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1248 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1249 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1250 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1251 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001252
Brian Carlstrom934486c2011-07-12 23:42:50 -07001253 // TODO: check for finalize method
1254
Brian Carlstromf615a612011-07-23 12:50:34 -07001255 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001256 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001257 dst->SetNumRegisters(code_item->registers_size_);
1258 dst->SetNumIns(code_item->ins_size_);
1259 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001260 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001261 uint16_t num_args = Method::NumArgRegisters(shorty);
1262 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001263 ++num_args;
1264 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001265 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001266 // TODO: native methods
1267 }
1268}
1269
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001270void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstroma663ea52011-08-19 23:33:41 -07001271 AppendToBootClassPath(dex_file, AllocDexCache(dex_file));
1272}
1273
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001274void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001275 CHECK(dex_cache != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001276 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001277 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001278}
1279
Brian Carlstromaded5f72011-10-07 17:15:04 -07001280bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001281 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001282 for (size_t i = 0; i != dex_files_.size(); ++i) {
1283 if (dex_files_[i] == &dex_file) {
1284 return true;
1285 }
1286 }
1287 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001288}
1289
Brian Carlstromaded5f72011-10-07 17:15:04 -07001290bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001291 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001292 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001293}
1294
1295void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001296 dex_lock_.AssertHeld();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001297 CHECK(dex_cache != NULL) << dex_file.GetLocation();
1298 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001299 dex_files_.push_back(&dex_file);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001300 dex_caches_.push_back(dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001301}
1302
Brian Carlstromaded5f72011-10-07 17:15:04 -07001303void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001304 {
1305 MutexLock mu(dex_lock_);
1306 if (IsDexFileRegisteredLocked(dex_file)) {
1307 return;
1308 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001309 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001310 // Don't alloc while holding the lock, since allocation may need to
1311 // suspend all threads and another thread may need the dex_lock_ to
1312 // get to a suspend point.
1313 DexCache* dex_cache = AllocDexCache(dex_file);
1314 {
1315 MutexLock mu(dex_lock_);
1316 if (IsDexFileRegisteredLocked(dex_file)) {
1317 return;
1318 }
1319 RegisterDexFileLocked(dex_file, dex_cache);
1320 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001321}
1322
1323void ClassLinker::RegisterDexFile(const DexFile& dex_file, DexCache* dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001324 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001325 RegisterDexFileLocked(dex_file, dex_cache);
1326}
1327
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001328const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001329 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001330 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001331 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1332 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001333 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001334 }
1335 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001336 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001337 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001338}
1339
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001340DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001341 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001342 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001343 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001344 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001345 }
1346 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001347 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001348 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001349}
1350
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001351Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1352 const char* descriptor,
1353 Class::PrimitiveType type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001354 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001355 CHECK(primitive_class != NULL);
1356 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1357 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001358 CHECK(primitive_class->GetDescriptor() != NULL);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001359 primitive_class->SetPrimitiveType(type);
1360 primitive_class->SetStatus(Class::kStatusInitialized);
1361 bool success = InsertClass(descriptor, primitive_class);
1362 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1363 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001364}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001365
Brian Carlstrombe977852011-07-19 14:54:54 -07001366// Create an array class (i.e. the class object for the array, not the
1367// array itself). "descriptor" looks like "[C" or "[[[[B" or
1368// "[Ljava/lang/String;".
1369//
1370// If "descriptor" refers to an array of primitives, look up the
1371// primitive type's internally-generated class object.
1372//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001373// "class_loader" is the class loader of the class that's referring to
1374// us. It's used to ensure that we're looking for the element type in
1375// the right context. It does NOT become the class loader for the
1376// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001377//
1378// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001379Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001380 const ClassLoader* class_loader) {
1381 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001382
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001383 // Identify the underlying component type
1384 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001385 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001386 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001387 return NULL;
1388 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001389
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001390 // See if the component type is already loaded. Array classes are
1391 // always associated with the class loader of their underlying
1392 // element type -- an array of Strings goes with the loader for
1393 // java/lang/String -- so we need to look for it there. (The
1394 // caller should have checked for the existence of the class
1395 // before calling here, but they did so with *their* class loader,
1396 // not the component type's loader.)
1397 //
1398 // If we find it, the caller adds "loader" to the class' initiating
1399 // loader list, which should prevent us from going through this again.
1400 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001401 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001402 // are the same, because our caller (FindClass) just did the
1403 // lookup. (Even if we get this wrong we still have correct behavior,
1404 // because we effectively do this lookup again when we add the new
1405 // class to the hash table --- necessary because of possible races with
1406 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001407 if (class_loader != component_type->GetClassLoader()) {
1408 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001409 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001410 return new_class;
1411 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001412 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001413
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001414 // Fill out the fields in the Class.
1415 //
1416 // It is possible to execute some methods against arrays, because
1417 // all arrays are subclasses of java_lang_Object_, so we need to set
1418 // up a vtable. We can just point at the one in java_lang_Object_.
1419 //
1420 // Array classes are simple enough that we don't need to do a full
1421 // link step.
1422
1423 Class* new_class = NULL;
1424 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001425 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001426 if (descriptor == "[Ljava/lang/Class;") {
1427 new_class = GetClassRoot(kClassArrayClass);
1428 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001429 new_class = GetClassRoot(kObjectArrayClass);
1430 } else if (descriptor == "[C") {
1431 new_class = GetClassRoot(kCharArrayClass);
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001432 } else if (descriptor == "[I") {
1433 new_class = GetClassRoot(kIntArrayClass);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001434 }
1435 }
1436 if (new_class == NULL) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07001437 new_class = AllocClass(sizeof(Class));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001438 if (new_class == NULL) {
1439 return NULL;
1440 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001441 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001442 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001443 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001444 if (new_class->GetDescriptor() != NULL) {
1445 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1446 } else {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001447 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001448 if (new_class->GetDescriptor() == NULL) {
1449 return NULL;
1450 }
Brian Carlstrom693267a2011-09-06 09:25:34 -07001451 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001452 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001453 new_class->SetSuperClass(java_lang_Object);
1454 new_class->SetVTable(java_lang_Object->GetVTable());
1455 new_class->SetPrimitiveType(Class::kPrimNot);
1456 new_class->SetClassLoader(component_type->GetClassLoader());
1457 new_class->SetStatus(Class::kStatusInitialized);
1458 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001459 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001460
1461
1462 // All arrays have java/lang/Cloneable and java/io/Serializable as
1463 // interfaces. We need to set that up here, so that stuff like
1464 // "instanceof" works right.
1465 //
1466 // Note: The GC could run during the call to FindSystemClass,
1467 // so we need to make sure the class object is GC-valid while we're in
1468 // there. Do this by clearing the interface list so the GC will just
1469 // think that the entries are null.
1470
1471
1472 // Use the single, global copies of "interfaces" and "iftable"
1473 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001474 CHECK(array_interfaces_ != NULL);
1475 CHECK(array_iftable_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001476 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001477 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001478
1479 // Inherit access flags from the component type. Arrays can't be
1480 // used as a superclass or interface, so we want to add "final"
1481 // and remove "interface".
1482 //
1483 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001484 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001485 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001486 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1487 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001488
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001489 if (InsertClass(descriptor, new_class)) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001490 return new_class;
1491 }
1492 // Another thread must have loaded the class after we
1493 // started but before we finished. Abandon what we've
1494 // done.
1495 //
1496 // (Yes, this happens.)
1497
1498 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001499 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001500 DCHECK(other_class != NULL);
1501 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001502}
1503
1504Class* ClassLinker::FindPrimitiveClass(char type) {
Carl Shapiro565f5072011-07-10 13:39:43 -07001505 switch (type) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001506 case 'B':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001507 return GetClassRoot(kPrimitiveByte);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001508 case 'C':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001509 return GetClassRoot(kPrimitiveChar);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001510 case 'D':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001511 return GetClassRoot(kPrimitiveDouble);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001512 case 'F':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001513 return GetClassRoot(kPrimitiveFloat);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001514 case 'I':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001515 return GetClassRoot(kPrimitiveInt);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001516 case 'J':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001517 return GetClassRoot(kPrimitiveLong);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001518 case 'S':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001519 return GetClassRoot(kPrimitiveShort);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001520 case 'Z':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001521 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001522 case 'V':
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001523 return GetClassRoot(kPrimitiveVoid);
Carl Shapiro744ad052011-08-06 15:53:36 -07001524 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001525 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001526 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001527 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001528}
1529
Brian Carlstromaded5f72011-10-07 17:15:04 -07001530bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001531 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001532 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001533 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001534 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001535}
1536
Brian Carlstromaded5f72011-10-07 17:15:04 -07001537Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001538 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001539 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001540 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001541 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001542 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001543 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001544 return klass;
1545 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001546 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001547 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001548}
1549
jeffhao98eacac2011-09-14 16:11:53 -07001550void ClassLinker::VerifyClass(Class* klass) {
1551 if (klass->IsVerified()) {
1552 return;
1553 }
1554
1555 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001556 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001557
jeffhao5cfd6fb2011-09-27 13:54:29 -07001558 if (DexVerifier::VerifyClass(klass)) {
1559 klass->SetStatus(Class::kStatusVerified);
1560 } else {
1561 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001562 Thread* self = Thread::Current();
1563 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1564 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
1565 PrettyDescriptor(klass->GetDescriptor()).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001566 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001567 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001568 }
jeffhao98eacac2011-09-14 16:11:53 -07001569}
1570
Jesse Wilson95caa792011-10-12 18:14:17 -04001571Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers466bb252011-10-14 03:29:56 -07001572 ClassLoader* loader, ObjectArray<Method>* methods, ObjectArray<ObjectArray<Class> >* throws) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001573 Class* klass = AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass));
1574 CHECK(klass != NULL);
1575 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers466bb252011-10-14 03:29:56 -07001576 const char* descriptor = DotToDescriptor(name->ToModifiedUtf8().c_str()).c_str();;
1577 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Jesse Wilson95caa792011-10-12 18:14:17 -04001578 klass->SetAccessFlags(kAccPublic | kAccFinal);
1579 klass->SetClassLoader(loader);
Ian Rogers466bb252011-10-14 03:29:56 -07001580 klass->SetStatus(Class::kStatusInitialized); // no loading or initializing necessary
1581 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1582 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1583 klass->SetInterfaces(interfaces); // The interfaces are the array of interfaces specified
Jesse Wilson95caa792011-10-12 18:14:17 -04001584
Ian Rogers466bb252011-10-14 03:29:56 -07001585 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001586 klass->SetDirectMethods(AllocObjectArray<Method>(1));
1587 klass->SetDirectMethod(0, CreateProxyConstructor(klass));
1588
Ian Rogers466bb252011-10-14 03:29:56 -07001589 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001590 size_t num_virtual_methods = methods->GetLength();
1591 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1592 for (size_t i = 0; i < num_virtual_methods; ++i) {
1593 Method* prototype = methods->Get(i);
1594 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype, throws->Get(i)));
1595 }
Ian Rogers466bb252011-10-14 03:29:56 -07001596 // Link the virtual methods, creating vtable and iftables
Jesse Wilson95caa792011-10-12 18:14:17 -04001597 if (!LinkMethods(klass)) {
1598 DCHECK(Thread::Current()->IsExceptionPending());
1599 return NULL;
1600 }
Jesse Wilson95caa792011-10-12 18:14:17 -04001601 return klass;
1602}
1603
1604Method* ClassLinker::CreateProxyConstructor(Class* klass) {
Ian Rogers466bb252011-10-14 03:29:56 -07001605 // Create constructor for Proxy that must initialize h
1606 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1607 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
1608 CHECK_EQ(proxy_direct_methods->GetLength(), 12);
1609 Method* proxy_constructor = proxy_direct_methods->Get(2);
1610 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1611 // code_ too)
1612 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1613 // Make this constructor public and fix the class to be our Proxy version
1614 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Jesse Wilson95caa792011-10-12 18:14:17 -04001615 constructor->SetDeclaringClass(klass);
Ian Rogers466bb252011-10-14 03:29:56 -07001616 // Sanity checks
1617 CHECK(constructor->IsConstructor());
1618 CHECK(constructor->GetName()->Equals("<init>"));
1619 CHECK(constructor->GetSignature()->Equals("(Ljava/lang/reflect/InvocationHandler;)V"));
1620 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001621 return constructor;
1622}
1623
Ian Rogers466bb252011-10-14 03:29:56 -07001624Method* ClassLinker::CreateProxyMethod(Class* klass, Method* prototype,
1625 ObjectArray<Class>* throws) {
1626 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialise
1627 // as necessary
1628 Method* method = down_cast<Method*>(prototype->Clone());
1629
1630 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1631 // the intersection of throw exceptions as defined in Proxy
Jesse Wilson95caa792011-10-12 18:14:17 -04001632 method->SetDeclaringClass(klass);
Ian Rogers466bb252011-10-14 03:29:56 -07001633 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001634 method->SetExceptionTypes(throws);
1635
Ian Rogers466bb252011-10-14 03:29:56 -07001636 // At runtime the method looks like a reference and argument saving method, clone the code
1637 // related parameters from this method.
1638 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1639 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1640 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1641 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1642 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Jesse Wilson95caa792011-10-12 18:14:17 -04001643
Ian Rogers466bb252011-10-14 03:29:56 -07001644 // Basic sanity
1645 DCHECK(method->GetName()->Equals(prototype->GetName()));
1646 DCHECK(method->GetSignature()->Equals(prototype->GetSignature()));
1647 DCHECK(method->GetShorty()->Equals(prototype->GetShorty()));
1648
1649 // More complex sanity - via dex cache
1650 CHECK_EQ(method->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04001651
1652 return method;
1653}
1654
Brian Carlstrom25c33252011-09-18 15:58:35 -07001655bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001656 CHECK(klass->IsResolved() || klass->IsErroneous())
1657 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001658
Carl Shapirob5573532011-07-12 18:22:59 -07001659 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001660
Brian Carlstrom25c33252011-09-18 15:58:35 -07001661 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001662 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001663 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001664 ObjectLock lock(klass);
1665
Brian Carlstromd1422f82011-09-28 11:37:09 -07001666 if (klass->GetStatus() == Class::kStatusInitialized) {
1667 return true;
1668 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001669
Brian Carlstromd1422f82011-09-28 11:37:09 -07001670 if (klass->IsErroneous()) {
1671 ThrowEarlierClassFailure(klass);
1672 return false;
1673 }
1674
1675 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001676 VerifyClass(klass);
1677 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001678 return false;
1679 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001680 }
1681
Brian Carlstrom25c33252011-09-18 15:58:35 -07001682 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1683 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001684 // if the class has a <clinit> but we can't run it during compilation,
1685 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001686 return false;
1687 }
1688
Brian Carlstromd1422f82011-09-28 11:37:09 -07001689 // If the class is kStatusInitializing, either this thread is
1690 // initializing higher up the stack or another thread has beat us
1691 // to initializing and we need to wait. Either way, this
1692 // invocation of InitializeClass will not be responsible for
1693 // running <clinit> and will return.
1694 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001695 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001696 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001697 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001698 return true;
1699 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001700 // No. That's fine. Wait for another thread to finish initializing.
1701 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001702 }
1703
1704 if (!ValidateSuperClassDescriptors(klass)) {
1705 klass->SetStatus(Class::kStatusError);
1706 return false;
1707 }
1708
Brian Carlstromd1422f82011-09-28 11:37:09 -07001709 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001710
Elliott Hughesdcc24742011-09-07 14:02:44 -07001711 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001712 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001713 }
1714
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001715 uint64_t t0 = NanoTime();
1716
Brian Carlstrom25c33252011-09-18 15:58:35 -07001717 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001718 return false;
1719 }
1720
1721 InitializeStaticFields(klass);
1722
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001723 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001724 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001725 }
1726
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001727 uint64_t t1 = NanoTime();
1728
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001729 {
1730 ObjectLock lock(klass);
1731
1732 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001733 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001734 klass->SetStatus(Class::kStatusError);
1735 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001736 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1737 RuntimeStats* thread_stats = self->GetStats();
1738 ++global_stats->class_init_count;
1739 ++thread_stats->class_init_count;
1740 global_stats->class_init_time_ns += (t1 - t0);
1741 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001742 klass->SetStatus(Class::kStatusInitialized);
1743 }
1744 lock.NotifyAll();
1745 }
1746
1747 return true;
1748}
1749
Brian Carlstromd1422f82011-09-28 11:37:09 -07001750bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1751 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001752 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001753 lock.Wait();
1754
1755 // When we wake up, repeat the test for init-in-progress. If
1756 // there's an exception pending (only possible if
1757 // "interruptShouldThrow" was set), bail out.
1758 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001759 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001760 klass->SetStatus(Class::kStatusError);
1761 return false;
1762 }
1763 // Spurious wakeup? Go back to waiting.
1764 if (klass->GetStatus() == Class::kStatusInitializing) {
1765 continue;
1766 }
1767 if (klass->IsErroneous()) {
1768 // The caller wants an exception, but it was thrown in a
1769 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001770 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
1771 PrettyDescriptor(klass->GetDescriptor()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001772 return false;
1773 }
1774 if (klass->IsInitialized()) {
1775 return true;
1776 }
1777 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1778 }
1779 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1780}
1781
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001782bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1783 if (klass->IsInterface()) {
1784 return true;
1785 }
1786 // begin with the methods local to the superclass
1787 if (klass->HasSuperClass() &&
1788 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1789 const Class* super = klass->GetSuperClass();
1790 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001791 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001792 if (method != super->GetVirtualMethod(i) &&
1793 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001794 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1795
1796 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 -07001797 return false;
1798 }
1799 }
1800 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001801 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1802 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1803 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001804 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1805 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001806 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001807 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001808 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001809 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1810
1811 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 -07001812 return false;
1813 }
1814 }
1815 }
1816 }
1817 return true;
1818}
1819
1820bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001821 const Class* klass1,
1822 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001823 if (method->IsMiranda()) {
1824 return true;
1825 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001826 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001827 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001828 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001829 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001830 const char* descriptor = it->GetDescriptor();
1831 if (descriptor == NULL) {
1832 break;
1833 }
1834 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1835 // Found a non-primitive type.
1836 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1837 return false;
1838 }
1839 }
1840 }
1841 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001842 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001843 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001844 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001845 return false;
1846 }
1847 }
1848 return true;
1849}
1850
1851// Returns true if classes referenced by the descriptor are the
1852// same classes in klass1 as they are in klass2.
1853bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001854 const Class* klass1,
1855 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001856 CHECK(descriptor != NULL);
1857 CHECK(klass1 != NULL);
1858 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001859 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001860 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001861 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001862 // TODO: found2 == NULL
1863 // TODO: lookup found1 in initiating loader list
1864 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001865 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001866 if (found1 == found2) {
1867 return true;
1868 } else {
1869 return false;
1870 }
1871 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001872 return true;
1873}
1874
Brian Carlstrom25c33252011-09-18 15:58:35 -07001875bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001876 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001877 if (!klass->IsInterface() && klass->HasSuperClass()) {
1878 Class* super_class = klass->GetSuperClass();
1879 if (super_class->GetStatus() != Class::kStatusInitialized) {
1880 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001881 Thread* self = Thread::Current();
1882 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001883 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001884 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001885 // TODO: check for a pending exception
1886 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001887 if (!can_run_clinit) {
1888 // Don't set status to error when we can't run <clinit>.
1889 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1890 klass->SetStatus(Class::kStatusVerified);
1891 return false;
1892 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001893 klass->SetStatus(Class::kStatusError);
1894 klass->NotifyAll();
1895 return false;
1896 }
1897 }
1898 }
1899 return true;
1900}
1901
Brian Carlstrom25c33252011-09-18 15:58:35 -07001902bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001903 CHECK(c != NULL);
1904 if (c->IsInitialized()) {
1905 return true;
1906 }
1907
Elliott Hughes5f791332011-09-15 17:45:30 -07001908 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001909 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001910 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001911 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001912}
1913
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001914void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1915 Class* c, std::map<int, Field*>& field_map) {
1916 const ClassLoader* cl = c->GetClassLoader();
1917 const byte* class_data = dex_file.GetClassData(dex_class_def);
1918 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1919 uint32_t last_idx = 0;
1920 for (size_t i = 0; i < header.static_fields_size_; ++i) {
1921 DexFile::Field dex_field;
1922 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1923 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
1924 }
1925}
1926
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001927void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001928 size_t num_static_fields = klass->NumStaticFields();
1929 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001930 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001931 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001932 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07001933 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07001934 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001935 return;
1936 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001937 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001938 const DexFile& dex_file = FindDexFile(dex_cache);
1939 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07001940 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001941
1942 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
1943 std::map<int, Field*> field_map;
1944 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
1945
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001946 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001947 if (addr == NULL) {
1948 // All this class' static fields have default values.
1949 return;
1950 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001951 size_t array_size = DecodeUnsignedLeb128(&addr);
1952 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001953 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001954 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001955 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001956 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001957 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001958 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001959 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001960 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001961 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001962 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001963 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001964 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001965 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001966 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001967 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001968 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001969 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001970 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001971 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001972 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001973 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001974 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001975 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001976 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001977 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001978 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001979 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07001980 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07001981 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001982 break;
1983 }
Brian Carlstromf615a612011-07-23 12:50:34 -07001984 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001985 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001986 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07001987 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07001988 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001989 break;
1990 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07001991 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07001992 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001993 }
1994}
1995
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001996bool ClassLinker::LinkClass(Class* klass) {
1997 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001998 if (!LinkSuperClass(klass)) {
1999 return false;
2000 }
2001 if (!LinkMethods(klass)) {
2002 return false;
2003 }
2004 if (!LinkInstanceFields(klass)) {
2005 return false;
2006 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002007 if (!LinkStaticFields(klass)) {
2008 return false;
2009 }
2010 CreateReferenceInstanceOffsets(klass);
2011 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002012 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2013 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002014 return true;
2015}
2016
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002017bool ClassLinker::LoadSuperAndInterfaces(Class* klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002018 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
2019 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
2020 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002021 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002022 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002023 return false;
2024 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002025 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002026 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002027 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
2028 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Elliott Hughese555dc02011-09-25 10:46:35 -07002029 Class* interface = ResolveType(dex_file, idx, klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002030 klass->SetInterface(i, interface);
2031 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002032 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002033 return false;
2034 }
2035 // Verify
2036 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002037 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002038 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002039 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002040 PrettyDescriptor(interface->GetDescriptor()).c_str(),
2041 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002042 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002043 }
2044 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002045 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002046 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002047 return true;
2048}
2049
2050bool ClassLinker::LinkSuperClass(Class* klass) {
2051 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002052 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002053 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002054 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002055 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002056 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002057 return false;
2058 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002059 return true;
2060 }
2061 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002062 ThrowLinkageError("No superclass defined for class %s",
2063 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002064 return false;
2065 }
2066 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002067 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002068 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002069 "Superclass %s of %s is %s",
2070 PrettyDescriptor(super->GetDescriptor()).c_str(),
2071 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002072 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002073 return false;
2074 }
2075 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002076 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002077 "Superclass %s is inaccessible by %s",
2078 PrettyDescriptor(super->GetDescriptor()).c_str(),
2079 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002080 return false;
2081 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002082
2083 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2084 if (super->IsFinalizable()) {
2085 klass->SetFinalizable();
2086 }
2087
Elliott Hughes2da50362011-10-10 16:57:08 -07002088 // Inherit reference flags (if any) from the superclass.
2089 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2090 if (reference_flags != 0) {
2091 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2092 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002093 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002094 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002095 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
2096 PrettyDescriptor(klass->GetDescriptor()).c_str());
2097 return false;
2098 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002099
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002100#ifndef NDEBUG
2101 // Ensure super classes are fully resolved prior to resolving fields..
2102 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002103 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002104 super = super->GetSuperClass();
2105 }
2106#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002107 return true;
2108}
2109
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002110// Populate the class vtable and itable. Compute return type indices.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002111bool ClassLinker::LinkMethods(Class* klass) {
2112 if (klass->IsInterface()) {
2113 // No vtable.
2114 size_t count = klass->NumVirtualMethods();
2115 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002116 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002117 return false;
2118 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002119 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002120 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002121 }
jeffhaobdb76512011-09-07 11:43:16 -07002122 // Link interface method tables
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002123 return LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002124 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002125 // Link virtual and interface method tables
2126 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002127 }
2128 return true;
2129}
2130
2131bool ClassLinker::LinkVirtualMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002132 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002133 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2134 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002135 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002136 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002137 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002138 // See if any of our virtual methods override the superclass.
2139 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002140 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002141 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002142 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002143 Method* super_method = vtable->Get(j);
Ian Rogers466bb252011-10-14 03:29:56 -07002144 if (local_method->HasSameNameAndSignature(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002145 // Verify
2146 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002147 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002148 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2149 local_method->GetName()->ToModifiedUtf8().c_str(),
2150 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002151 return false;
2152 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002153 vtable->Set(j, local_method);
2154 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002155 break;
2156 }
2157 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002158 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002159 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002160 vtable->Set(actual_count, local_method);
2161 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002162 actual_count += 1;
2163 }
2164 }
2165 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002166 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002167 return false;
2168 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002169 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002170 CHECK_LE(actual_count, max_count);
2171 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002172 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002173 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002174 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002175 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002176 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002177 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002178 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002179 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002180 return false;
2181 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002182 ObjectArray<Method>* vtable = AllocObjectArray<Method>(num_virtual_methods);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002183 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002184 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2185 vtable->Set(i, virtual_method);
2186 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002187 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002188 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002189 }
2190 return true;
2191}
2192
2193bool ClassLinker::LinkInterfaceMethods(Class* klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194 size_t super_ifcount;
2195 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002196 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002197 } else {
2198 super_ifcount = 0;
2199 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002200 size_t ifcount = super_ifcount;
2201 ifcount += klass->NumInterfaces();
2202 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002203 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002204 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002205 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002206 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002207 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002208 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002209 return true;
2210 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002211 ObjectArray<InterfaceEntry>* iftable = AllocObjectArray<InterfaceEntry>(ifcount);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002212 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002213 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2214 for (size_t i = 0; i < super_ifcount; i++) {
2215 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2216 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002217 }
2218 // Flatten the interface inheritance hierarchy.
2219 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002220 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002221 Class* interface = klass->GetInterface(i);
2222 DCHECK(interface != NULL);
2223 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002224 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002225 "Class %s implements non-interface class %s",
2226 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2227 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002228 return false;
2229 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002230 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002231 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002232 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002233 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2234 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002235 }
2236 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002237 klass->SetIfTable(iftable);
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002238 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002239
2240 // If we're an interface, we don't need the vtable pointers, so we're done.
2241 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002242 return true;
2243 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002244 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002245 for (size_t i = 0; i < ifcount; ++i) {
2246 InterfaceEntry* interface_entry = iftable->Get(i);
2247 Class* interface = interface_entry->GetInterface();
2248 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2249 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002250 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002251 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2252 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002253 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002254 // For each method listed in the interface's method list, find the
2255 // matching method in our class's method list. We want to favor the
2256 // subclass over the superclass, which just requires walking
2257 // back from the end of the vtable. (This only matters if the
2258 // superclass defines a private method and this class redefines
2259 // it -- otherwise it would use the same vtable slot. In .dex files
2260 // those don't end up in the virtual method table, so it shouldn't
2261 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002262 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2263 Method* vtable_method = vtable->Get(k);
Ian Rogers466bb252011-10-14 03:29:56 -07002264 if (interface_method->HasSameNameAndSignature(vtable_method)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002265 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002266 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002267 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002268 return false;
2269 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002270 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002271 break;
2272 }
2273 }
2274 if (k < 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002275 Method* miranda_method = NULL;
Elliott Hughes4681c802011-09-25 18:04:37 -07002276 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers466bb252011-10-14 03:29:56 -07002277 if (miranda_list[mir]->HasSameNameAndSignature(interface_method)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002278 miranda_method = miranda_list[mir];
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002279 break;
2280 }
2281 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002282 if (miranda_method == NULL) {
2283 // point the interface table at a phantom slot
2284 miranda_method = AllocMethod();
2285 memcpy(miranda_method, interface_method, sizeof(Method));
2286 miranda_list.push_back(miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002287 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002288 method_array->Set(j, miranda_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002289 }
2290 }
2291 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002292 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002293 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002294 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002295 klass->SetVirtualMethods((old_method_count == 0)
2296 ? AllocObjectArray<Method>(new_method_count)
2297 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002298
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002299 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2300 CHECK(vtable != NULL);
2301 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002302 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002303 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002304 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002305 Method* method = miranda_list[i];
2306 method->SetDeclaringClass(klass);
2307 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2308 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2309 klass->SetVirtualMethod(old_method_count + i, method);
2310 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002311 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002312 // TODO: do not assign to the vtable field until it is fully constructed.
2313 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002314 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002315
2316 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2317 for (int i = 0; i < vtable->GetLength(); ++i) {
2318 CHECK(vtable->Get(i) != NULL);
2319 }
2320
2321// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2322
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002323 return true;
2324}
2325
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002326bool ClassLinker::LinkInstanceFields(Class* klass) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002327 CHECK(klass != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002328 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002329}
2330
2331bool ClassLinker::LinkStaticFields(Class* klass) {
2332 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002333 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002334 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002335 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002336 return success;
2337}
2338
Brian Carlstromdbc05252011-09-09 01:59:59 -07002339struct LinkFieldsComparator {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002340 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002341 // First come reference fields, then 64-bit, and finally 32-bit
2342 const Class* type1 = field1->GetTypeDuringLinking();
2343 const Class* type2 = field2->GetTypeDuringLinking();
2344 bool isPrimitive1 = type1 != NULL && type1->IsPrimitive();
2345 bool isPrimitive2 = type2 != NULL && type2->IsPrimitive();
2346 bool is64bit1 = isPrimitive1 && (type1->IsPrimitiveLong() || type1->IsPrimitiveDouble());
2347 bool is64bit2 = isPrimitive2 && (type2->IsPrimitiveLong() || type2->IsPrimitiveDouble());
2348 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2349 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2350 if (order1 != order2) {
2351 return order1 < order2;
2352 }
2353
2354 // same basic group? then sort by string.
2355 std::string name1 = field1->GetName()->ToModifiedUtf8();
2356 std::string name2 = field2->GetName()->ToModifiedUtf8();
2357 return name1 < name2;
2358 }
2359};
2360
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002361bool ClassLinker::LinkFields(Class* klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002362 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002363 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002364
2365 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002366 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002367
2368 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002369 size_t size;
2370 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002371 if (is_static) {
2372 size = klass->GetClassSize();
2373 field_offset = Class::FieldsOffset();
2374 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002375 Class* super_class = klass->GetSuperClass();
2376 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002377 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002378 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002379 }
2380 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002381 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002382
Brian Carlstromdbc05252011-09-09 01:59:59 -07002383 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002384
Brian Carlstromdbc05252011-09-09 01:59:59 -07002385 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002386 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002387 std::deque<Field*> grouped_and_sorted_fields;
2388 for (size_t i = 0; i < num_fields; i++) {
2389 grouped_and_sorted_fields.push_back(fields->Get(i));
2390 }
2391 std::sort(grouped_and_sorted_fields.begin(),
2392 grouped_and_sorted_fields.end(),
2393 LinkFieldsComparator());
2394
2395 // References should be at the front.
2396 size_t current_field = 0;
2397 size_t num_reference_fields = 0;
2398 for (; current_field < num_fields; current_field++) {
2399 Field* field = grouped_and_sorted_fields.front();
2400 const Class* type = field->GetTypeDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002401 // if a field's type at this point is NULL it isn't primitive
Brian Carlstromdbc05252011-09-09 01:59:59 -07002402 bool isPrimitive = type != NULL && type->IsPrimitive();
2403 if (isPrimitive) {
2404 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002405 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002406 grouped_and_sorted_fields.pop_front();
2407 num_reference_fields++;
2408 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002409 field->SetOffset(field_offset);
2410 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002411 }
2412
2413 // Now we want to pack all of the double-wide fields together. If
2414 // we're not aligned, though, we want to shuffle one 32-bit field
2415 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002416 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002417 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2418 Field* field = grouped_and_sorted_fields[i];
2419 const Class* type = field->GetTypeDuringLinking();
2420 CHECK(type != NULL); // should only be working on primitive types
2421 DCHECK(type->IsPrimitive());
2422 if (type->IsPrimitiveLong() || type->IsPrimitiveDouble()) {
2423 continue;
2424 }
2425 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002426 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002427 // drop the consumed field
2428 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2429 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002431 // whether we found a 32-bit field for padding or not, we advance
2432 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002433 }
2434
2435 // Alignment is good, shuffle any double-wide fields forward, and
2436 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002437 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002438 while (!grouped_and_sorted_fields.empty()) {
2439 Field* field = grouped_and_sorted_fields.front();
2440 grouped_and_sorted_fields.pop_front();
2441 const Class* type = field->GetTypeDuringLinking();
2442 CHECK(type != NULL); // should only be working on primitive types
2443 DCHECK(type->IsPrimitive());
2444 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002445 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002446 field_offset = MemberOffset(field_offset.Uint32Value() +
2447 ((type->IsPrimitiveLong() || type->IsPrimitiveDouble())
2448 ? sizeof(uint64_t)
2449 : sizeof(uint32_t)));
2450 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002451 }
2452
Elliott Hughesadb460d2011-10-05 17:02:34 -07002453 // 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 -07002454 if (!is_static && klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002455 // We know there are no non-reference fields in the Reference classes, and we know
2456 // that 'referent' is alphabetically last, so this is easy...
2457 CHECK_EQ(num_reference_fields, num_fields);
2458 CHECK(fields->Get(num_fields - 1)->GetName()->Equals("referent"));
2459 --num_reference_fields;
2460 }
2461
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002462#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002463 // Make sure that all reference fields appear before
2464 // non-reference fields, and all double-wide fields are aligned.
2465 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002466 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002467 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002468 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002469 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002470 << " class=" << PrettyClass(klass)
2471 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002472 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2473 }
2474 const Class* type = field->GetTypeDuringLinking();
Elliott Hughesadb460d2011-10-05 17:02:34 -07002475 bool is_primitive = (type != NULL && type->IsPrimitive());
2476 if (klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;") && field->GetName()->Equals("referent")) {
2477 is_primitive = true; // We lied above, so we have to expect a lie here.
2478 }
2479 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002480 if (!seen_non_ref) {
2481 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002482 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002483 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002484 } else {
2485 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002486 }
2487 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002488 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002489 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002490 }
2491#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002492 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002493 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002494 if (is_static) {
2495 klass->SetNumReferenceStaticFields(num_reference_fields);
2496 klass->SetClassSize(size);
2497 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002498 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002499 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002500 klass->SetObjectSize(size);
2501 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002502 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002503 return true;
2504}
2505
2506// Set the bitmap of reference offsets, refOffsets, from the ifields
2507// list.
Brian Carlstrom4873d462011-08-21 15:23:39 -07002508void ClassLinker::CreateReferenceInstanceOffsets(Class* klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002509 uint32_t reference_offsets = 0;
2510 Class* super_class = klass->GetSuperClass();
2511 if (super_class != NULL) {
2512 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002513 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002514 if (reference_offsets == CLASS_WALK_SUPER) {
2515 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002516 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002517 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002518 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002519 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002520}
2521
2522void ClassLinker::CreateReferenceStaticOffsets(Class* klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002523 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002524}
2525
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002526void ClassLinker::CreateReferenceOffsets(Class* klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002527 uint32_t reference_offsets) {
2528 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002529 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2530 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002531 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002532 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002533 // All of the fields that contain object references are guaranteed
2534 // to be at the beginning of the fields list.
2535 for (size_t i = 0; i < num_reference_fields; ++i) {
2536 // Note that byte_offset is the offset from the beginning of
2537 // object, not the offset into instance data
2538 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002539 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002540 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2541 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2542 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002543 CHECK_NE(new_bit, 0U);
2544 reference_offsets |= new_bit;
2545 } else {
2546 reference_offsets = CLASS_WALK_SUPER;
2547 break;
2548 }
2549 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002550 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002551 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002552 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002553 } else {
2554 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002555 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002556}
2557
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002558String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002559 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002560 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002561 if (resolved != NULL) {
2562 return resolved;
2563 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002564 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2565 int32_t utf16_length = dex_file.GetStringLength(string_id);
2566 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002567 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002568 dex_cache->SetResolvedString(string_idx, string);
2569 return string;
2570}
2571
2572Class* ClassLinker::ResolveType(const DexFile& dex_file,
2573 uint32_t type_idx,
2574 DexCache* dex_cache,
2575 const ClassLoader* class_loader) {
2576 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 if (resolved == NULL) {
2578 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002579 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002580 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002581 Class* check = resolved;
2582 while (check->IsArrayClass()) {
2583 check = check->GetComponentType();
2584 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002585 if (dex_cache != check->GetDexCache()) {
2586 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002587 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002588 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002589 resolved = NULL;
2590 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002591 }
2592 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002593 if (resolved != NULL) {
2594 dex_cache->SetResolvedType(type_idx, resolved);
2595 } else {
2596 DCHECK(Thread::Current()->IsExceptionPending());
2597 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002598 }
2599 return resolved;
2600}
2601
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002602Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2603 uint32_t method_idx,
2604 DexCache* dex_cache,
2605 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002606 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002607 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2608 if (resolved != NULL) {
2609 return resolved;
2610 }
2611 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2612 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2613 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002614 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002615 return NULL;
2616 }
2617
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002618 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002619 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002620 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002621 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002622 } else if (klass->IsInterface()) {
2623 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002624 } else {
2625 resolved = klass->FindVirtualMethod(name, signature);
2626 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002627 if (resolved != NULL) {
2628 dex_cache->SetResolvedMethod(method_idx, resolved);
2629 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002630 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002631 }
2632 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002633}
2634
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002635Field* ClassLinker::ResolveField(const DexFile& dex_file,
2636 uint32_t field_idx,
2637 DexCache* dex_cache,
2638 const ClassLoader* class_loader,
2639 bool is_static) {
2640 Field* resolved = dex_cache->GetResolvedField(field_idx);
2641 if (resolved != NULL) {
2642 return resolved;
2643 }
2644 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2645 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2646 if (klass == NULL) {
2647 return NULL;
2648 }
2649
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002650 const char* name = dex_file.dexStringById(field_id.name_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002651 Class* field_type = ResolveType(dex_file, field_id.type_idx_, dex_cache, class_loader);
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002652 if (field_type == NULL) {
2653 // TODO: LinkageError?
2654 UNIMPLEMENTED(WARNING) << "Failed to resolve type of field " << name
2655 << " in " << PrettyClass(klass);
2656 return NULL;
2657}
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002658 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002659 resolved = klass->FindStaticField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002660 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002661 resolved = klass->FindInstanceField(name, field_type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002662 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002663 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002664 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002665 } else {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002666 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002667 }
2668 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002669}
2670
Ian Rogersad25ac52011-10-04 19:13:33 -07002671const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2672 Class* declaring_class = referrer->GetDeclaringClass();
2673 DexCache* dex_cache = declaring_class->GetDexCache();
2674 const DexFile& dex_file = FindDexFile(dex_cache);
2675 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2676 return dex_file.GetShorty(method_id.proto_idx_);
2677}
2678
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002679void ClassLinker::DumpAllClasses(int flags) const {
2680 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2681 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2682 std::vector<Class*> all_classes;
2683 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002684 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002685 typedef Table::const_iterator It; // TODO: C++0x auto
2686 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2687 all_classes.push_back(it->second);
2688 }
2689 }
2690
2691 for (size_t i = 0; i < all_classes.size(); ++i) {
2692 all_classes[i]->DumpClass(std::cerr, flags);
2693 }
2694}
2695
Elliott Hughese27955c2011-08-26 15:21:24 -07002696size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002697 MutexLock mu(classes_lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002698 return classes_.size();
2699}
2700
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002701pid_t ClassLinker::GetClassesLockOwner() {
2702 return classes_lock_.GetOwner();
2703}
2704
2705pid_t ClassLinker::GetDexLockOwner() {
2706 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002707}
2708
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002709} // namespace art