blob: 04a368d81ad534a57160bef97b12244109dec43a [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"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080012#include "debugger.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070013#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070014#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070015#include "dex_verifier.h"
16#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070017#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070018#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070019#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070020#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070021#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070022#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080023#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070024#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070025#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070026#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070027#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070028#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070029#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070030#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070031#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070032#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070033
34namespace art {
35
Elliott Hughes4a2b4172011-09-20 17:08:25 -070036namespace {
37
Elliott Hughes362f9bc2011-10-17 18:56:41 -070038void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070039void ThrowNoClassDefFoundError(const char* fmt, ...) {
40 va_list args;
41 va_start(args, fmt);
42 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
43 va_end(args);
44}
45
Elliott Hughes362f9bc2011-10-17 18:56:41 -070046void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070047void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070048 va_list args;
49 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070050 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070051 va_end(args);
52}
53
Elliott Hughes362f9bc2011-10-17 18:56:41 -070054void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070055void ThrowLinkageError(const char* fmt, ...) {
56 va_list args;
57 va_start(args, fmt);
58 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
59 va_end(args);
60}
61
Ian Rogers9f1ab122011-12-12 08:52:43 -080062void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
63 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080064 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070065 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080066 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
67 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080068 std::string location(kh.GetLocation());
69 if (!location.empty()) {
70 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070071 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070072 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070073}
74
Ian Rogers9f1ab122011-12-12 08:52:43 -080075void ThrowNoSuchFieldError(bool is_static, Class* c, const StringPiece& type,
76 const StringPiece& name) {
77 ClassHelper kh(c);
78 std::ostringstream msg;
79 msg << "no " << (is_static ? "static": "instance") << " field " << name << " of type " << type
80 << " in class " << kh.GetDescriptor() << " or its superclasses";
81 std::string location(kh.GetLocation());
82 if (!location.empty()) {
83 msg << " (defined in " << location << ")";
84 }
85 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
86}
87
Elliott Hughes4a2b4172011-09-20 17:08:25 -070088void ThrowEarlierClassFailure(Class* c) {
89 /*
90 * The class failed to initialize on a previous attempt, so we want to throw
91 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
92 * failed in verification, in which case v2 5.4.1 says we need to re-throw
93 * the previous error.
94 */
95 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
96
97 if (c->GetVerifyErrorClass() != NULL) {
98 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080099 ClassHelper ve_ch(c->GetVerifyErrorClass());
100 std::string error_descriptor(ve_ch.GetDescriptor());
101 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700102 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800103 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700104 }
105}
106
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700107void WrapExceptionInInitializer() {
108 JNIEnv* env = Thread::Current()->GetJniEnv();
109
110 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
111 CHECK(cause.get() != NULL);
112
113 env->ExceptionClear();
114
115 // TODO: add java.lang.Error to JniConstants?
116 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
117 CHECK(error_class.get() != NULL);
118 if (env->IsInstanceOf(cause.get(), error_class.get())) {
119 // We only wrap non-Error exceptions; an Error can just be used as-is.
120 env->Throw(cause.get());
121 return;
122 }
123
124 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
125 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
126 CHECK(eiie_class.get() != NULL);
127
128 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
129 CHECK(mid != NULL);
130
131 ScopedLocalRef<jthrowable> eiie(env,
132 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
133 env->Throw(eiie.get());
134}
135
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700136} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700137
Elliott Hughes418d20f2011-09-22 14:00:39 -0700138const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700139 "Ljava/lang/Class;",
140 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700141 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700142 "[Ljava/lang/Object;",
143 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700144 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700145 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700146 "Ljava/lang/reflect/Field;",
147 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700148 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700149 "Ljava/lang/ClassLoader;",
150 "Ldalvik/system/BaseDexClassLoader;",
151 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700152 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700153 "Z",
154 "B",
155 "C",
156 "D",
157 "F",
158 "I",
159 "J",
160 "S",
161 "V",
162 "[Z",
163 "[B",
164 "[C",
165 "[D",
166 "[F",
167 "[I",
168 "[J",
169 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700170 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700171};
172
Elliott Hughes5f791332011-09-15 17:45:30 -0700173class ObjectLock {
174 public:
175 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
176 CHECK(object != NULL);
177 obj_->MonitorEnter(self_);
178 }
179
180 ~ObjectLock() {
181 obj_->MonitorExit(self_);
182 }
183
184 void Wait() {
185 return Monitor::Wait(self_, obj_, 0, 0, false);
186 }
187
188 void Notify() {
189 obj_->Notify();
190 }
191
192 void NotifyAll() {
193 obj_->NotifyAll();
194 }
195
196 private:
197 Thread* self_;
198 Object* obj_;
199 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
200};
201
Brian Carlstromae826982011-11-09 01:33:42 -0800202ClassLinker* ClassLinker::Create(bool verbose,
203 const std::string& boot_class_path,
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700204 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700205 CHECK_NE(boot_class_path.size(), 0U);
Brian Carlstromae826982011-11-09 01:33:42 -0800206 UniquePtr<ClassLinker> class_linker(new ClassLinker(verbose, intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700207 class_linker->Init(boot_class_path);
208 return class_linker.release();
209}
210
Brian Carlstromae826982011-11-09 01:33:42 -0800211ClassLinker* ClassLinker::Create(bool verbose, InternTable* intern_table) {
212 UniquePtr<ClassLinker> class_linker(new ClassLinker(verbose, intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700213 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700214 return class_linker.release();
215}
216
Brian Carlstromae826982011-11-09 01:33:42 -0800217ClassLinker::ClassLinker(bool verbose, InternTable* intern_table)
218 : verbose_(verbose),
219 dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700220 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700221 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700222 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700223 init_done_(false),
224 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700225 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700226}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700227
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700228void CreateClassPath(const std::string& class_path,
229 std::vector<const DexFile*>& class_path_vector) {
230 std::vector<std::string> parsed;
231 Split(class_path, ':', parsed);
232 for (size_t i = 0; i < parsed.size(); ++i) {
233 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700234 if (dex_file == NULL) {
235 LOG(WARNING) << "Failed to open dex file " << parsed[i];
236 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700237 class_path_vector.push_back(dex_file);
238 }
239 }
240}
241
242void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700243 const Runtime* runtime = Runtime::Current();
244 if (runtime->IsVerboseStartup()) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700245 LOG(INFO) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700246 }
247
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700248 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700249
Elliott Hughes30646832011-10-13 16:59:46 -0700250 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700251 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
252 CHECK(java_lang_Class.get() != NULL);
253 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700255 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700256
Elliott Hughes418d20f2011-09-22 14:00:39 -0700257 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700258 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
259 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700260
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700261 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700262 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
263 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700264 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700265 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700266 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700267
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700268 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700269 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
270 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700271
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700272 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700273 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700274
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700276 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
277 char_array_class->SetComponentType(char_class.get());
278 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700279
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700280 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700281 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
282 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283 java_lang_String->SetObjectSize(sizeof(String));
284 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400285
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700286 // Create storage for root classes, save away our work so far (requires
287 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700288 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700289 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700290 SetClassRoot(kJavaLangClass, java_lang_Class.get());
291 SetClassRoot(kJavaLangObject, java_lang_Object.get());
292 SetClassRoot(kClassArrayClass, class_array_class.get());
293 SetClassRoot(kObjectArrayClass, object_array_class.get());
294 SetClassRoot(kCharArrayClass, char_array_class.get());
295 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700296
297 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700298 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
299 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
300 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
301 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
302 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
303 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
304 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
305 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700307 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700308 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700309
310 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700311 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700312 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700313 IntArray::SetArrayClass(int_array_class.get());
314 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700316 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700317
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700318 // setup boot_class_path_ and register class_path now that we can
319 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700320 std::vector<const DexFile*> boot_class_path_vector;
321 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700322 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700323 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
324 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700325 CHECK(dex_file != NULL);
326 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700327 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700328
Elliott Hughes80609252011-09-23 17:24:51 -0700329 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700332 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700334 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
335
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700336 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
337 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700339 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700340 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700341 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700343 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700344 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700346 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700347 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349
350 // now we can use FindSystemClass
351
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700352 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700353 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700354 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700355
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700356 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 java_lang_Object->SetStatus(Class::kStatusNotReady);
358 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700359 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700360 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
361 java_lang_String->SetStatus(Class::kStatusNotReady);
362 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700363 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
365
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700366 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700367 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
368 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
369
370 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
371 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
372
373 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700374 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700375
376 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
377 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
378
379 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700380 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381
382 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
383 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
384
385 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
386 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
387
388 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
389 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
390
Elliott Hughes418d20f2011-09-22 14:00:39 -0700391 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700392 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700393
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700394 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700395 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700396
397 // Setup the single, global copies of "interfaces" and "iftable"
398 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
399 CHECK(java_lang_Cloneable != NULL);
400 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
401 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700402 // We assume that Cloneable/Serializable don't have superinterfaces --
403 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700404 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800405 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
406 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407
Elliott Hughes418d20f2011-09-22 14:00:39 -0700408 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800409 ClassHelper kh(class_array_class.get(), this);
410 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
411 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
412 kh.ChangeClass(object_array_class.get());
413 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
414 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700415 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700416 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700417 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700418 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419
Elliott Hughes80609252011-09-23 17:24:51 -0700420 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
421 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700422 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700423
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700424 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700425 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700426 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700427
428 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700429 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700430 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700431
Ian Rogers466bb252011-10-14 03:29:56 -0700432 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
433
434 // Create java.lang.reflect.Proxy root
435 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
436 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
437
Brian Carlstrom1f870082011-08-23 16:02:11 -0700438 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700439 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
440 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700441 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700442 java_lang_ref_FinalizerReference->SetAccessFlags(
443 java_lang_ref_FinalizerReference->GetAccessFlags() |
444 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700445 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700446 java_lang_ref_PhantomReference->SetAccessFlags(
447 java_lang_ref_PhantomReference->GetAccessFlags() |
448 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700449 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700450 java_lang_ref_SoftReference->SetAccessFlags(
451 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700452 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700453 java_lang_ref_WeakReference->SetAccessFlags(
454 java_lang_ref_WeakReference->GetAccessFlags() |
455 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700456
Brian Carlstromaded5f72011-10-07 17:15:04 -0700457 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700459 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700460 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
461
462 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
463 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
464 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
465
466 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
467 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
468 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
469 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
470
471 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700472 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
473 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700474 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700475
Brian Carlstroma663ea52011-08-19 23:33:41 -0700476 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700477
478 if (runtime->IsVerboseStartup()) {
479 LOG(INFO) << "ClassLinker::InitFrom exiting";
480 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700481}
482
483void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700484 const Runtime* runtime = Runtime::Current();
485 if (runtime->IsVerboseStartup()) {
486 LOG(INFO) << "ClassLinker::FinishInit entering";
487 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700488
489 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700490 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700491 // as the types of the field can't be resolved prior to the runtime being
492 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700493 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700494 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700495 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
496
Elliott Hughesadb460d2011-10-05 17:02:34 -0700497 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
498
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800499 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
500
Brian Carlstrom16192862011-09-12 17:50:06 -0700501 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800502 FieldHelper fh(pendingNext, this);
503 CHECK_STREQ(fh.GetName(), "pendingNext");
504 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
505 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700506
507 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800508 fh.ChangeField(queue);
509 CHECK_STREQ(fh.GetName(), "queue");
510 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
511 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700512
513 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800514 fh.ChangeField(queueNext);
515 CHECK_STREQ(fh.GetName(), "queueNext");
516 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
517 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700518
519 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800520 fh.ChangeField(referent);
521 CHECK_STREQ(fh.GetName(), "referent");
522 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
523 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700524
525 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800526 fh.ChangeField(zombie);
527 CHECK_STREQ(fh.GetName(), "zombie");
528 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
529 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700530
531 Heap::SetReferenceOffsets(referent->GetOffset(),
532 queue->GetOffset(),
533 queueNext->GetOffset(),
534 pendingNext->GetOffset(),
535 zombie->GetOffset());
536
Brian Carlstroma663ea52011-08-19 23:33:41 -0700537 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700538 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700539 ClassRoot class_root = static_cast<ClassRoot>(i);
540 Class* klass = GetClassRoot(class_root);
541 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700542 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700543 // note SetClassRoot does additional validation.
544 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700545 }
546
Elliott Hughes92f14b22011-10-06 12:29:54 -0700547 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700548
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700549 // disable the slow paths in FindClass and CreatePrimitiveClass now
550 // that Object, Class, and Object[] are setup
551 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700552
553 if (runtime->IsVerboseStartup()) {
554 LOG(INFO) << "ClassLinker::FinishInit exiting";
555 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700556}
557
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700558void ClassLinker::RunRootClinits() {
559 Thread* self = Thread::Current();
560 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
561 Class* c = GetClassRoot(ClassRoot(i));
562 if (!c->IsArrayClass() && !c->IsPrimitive()) {
563 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700564 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700565 }
566 }
567}
568
jeffhao262bf462011-10-20 18:36:32 -0700569const OatFile* ClassLinker::GenerateOatFile(const std::string& filename) {
570 std::string oat_filename(GetArtCacheFilenameOrDie(OatFile::DexFilenameToOatFilename(filename)));
571
572 // fork and exec dex2oat
573 pid_t pid = fork();
574 if (pid == 0) {
575 std::string boot_image_option("--boot-image=");
576 boot_image_option += Heap::GetSpaces()[0]->GetImageFilename();
577
578 std::string dex_file_option("--dex-file=");
579 dex_file_option += filename;
580
581 std::string oat_file_option("--oat=");
582 oat_file_option += oat_filename;
583
Elliott Hughes234da572011-11-03 22:13:06 -0700584 std::string dex2oat("/system/bin/dex2oat");
585#ifndef NDEBUG
586 dex2oat += 'd';
587#endif
588
589 execl(dex2oat.c_str(), dex2oat.c_str(),
jeffhao5d840402011-10-24 17:09:45 -0700590 "--runtime-arg", "-Xms64m",
591 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500592 "--runtime-arg", "-classpath",
593 "--runtime-arg", Runtime::Current()->GetClassPath().c_str(),
jeffhao262bf462011-10-20 18:36:32 -0700594 boot_image_option.c_str(),
595 dex_file_option.c_str(),
596 oat_file_option.c_str(),
597 NULL);
598
599 PLOG(FATAL) << "execl(dex2oatd) failed";
600 return NULL;
601 } else {
602 // wait for dex2oat to finish
603 int status;
604 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
605 if (got_pid != pid) {
606 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
607 return NULL;
608 }
609 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
610 LOG(ERROR) << "dex2oatd failed with dex-file=" << filename;
611 return NULL;
612 }
613 }
614 return OatFile::Open(oat_filename, "", NULL);
615}
616
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700617OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700618 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700619 const Runtime* runtime = Runtime::Current();
620 if (runtime->IsVerboseStartup()) {
621 LOG(INFO) << "ClassLinker::OpenOat entering";
622 }
623 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800624 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
625 // check the down cast
626 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700627 std::string oat_filename;
628 oat_filename += runtime->GetHostPrefix();
629 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700630 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700631 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700632 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700633 return NULL;
634 }
635 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
636 uint32_t image_oat_checksum = image_header.GetOatChecksum();
637 if (oat_checksum != image_oat_checksum) {
638 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
639 << " to expected oat checksum " << std::hex << oat_checksum
640 << " in image";
641 return NULL;
642 }
643 oat_files_.push_back(oat_file);
644 if (runtime->IsVerboseStartup()) {
645 LOG(INFO) << "ClassLinker::OpenOat exiting";
646 }
647 return oat_file;
648}
649
Brian Carlstromae826982011-11-09 01:33:42 -0800650const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
651 for (size_t i = 0; i < oat_files_.size(); i++) {
652 const OatFile* oat_file = oat_files_[i];
653 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800654 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800655 return oat_file;
656 }
657 }
658 return NULL;
659}
660
661const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700662 MutexLock mu(dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800663 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
664 if (oat_file != NULL) {
665 return oat_file;
666 }
667
668 oat_file = FindOatFileFromOatLocation(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
jeffhao262bf462011-10-20 18:36:32 -0700669 if (oat_file != NULL) {
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700670 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
671 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
672 return oat_file;
673 }
674 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
675 << " is older than " << dex_file.GetLocation() << " --- regenerating";
Elliott Hughes234da572011-11-03 22:13:06 -0700676 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
677 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
678 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700679 // Fall through...
jeffhao262bf462011-10-20 18:36:32 -0700680 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700681 // Generate oat file if it wasn't found or was obsolete.
jeffhao262bf462011-10-20 18:36:32 -0700682 oat_file = GenerateOatFile(dex_file.GetLocation());
683 if (oat_file == NULL) {
684 LOG(ERROR) << "Failed to generate oat file from dex file " << dex_file.GetLocation();
685 return NULL;
686 }
687 oat_files_.push_back(oat_file);
688 return oat_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700689}
690
Brian Carlstromae826982011-11-09 01:33:42 -0800691const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700692 for (size_t i = 0; i < oat_files_.size(); i++) {
693 const OatFile* oat_file = oat_files_[i];
694 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800695 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700696 return oat_file;
697 }
698 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700699 return NULL;
700}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700701
Brian Carlstromae826982011-11-09 01:33:42 -0800702const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
703 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700704 if (oat_file != NULL) {
705 return oat_file;
706 }
707
Brian Carlstromae826982011-11-09 01:33:42 -0800708 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700709 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800710 if (oat_location.empty() || oat_location[0] != '/') {
711 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700712 return NULL;
713 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700714
Brian Carlstroma9f19782011-10-13 00:14:47 -0700715 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Brian Carlstromae826982011-11-09 01:33:42 -0800716 std::string cache_location = GetArtCacheFilenameOrDie(oat_location);
717 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700718 if (oat_file != NULL) {
719 return oat_file;
720 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700721 oat_file = OatFile::Open(cache_location, "", NULL);
722 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800723 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700724 return NULL;
725 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700726 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700727
Brian Carlstromae826982011-11-09 01:33:42 -0800728 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromfad71432011-10-16 20:25:10 -0700729 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700730 return oat_file;
731}
732
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700733void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700734 const Runtime* runtime = Runtime::Current();
735 if (runtime->IsVerboseStartup()) {
736 LOG(INFO) << "ClassLinker::InitFromImage entering";
737 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700738 CHECK(!init_done_);
739
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700740 const std::vector<Space*>& spaces = Heap::GetSpaces();
741 for (size_t i = 0; i < spaces.size(); i++) {
742 Space* space = spaces[i] ;
743 if (space->IsImageSpace()) {
744 OatFile* oat_file = OpenOat(space);
745 CHECK(oat_file != NULL) << "Failed to open oat file for image";
746 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
747 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
748
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800749 if (i == 0) {
750 // Special case of setting up the String class early so that we can test arbitrary objects
751 // as being Strings or not
752 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
753 ->AsObjectArray<Class>()->Get(kJavaLangString);
754 String::SetClass(java_lang_String);
755 }
756
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700757 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
758 static_cast<uint32_t>(dex_caches->GetLength()));
759 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700760 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700761 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
762
763 std::string dex_filename;
764 dex_filename += runtime->GetHostPrefix();
765 dex_filename += dex_file_location;
766 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
767 if (dex_file == NULL) {
768 LOG(FATAL) << "Failed to open dex file " << dex_filename
769 << " referenced from oat file as " << dex_file_location;
770 }
771
Brian Carlstromaded5f72011-10-07 17:15:04 -0700772 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
773 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700774
Brian Carlstromdf143242011-10-10 18:05:34 -0700775 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700776 }
777 }
778 }
779
Brian Carlstroma663ea52011-08-19 23:33:41 -0700780 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
781 DCHECK(heap_bitmap != NULL);
782
Brian Carlstroma663ea52011-08-19 23:33:41 -0700783 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700784 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700785
786 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700787 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
788 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700789
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800790 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700791 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
792 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800793 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700794 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700795 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700796 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
797 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
798 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
799 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
800 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
801 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
802 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
803 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700804 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700805 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700806
807 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700808
809 if (runtime->IsVerboseStartup()) {
810 LOG(INFO) << "ClassLinker::InitFromImage exiting";
811 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700812}
813
Brian Carlstrom78128a62011-09-15 17:21:19 -0700814void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700815 DCHECK(obj != NULL);
816 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700817 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700818
Elliott Hughesdbb40792011-11-18 17:05:22 -0800819 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700820 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700821 return;
822 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700823 if (obj->IsClass()) {
824 // restore class to ClassLinker::classes_ table
825 Class* klass = obj->AsClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800826 std::string descriptor(ClassHelper(klass, class_linker).GetDescriptor());
Ian Rogers5d76c432011-10-31 21:42:49 -0700827 bool success = class_linker->InsertClass(descriptor, klass, true);
828 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700829 return;
830 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700831}
832
833// Keep in sync with InitCallback. Anything we visit, we need to
834// reinit references to when reinitializing a ClassLinker from a
835// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700836void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
837 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700838
839 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700840 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700841 }
842
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700843 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700844 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700845 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700846 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700847 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700848 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700849 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700850 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700851
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700852 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700853}
854
Elliott Hughesa2155262011-11-16 16:26:58 -0800855void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
856 MutexLock mu(classes_lock_);
857 typedef Table::const_iterator It; // TODO: C++0x auto
858 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
859 if (!visitor(it->second, arg)) {
860 return;
861 }
862 }
863 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
864 if (!visitor(it->second, arg)) {
865 return;
866 }
867 }
868}
869
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700870ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700871 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700872 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700873 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700874 BooleanArray::ResetArrayClass();
875 ByteArray::ResetArrayClass();
876 CharArray::ResetArrayClass();
877 DoubleArray::ResetArrayClass();
878 FloatArray::ResetArrayClass();
879 IntArray::ResetArrayClass();
880 LongArray::ResetArrayClass();
881 ShortArray::ResetArrayClass();
882 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700883 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700884 STLDeleteElements(&boot_class_path_);
885 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700886}
887
888DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700889 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
890 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700891 return NULL;
892 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700893 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
894 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700895 return NULL;
896 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700897 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
898 if (strings.get() == NULL) {
899 return NULL;
900 }
901 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
902 if (types.get() == NULL) {
903 return NULL;
904 }
905 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
906 if (methods.get() == NULL) {
907 return NULL;
908 }
909 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
910 if (fields.get() == NULL) {
911 return NULL;
912 }
913 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
914 if (code_and_direct_methods.get() == NULL) {
915 return NULL;
916 }
917 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
918 if (initialized_static_storage.get() == NULL) {
919 return NULL;
920 }
921
922 dex_cache->Init(location.get(),
923 strings.get(),
924 types.get(),
925 methods.get(),
926 fields.get(),
927 code_and_direct_methods.get(),
928 initialized_static_storage.get());
929 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700930}
931
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700932CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
933 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700934}
935
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700936InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
937 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700938 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
939 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700940 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700941 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700942}
943
Brian Carlstrom4873d462011-08-21 15:23:39 -0700944Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
945 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700946 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700947 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700948 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700949 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700950}
951
Brian Carlstrom4873d462011-08-21 15:23:39 -0700952Class* ClassLinker::AllocClass(size_t class_size) {
953 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700954}
955
Jesse Wilson35baaab2011-08-10 16:18:03 -0400956Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700957 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700958}
959
960Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700961 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700962}
963
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700964ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
965 return ObjectArray<StackTraceElement>::Alloc(
966 GetClassRoot(kJavaLangStackTraceElementArrayClass),
967 length);
968}
969
Brian Carlstromaded5f72011-10-07 17:15:04 -0700970Class* EnsureResolved(Class* klass) {
971 DCHECK(klass != NULL);
972 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700973 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700974 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700975 ObjectLock lock(klass);
976 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700977 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700978 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800979 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700980 return NULL;
981 }
982 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700983 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700984 lock.Wait();
985 }
986 }
987 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700988 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700989 return NULL;
990 }
991 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700992 CHECK(klass->IsResolved()) << PrettyClass(klass);
993 CHECK(!self->IsExceptionPending())
994 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
995 return klass;
996}
997
998Class* ClassLinker::FindClass(const std::string& descriptor,
999 const ClassLoader* class_loader) {
1000 CHECK_NE(descriptor.size(), 0U);
1001 Thread* self = Thread::Current();
1002 DCHECK(self != NULL);
1003 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001004 if (descriptor.size() == 1) {
1005 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1006 // for primitive classes that aren't backed by dex files.
1007 return FindPrimitiveClass(descriptor[0]);
1008 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001009 // Find the class in the loaded classes table.
1010 Class* klass = LookupClass(descriptor, class_loader);
1011 if (klass != NULL) {
1012 return EnsureResolved(klass);
1013 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001014 // Class is not yet loaded.
1015 if (descriptor[0] == '[') {
1016 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001017
Jesse Wilson47daf872011-11-23 11:42:45 -05001018 } else if (class_loader == NULL) {
1019 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1020 if (pair.second != NULL) {
1021 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1022 }
1023
1024 } else if (ClassLoader::UseCompileTimeClassPath()) {
1025 // first try the boot class path
1026 Class* system_class = FindSystemClass(descriptor);
1027 if (system_class != NULL) {
1028 return system_class;
1029 }
1030 CHECK(self->IsExceptionPending());
1031 self->ClearException();
1032
1033 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001034 const std::vector<const DexFile*>& class_path
1035 = ClassLoader::GetCompileTimeClassPath(class_loader);
1036 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001037 if (pair.second != NULL) {
1038 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001039 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001040
1041 } else {
1042 std::string class_name_string = DescriptorToDot(descriptor);
1043 ScopedThreadStateChange(self, Thread::kNative);
1044 JNIEnv* env = self->GetJniEnv();
1045 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1046 CHECK(c.get() != NULL);
1047 // TODO: cache method?
1048 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1049 CHECK(mid != NULL);
1050 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1051 if (class_name_object.get() == NULL) {
1052 return NULL;
1053 }
1054 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1055 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
1056 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001057 }
1058
Jesse Wilson47daf872011-11-23 11:42:45 -05001059 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
1060 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001061}
1062
1063Class* ClassLinker::DefineClass(const std::string& descriptor,
1064 const ClassLoader* class_loader,
1065 const DexFile& dex_file,
1066 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001067 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001068 // Load the class from the dex file.
1069 if (!init_done_) {
1070 // finish up init of hand crafted class_roots_
1071 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001072 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001073 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001074 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001075 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001076 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001077 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001078 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001079 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001080 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001081 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001082 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001083 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001084 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001085 }
1086 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001087 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001088 }
1089 klass->SetDexCache(FindDexCache(dex_file));
1090 LoadClass(dex_file, dex_class_def, klass, class_loader);
1091 // Check for a pending exception during load
1092 Thread* self = Thread::Current();
1093 if (self->IsExceptionPending()) {
1094 return NULL;
1095 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001096 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001097 klass->SetClinitThreadId(self->GetTid());
1098 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001099 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001100 if (!success) {
1101 // We may fail to insert if we raced with another thread.
1102 klass->SetClinitThreadId(0);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001103 klass.reset(LookupClass(descriptor, class_loader));
1104 CHECK(klass.get() != NULL);
1105 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001106 }
1107 // Finish loading (if necessary) by finding parents
1108 CHECK(!klass->IsLoaded());
1109 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1110 // Loading failed.
1111 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001112 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001113 lock.NotifyAll();
1114 return NULL;
1115 }
1116 CHECK(klass->IsLoaded());
1117 // Link the class (if necessary)
1118 CHECK(!klass->IsResolved());
1119 if (!LinkClass(klass)) {
1120 // Linking failed.
1121 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001122 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001123 lock.NotifyAll();
1124 return NULL;
1125 }
1126 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001127
1128 /*
1129 * We send CLASS_PREPARE events to the debugger from here. The
1130 * definition of "preparation" is creating the static fields for a
1131 * class and initializing them to the standard default values, but not
1132 * executing any code (that comes later, during "initialization").
1133 *
1134 * We did the static preparation in LinkClass.
1135 *
1136 * The class has been prepared and resolved but possibly not yet verified
1137 * at this point.
1138 */
1139 Dbg::PostClassPrepare(klass.get());
1140
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001141 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001142}
1143
Brian Carlstrom4873d462011-08-21 15:23:39 -07001144// Precomputes size that will be needed for Class, matching LinkStaticFields
1145size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1146 const DexFile::ClassDef& dex_class_def) {
1147 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001148 size_t num_ref = 0;
1149 size_t num_32 = 0;
1150 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001151 if (class_data != NULL) {
1152 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1153 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001154 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001155 char c = descriptor[0];
1156 if (c == 'L' || c == '[') {
1157 num_ref++;
1158 } else if (c == 'J' || c == 'D') {
1159 num_64++;
1160 } else {
1161 num_32++;
1162 }
1163 }
1164 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001165 // start with generic class data
1166 size_t size = sizeof(Class);
1167 // follow with reference fields which must be contiguous at start
1168 size += (num_ref * sizeof(uint32_t));
1169 // if there are 64-bit fields to add, make sure they are aligned
1170 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1171 if (num_32 != 0) {
1172 // use an available 32-bit field for padding
1173 num_32--;
1174 }
1175 size += sizeof(uint32_t); // either way, we are adding a word
1176 DCHECK_EQ(size, RoundUp(size, 8));
1177 }
1178 // tack on any 64-bit fields now that alignment is assured
1179 size += (num_64 * sizeof(uint64_t));
1180 // tack on any remaining 32-bit fields
1181 size += (num_32 * sizeof(uint32_t));
1182 return size;
1183}
1184
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001185void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001186 // Every kind of method should at least get an invoke stub from the oat_method.
1187 // non-abstract methods also get their code pointers.
1188 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001189 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001190
1191 if (method->IsAbstract()) {
1192 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1193 return;
1194 }
1195 if (method->IsNative()) {
1196 // unregistering restores the dlsym lookup stub
1197 method->UnregisterNative();
1198 return;
1199 }
1200}
1201
Brian Carlstromf615a612011-07-23 12:50:34 -07001202void ClassLinker::LoadClass(const DexFile& dex_file,
1203 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001204 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001205 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001206 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001207 CHECK(klass->GetDexCache() != NULL);
1208 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001209 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001210 CHECK(descriptor != NULL);
1211
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001212 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001213 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001214 // Make sure that none of our runtime-only flags are set.
1215 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001216 klass->SetAccessFlags(access_flags);
1217 klass->SetClassLoader(class_loader);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001218 DCHECK(klass->GetPrimitiveType() == Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001219 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001220
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001221 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001222
Ian Rogers0571d352011-11-03 19:51:38 -07001223 // Load fields fields.
1224 const byte* class_data = dex_file.GetClassData(dex_class_def);
1225 if (class_data == NULL) {
1226 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001227 }
Ian Rogers0571d352011-11-03 19:51:38 -07001228 ClassDataItemIterator it(dex_file, class_data);
1229 if (it.NumStaticFields() != 0) {
1230 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1231 }
1232 if (it.NumInstanceFields() != 0) {
1233 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1234 }
1235 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1236 SirtRef<Field> sfield(AllocField());
1237 klass->SetStaticField(i, sfield.get());
1238 LoadField(dex_file, it, klass, sfield);
1239 }
1240 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1241 SirtRef<Field> ifield(AllocField());
1242 klass->SetInstanceField(i, ifield.get());
1243 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001244 }
1245
Brian Carlstromaded5f72011-10-07 17:15:04 -07001246 UniquePtr<const OatFile::OatClass> oat_class;
1247 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001248 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001249 if (oat_file != NULL) {
1250 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1251 if (oat_dex_file != NULL) {
1252 uint32_t class_def_index;
1253 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1254 CHECK(found) << descriptor;
1255 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001256 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001257 }
1258 }
1259 }
Ian Rogers0571d352011-11-03 19:51:38 -07001260 // Load methods.
1261 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001262 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001263 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001264 }
Ian Rogers0571d352011-11-03 19:51:38 -07001265 if (it.NumVirtualMethods() != 0) {
1266 // TODO: append direct methods to class object
1267 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001268 }
Ian Rogers0571d352011-11-03 19:51:38 -07001269 size_t method_index = 0;
1270 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1271 SirtRef<Method> method(AllocMethod());
1272 klass->SetDirectMethod(i, method.get());
1273 LoadMethod(dex_file, it, klass, method);
1274 if (oat_class.get() != NULL) {
1275 LinkCode(method, oat_class.get(), method_index);
1276 }
1277 method_index++;
1278 }
1279 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1280 SirtRef<Method> method(AllocMethod());
1281 klass->SetVirtualMethod(i, method.get());
1282 LoadMethod(dex_file, it, klass, method);
1283 if (oat_class.get() != NULL) {
1284 LinkCode(method, oat_class.get(), method_index);
1285 }
1286 method_index++;
1287 }
1288 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001289}
1290
Ian Rogers0571d352011-11-03 19:51:38 -07001291void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1292 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001293 uint32_t field_idx = it.GetMemberIndex();
1294 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001295 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001296 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001297}
1298
Ian Rogers0571d352011-11-03 19:51:38 -07001299void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1300 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001301 uint32_t method_idx = it.GetMemberIndex();
1302 dst->SetDexMethodIndex(method_idx);
1303 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001304 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001305
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001306
1307 StringPiece method_name(dex_file.GetMethodName(method_id));
1308 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001309 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1310 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001311
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001312 if (method_name == "finalize") {
1313 // Create the prototype for a signature of "()V"
1314 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1315 if (void_string_id != NULL) {
1316 const DexFile::TypeId* void_type_id =
1317 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1318 if (void_type_id != NULL) {
1319 std::vector<uint16_t> no_args;
1320 const DexFile::ProtoId* finalizer_proto =
1321 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1322 if (finalizer_proto != NULL) {
1323 // We have the prototype in the dex file
1324 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1325 klass->SetFinalizable();
1326 } else {
1327 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1328 // The Enum class declares a "final" finalize() method to prevent subclasses from
1329 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1330 // subclasses, so we exclude it here.
1331 // We also want to avoid setting the flag on Object, where we know that finalize() is
1332 // empty.
1333 if (klass_descriptor != "Ljava/lang/Object;" &&
1334 klass_descriptor != "Ljava/lang/Enum;") {
1335 klass->SetFinalizable();
1336 }
1337 }
1338 }
1339 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001340 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001341 }
Ian Rogers0571d352011-11-03 19:51:38 -07001342 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001343 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001344
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001345 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1346 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1347 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1348 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1349 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1350 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001351
Brian Carlstrom934486c2011-07-12 23:42:50 -07001352 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001353}
1354
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001355void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001356 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1357 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001358}
1359
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001360void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1361 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001362 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001363 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001364}
1365
Brian Carlstromaded5f72011-10-07 17:15:04 -07001366bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001367 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001368 for (size_t i = 0; i != dex_files_.size(); ++i) {
1369 if (dex_files_[i] == &dex_file) {
1370 return true;
1371 }
1372 }
1373 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001374}
1375
Brian Carlstromaded5f72011-10-07 17:15:04 -07001376bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001377 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001378 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001379}
1380
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001381void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001382 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001383 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001384 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001385 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001386 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001387}
1388
Brian Carlstromaded5f72011-10-07 17:15:04 -07001389void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001390 {
1391 MutexLock mu(dex_lock_);
1392 if (IsDexFileRegisteredLocked(dex_file)) {
1393 return;
1394 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001395 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001396 // Don't alloc while holding the lock, since allocation may need to
1397 // suspend all threads and another thread may need the dex_lock_ to
1398 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001399 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001400 {
1401 MutexLock mu(dex_lock_);
1402 if (IsDexFileRegisteredLocked(dex_file)) {
1403 return;
1404 }
1405 RegisterDexFileLocked(dex_file, dex_cache);
1406 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001407}
1408
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001409void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001410 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001411 RegisterDexFileLocked(dex_file, dex_cache);
1412}
1413
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001414const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001415 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001416 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001417 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1418 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001419 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001420 }
1421 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001422 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001423 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001424}
1425
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001426DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001427 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001428 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001429 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001430 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001431 }
1432 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001433 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001434 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001435}
1436
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001437Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1438 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001439 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001440 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001441 CHECK(primitive_class != NULL);
1442 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001443 primitive_class->SetPrimitiveType(type);
1444 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001445 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001446 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1447 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001448}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001449
Brian Carlstrombe977852011-07-19 14:54:54 -07001450// Create an array class (i.e. the class object for the array, not the
1451// array itself). "descriptor" looks like "[C" or "[[[[B" or
1452// "[Ljava/lang/String;".
1453//
1454// If "descriptor" refers to an array of primitives, look up the
1455// primitive type's internally-generated class object.
1456//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001457// "class_loader" is the class loader of the class that's referring to
1458// us. It's used to ensure that we're looking for the element type in
1459// the right context. It does NOT become the class loader for the
1460// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001461//
1462// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001463Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001464 const ClassLoader* class_loader) {
1465 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001466
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001467 // Identify the underlying component type
1468 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001469 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001470 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001471 return NULL;
1472 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001473
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001474 // See if the component type is already loaded. Array classes are
1475 // always associated with the class loader of their underlying
1476 // element type -- an array of Strings goes with the loader for
1477 // java/lang/String -- so we need to look for it there. (The
1478 // caller should have checked for the existence of the class
1479 // before calling here, but they did so with *their* class loader,
1480 // not the component type's loader.)
1481 //
1482 // If we find it, the caller adds "loader" to the class' initiating
1483 // loader list, which should prevent us from going through this again.
1484 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001485 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001486 // are the same, because our caller (FindClass) just did the
1487 // lookup. (Even if we get this wrong we still have correct behavior,
1488 // because we effectively do this lookup again when we add the new
1489 // class to the hash table --- necessary because of possible races with
1490 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001491 if (class_loader != component_type->GetClassLoader()) {
1492 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001493 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001494 return new_class;
1495 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001496 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001497
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001498 // Fill out the fields in the Class.
1499 //
1500 // It is possible to execute some methods against arrays, because
1501 // all arrays are subclasses of java_lang_Object_, so we need to set
1502 // up a vtable. We can just point at the one in java_lang_Object_.
1503 //
1504 // Array classes are simple enough that we don't need to do a full
1505 // link step.
1506
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001507 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001508 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001509 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001510 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001511 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001512 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001513 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001514 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001515 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001516 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001517 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001518 }
1519 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001520 if (new_class.get() == NULL) {
1521 new_class.reset(AllocClass(sizeof(Class)));
1522 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001523 return NULL;
1524 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001525 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001526 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001527 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001528 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001529 new_class->SetSuperClass(java_lang_Object);
1530 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001531 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001532 new_class->SetClassLoader(component_type->GetClassLoader());
1533 new_class->SetStatus(Class::kStatusInitialized);
1534 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001535 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001536
1537
1538 // All arrays have java/lang/Cloneable and java/io/Serializable as
1539 // interfaces. We need to set that up here, so that stuff like
1540 // "instanceof" works right.
1541 //
1542 // Note: The GC could run during the call to FindSystemClass,
1543 // so we need to make sure the class object is GC-valid while we're in
1544 // there. Do this by clearing the interface list so the GC will just
1545 // think that the entries are null.
1546
1547
1548 // Use the single, global copies of "interfaces" and "iftable"
1549 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001550 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001551 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001552
1553 // Inherit access flags from the component type. Arrays can't be
1554 // used as a superclass or interface, so we want to add "final"
1555 // and remove "interface".
1556 //
1557 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001558 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001559 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001560 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1561 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001562
Ian Rogers5d76c432011-10-31 21:42:49 -07001563 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001564 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001565 }
1566 // Another thread must have loaded the class after we
1567 // started but before we finished. Abandon what we've
1568 // done.
1569 //
1570 // (Yes, this happens.)
1571
1572 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001573 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001574 DCHECK(other_class != NULL);
1575 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001576}
1577
1578Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001579 switch (Primitive::GetType(type)) {
1580 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001581 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001582 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001583 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001584 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001585 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001586 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001587 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001588 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001589 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001590 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001591 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001592 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001593 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001594 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001595 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001596 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001597 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001598 case Primitive::kPrimNot:
1599 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001600 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001601 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001602 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001603 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001604}
1605
Ian Rogers5d76c432011-10-31 21:42:49 -07001606bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass, bool image_class) {
Brian Carlstromae826982011-11-09 01:33:42 -08001607 if (verbose_) {
1608 DexCache* dex_cache = klass->GetDexCache();
1609 std::string source;
1610 if (dex_cache != NULL) {
1611 source += " from ";
1612 source += dex_cache->GetLocation()->ToModifiedUtf8();
1613 }
1614 LOG(INFO) << "Loaded class " << descriptor << source;
1615 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001616 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001617 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001618 Table::iterator it;
1619 if (image_class) {
1620 // TODO: sanity check there's no match in classes_
1621 it = image_classes_.insert(std::make_pair(hash, klass));
1622 } else {
1623 // TODO: sanity check there's no match in image_classes_
1624 it = classes_.insert(std::make_pair(hash, klass));
1625 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001626 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001627}
1628
Brian Carlstromae826982011-11-09 01:33:42 -08001629bool ClassLinker::RemoveClass(const std::string& descriptor, const ClassLoader* class_loader) {
1630 size_t hash = StringPieceHash()(descriptor);
1631 MutexLock mu(classes_lock_);
1632 typedef Table::const_iterator It; // TODO: C++0x auto
1633 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001634 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001635 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1636 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001637 kh.ChangeClass(klass);
1638 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001639 classes_.erase(it);
1640 return true;
1641 }
1642 }
1643 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1644 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001645 kh.ChangeClass(klass);
1646 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001647 image_classes_.erase(it);
1648 return true;
1649 }
1650 }
1651 return false;
1652}
1653
Brian Carlstromaded5f72011-10-07 17:15:04 -07001654Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001655 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001656 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001657 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001658 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001659 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001660 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001661 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001662 kh.ChangeClass(klass);
1663 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001664 return klass;
1665 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001666 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001667 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1668 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001669 kh.ChangeClass(klass);
1670 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001671 return klass;
1672 }
1673 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001674 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001675}
1676
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001677void ClassLinker::LookupClasses(const std::string& descriptor, std::vector<Class*>& classes) {
1678 classes.clear();
1679 size_t hash = StringPieceHash()(descriptor);
1680 MutexLock mu(classes_lock_);
1681 typedef Table::const_iterator It; // TODO: C++0x auto
1682 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001683 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001684 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001685 Class* klass = it->second;
1686 kh.ChangeClass(klass);
1687 if (descriptor == kh.GetDescriptor()) {
1688 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001689 }
1690 }
1691 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001692 Class* klass = it->second;
1693 kh.ChangeClass(klass);
1694 if (descriptor == kh.GetDescriptor()) {
1695 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001696 }
1697 }
1698}
1699
jeffhao98eacac2011-09-14 16:11:53 -07001700void ClassLinker::VerifyClass(Class* klass) {
1701 if (klass->IsVerified()) {
1702 return;
1703 }
1704
1705 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001706 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001707
Ian Rogersd81871c2011-10-03 13:57:23 -07001708 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001709 klass->SetStatus(Class::kStatusVerified);
1710 } else {
1711 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001712 Thread* self = Thread::Current();
1713 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1714 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001715 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001716 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001717 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001718 }
jeffhao98eacac2011-09-14 16:11:53 -07001719}
1720
Jesse Wilson95caa792011-10-12 18:14:17 -04001721Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001722 ClassLoader* loader, ObjectArray<Method>* methods,
1723 ObjectArray<ObjectArray<Class> >* throws) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001724 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass)));
1725 CHECK(klass.get() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001726 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001727 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001728 klass->SetClassLoader(loader);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001729 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001730 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001731 klass->SetDexCache(proxy_class->GetDexCache());
1732 klass->SetDexTypeIndex(-1);
Ian Rogers466bb252011-10-14 03:29:56 -07001733 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001734 klass->SetStatus(Class::kStatusInitialized); // no loading or initializing necessary
Jesse Wilson95caa792011-10-12 18:14:17 -04001735
Ian Rogers466bb252011-10-14 03:29:56 -07001736 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001737 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001738 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001739
Ian Rogers466bb252011-10-14 03:29:56 -07001740 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001741 size_t num_virtual_methods = methods->GetLength();
1742 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1743 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001744 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001745 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001746 }
Ian Rogers466bb252011-10-14 03:29:56 -07001747 // Link the virtual methods, creating vtable and iftables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001748 if (!LinkMethods(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001749 DCHECK(Thread::Current()->IsExceptionPending());
1750 return NULL;
1751 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001752 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001753}
1754
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001755std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1756 DCHECK(proxy_class->IsProxyClass());
1757 String* name = proxy_class->GetName();
1758 DCHECK(name != NULL);
1759 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1760}
1761
1762
1763Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001764 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001765 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001766 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001767 Method* proxy_constructor = proxy_direct_methods->Get(2);
1768 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1769 // code_ too)
1770 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1771 // Make this constructor public and fix the class to be our Proxy version
1772 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001773 constructor->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001774 // Sanity checks
1775 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001776 MethodHelper mh(constructor);
1777 CHECK_STREQ(mh.GetName(), "<init>");
1778 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001779 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001780 return constructor;
1781}
1782
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001783Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1784 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1785 // prototype method
1786 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1787 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001788 // as necessary
1789 Method* method = down_cast<Method*>(prototype->Clone());
1790
1791 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1792 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001793 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001794 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001795
Ian Rogers466bb252011-10-14 03:29:56 -07001796 // At runtime the method looks like a reference and argument saving method, clone the code
1797 // related parameters from this method.
1798 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1799 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1800 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1801 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1802 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Jesse Wilson95caa792011-10-12 18:14:17 -04001803
Ian Rogers466bb252011-10-14 03:29:56 -07001804 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001805 CHECK(!prototype->IsFinal());
1806 CHECK(method->IsFinal());
1807 CHECK(!method->IsAbstract());
1808 MethodHelper mh(method);
1809 const char* method_name = mh.GetName();
1810 const char* method_shorty = mh.GetShorty();
1811 Class* method_return = mh.GetReturnType();
1812
1813 mh.ChangeMethod(prototype.get());
1814
1815 CHECK_STREQ(mh.GetName(), method_name);
1816 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001817
1818 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001819 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001820
1821 return method;
1822}
1823
Brian Carlstrom25c33252011-09-18 15:58:35 -07001824bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001825 CHECK(klass->IsResolved() || klass->IsErroneous())
1826 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001827
Carl Shapirob5573532011-07-12 18:22:59 -07001828 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001829
Brian Carlstrom25c33252011-09-18 15:58:35 -07001830 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001831 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001832 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001833 ObjectLock lock(klass);
1834
Brian Carlstromd1422f82011-09-28 11:37:09 -07001835 if (klass->GetStatus() == Class::kStatusInitialized) {
1836 return true;
1837 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001838
Brian Carlstromd1422f82011-09-28 11:37:09 -07001839 if (klass->IsErroneous()) {
1840 ThrowEarlierClassFailure(klass);
1841 return false;
1842 }
1843
1844 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001845 VerifyClass(klass);
1846 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001847 return false;
1848 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001849 }
1850
Brian Carlstrom25c33252011-09-18 15:58:35 -07001851 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1852 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001853 // if the class has a <clinit> but we can't run it during compilation,
1854 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001855 return false;
1856 }
1857
Brian Carlstromd1422f82011-09-28 11:37:09 -07001858 // If the class is kStatusInitializing, either this thread is
1859 // initializing higher up the stack or another thread has beat us
1860 // to initializing and we need to wait. Either way, this
1861 // invocation of InitializeClass will not be responsible for
1862 // running <clinit> and will return.
1863 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001864 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001865 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001866 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001867 return true;
1868 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001869 // No. That's fine. Wait for another thread to finish initializing.
1870 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001871 }
1872
1873 if (!ValidateSuperClassDescriptors(klass)) {
1874 klass->SetStatus(Class::kStatusError);
1875 return false;
1876 }
1877
Brian Carlstromd1422f82011-09-28 11:37:09 -07001878 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001879
Elliott Hughesdcc24742011-09-07 14:02:44 -07001880 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001881 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001882 }
1883
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001884 uint64_t t0 = NanoTime();
1885
Brian Carlstrom25c33252011-09-18 15:58:35 -07001886 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001887 return false;
1888 }
1889
1890 InitializeStaticFields(klass);
1891
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001892 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001893 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001894 }
1895
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001896 uint64_t t1 = NanoTime();
1897
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001898 {
1899 ObjectLock lock(klass);
1900
1901 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001902 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001903 klass->SetStatus(Class::kStatusError);
1904 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001905 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1906 RuntimeStats* thread_stats = self->GetStats();
1907 ++global_stats->class_init_count;
1908 ++thread_stats->class_init_count;
1909 global_stats->class_init_time_ns += (t1 - t0);
1910 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001911 klass->SetStatus(Class::kStatusInitialized);
Brian Carlstromae826982011-11-09 01:33:42 -08001912 if (verbose_) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001913 ClassHelper kh(klass);
1914 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08001915 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001916 }
1917 lock.NotifyAll();
1918 }
1919
1920 return true;
1921}
1922
Brian Carlstromd1422f82011-09-28 11:37:09 -07001923bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1924 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001925 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001926 lock.Wait();
1927
1928 // When we wake up, repeat the test for init-in-progress. If
1929 // there's an exception pending (only possible if
1930 // "interruptShouldThrow" was set), bail out.
1931 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001932 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001933 klass->SetStatus(Class::kStatusError);
1934 return false;
1935 }
1936 // Spurious wakeup? Go back to waiting.
1937 if (klass->GetStatus() == Class::kStatusInitializing) {
1938 continue;
1939 }
1940 if (klass->IsErroneous()) {
1941 // The caller wants an exception, but it was thrown in a
1942 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001943 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001944 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001945 return false;
1946 }
1947 if (klass->IsInitialized()) {
1948 return true;
1949 }
1950 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1951 }
1952 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1953}
1954
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001955bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1956 if (klass->IsInterface()) {
1957 return true;
1958 }
1959 // begin with the methods local to the superclass
1960 if (klass->HasSuperClass() &&
1961 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1962 const Class* super = klass->GetSuperClass();
1963 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001964 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001965 if (method != super->GetVirtualMethod(i) &&
1966 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001967 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1968
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001969 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
1970 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
1971 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001972 return false;
1973 }
1974 }
1975 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001976 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1977 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1978 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001979 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1980 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001981 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001982 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001983 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001984 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1985
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001986 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
1987 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
1988 PrettyMethod(method).c_str(),
1989 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001990 return false;
1991 }
1992 }
1993 }
1994 }
1995 return true;
1996}
1997
1998bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001999 const Class* klass1,
2000 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002001 if (klass1 == klass2) {
2002 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002003 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002004 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002005 const DexFile::ProtoId& proto_id =
2006 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002007 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2008 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002009 if (descriptor == NULL) {
2010 break;
2011 }
2012 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2013 // Found a non-primitive type.
2014 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2015 return false;
2016 }
2017 }
2018 }
2019 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002020 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002021 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002022 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002023 return false;
2024 }
2025 }
2026 return true;
2027}
2028
2029// Returns true if classes referenced by the descriptor are the
2030// same classes in klass1 as they are in klass2.
2031bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002032 const Class* klass1,
2033 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002034 CHECK(descriptor != NULL);
2035 CHECK(klass1 != NULL);
2036 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002037 if (klass1 == klass2) {
2038 return true;
2039 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002040 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002042 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002043 // TODO: found2 == NULL
2044 // TODO: lookup found1 in initiating loader list
2045 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002046 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002047 return found1 == found2;
2048 } else {
2049 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002050 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002051}
2052
Brian Carlstrom25c33252011-09-18 15:58:35 -07002053bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002054 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002055 if (!klass->IsInterface() && klass->HasSuperClass()) {
2056 Class* super_class = klass->GetSuperClass();
2057 if (super_class->GetStatus() != Class::kStatusInitialized) {
2058 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002059 Thread* self = Thread::Current();
2060 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002061 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002062 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002063 // TODO: check for a pending exception
2064 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002065 if (!can_run_clinit) {
2066 // Don't set status to error when we can't run <clinit>.
2067 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2068 klass->SetStatus(Class::kStatusVerified);
2069 return false;
2070 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002071 klass->SetStatus(Class::kStatusError);
2072 klass->NotifyAll();
2073 return false;
2074 }
2075 }
2076 }
2077 return true;
2078}
2079
Brian Carlstrom25c33252011-09-18 15:58:35 -07002080bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002081 CHECK(c != NULL);
2082 if (c->IsInitialized()) {
2083 return true;
2084 }
2085
Elliott Hughes5f791332011-09-15 17:45:30 -07002086 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002087 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002088 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002089 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002090}
2091
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002092void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002093 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002094 const ClassLoader* cl = c->GetClassLoader();
2095 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002096 ClassDataItemIterator it(dex_file, class_data);
2097 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2098 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002099 }
2100}
2101
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002102void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002103 size_t num_static_fields = klass->NumStaticFields();
2104 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002105 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002106 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002107 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002108 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002109 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002110 return;
2111 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002112 ClassHelper kh(klass);
2113 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002114 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002115 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002116 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002117
Ian Rogers0571d352011-11-03 19:51:38 -07002118 if (it.HasNext()) {
2119 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2120 std::map<uint32_t, Field*> field_map;
2121 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2122 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2123 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002124 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002125 }
2126}
2127
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002128bool ClassLinker::LinkClass(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002129 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002130 if (!LinkSuperClass(klass)) {
2131 return false;
2132 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002133 if (!LinkMethods(klass, NULL)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002134 return false;
2135 }
2136 if (!LinkInstanceFields(klass)) {
2137 return false;
2138 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002139 if (!LinkStaticFields(klass)) {
2140 return false;
2141 }
2142 CreateReferenceInstanceOffsets(klass);
2143 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002144 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2145 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002146 return true;
2147}
2148
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002149bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002150 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002151 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2152 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2153 if (class_def == NULL) {
2154 return false;
2155 }
2156 uint16_t super_class_idx = class_def->superclass_idx_;
2157 if (super_class_idx != DexFile::kDexNoIndex16) {
2158 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002159 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002160 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002161 return false;
2162 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002163 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002164 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002165 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2166 if (interfaces != NULL) {
2167 for (size_t i = 0; i < interfaces->Size(); i++) {
2168 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2169 Class* interface = ResolveType(dex_file, idx, klass.get());
2170 if (interface == NULL) {
2171 DCHECK(Thread::Current()->IsExceptionPending());
2172 return false;
2173 }
2174 // Verify
2175 if (!klass->CanAccess(interface)) {
2176 // TODO: the RI seemed to ignore this in my testing.
2177 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2178 "Interface %s implemented by class %s is inaccessible",
2179 PrettyDescriptor(interface).c_str(),
2180 PrettyDescriptor(klass.get()).c_str());
2181 return false;
2182 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002183 }
2184 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002185 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002186 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002187 return true;
2188}
2189
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002190bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002191 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002192 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002193 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002195 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002196 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002197 return false;
2198 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002199 return true;
2200 }
2201 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002202 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002203 return false;
2204 }
2205 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002206 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002207 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002208 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002209 PrettyDescriptor(super).c_str(),
2210 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002211 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002212 return false;
2213 }
2214 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002215 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002216 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002217 PrettyDescriptor(super).c_str(),
2218 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002219 return false;
2220 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002221
2222 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2223 if (super->IsFinalizable()) {
2224 klass->SetFinalizable();
2225 }
2226
Elliott Hughes2da50362011-10-10 16:57:08 -07002227 // Inherit reference flags (if any) from the superclass.
2228 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2229 if (reference_flags != 0) {
2230 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2231 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002232 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002233 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002234 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002235 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002236 return false;
2237 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002238
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002239#ifndef NDEBUG
2240 // Ensure super classes are fully resolved prior to resolving fields..
2241 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002242 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002243 super = super->GetSuperClass();
2244 }
2245#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002246 return true;
2247}
2248
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002249// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002250bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002251 if (klass->IsInterface()) {
2252 // No vtable.
2253 size_t count = klass->NumVirtualMethods();
2254 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002255 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002256 return false;
2257 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002258 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002259 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002260 }
jeffhaobdb76512011-09-07 11:43:16 -07002261 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002262 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002263 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002264 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002265 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002266 }
2267 return true;
2268}
2269
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002270bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002271 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002272 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2273 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002274 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002275 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002276 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002277 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002278 MethodHelper local_mh(NULL, this);
2279 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002280 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002281 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002282 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002283 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002284 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002285 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002286 super_mh.ChangeMethod(super_method);
2287 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288 // Verify
2289 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002290 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002291 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002292 PrettyDescriptor(klass.get()).c_str(),
2293 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 return false;
2295 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002296 vtable->Set(j, local_method);
2297 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002298 break;
2299 }
2300 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002301 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002302 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002303 vtable->Set(actual_count, local_method);
2304 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002305 actual_count += 1;
2306 }
2307 }
2308 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002309 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002310 return false;
2311 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002312 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002313 CHECK_LE(actual_count, max_count);
2314 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002315 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002316 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002317 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002318 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002319 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002320 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002321 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002322 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002323 return false;
2324 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002325 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002326 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002327 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2328 vtable->Set(i, virtual_method);
2329 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002330 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002331 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002332 }
2333 return true;
2334}
2335
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002336bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002337 size_t super_ifcount;
2338 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002339 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002340 } else {
2341 super_ifcount = 0;
2342 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002343 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002344 ClassHelper kh(klass.get(), this);
2345 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2346 ifcount += num_interfaces;
2347 for (size_t i = 0; i < num_interfaces; i++) {
2348 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2349 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002350 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002351 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002352 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002353 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002354 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002355 return true;
2356 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002357 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002359 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2360 for (size_t i = 0; i < super_ifcount; i++) {
2361 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2362 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002363 }
2364 // Flatten the interface inheritance hierarchy.
2365 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002366 for (size_t i = 0; i < num_interfaces; i++) {
2367 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002368 DCHECK(interface != NULL);
2369 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002370 ClassHelper ih(interface);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002371 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002372 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002373 PrettyDescriptor(klass.get()).c_str(),
2374 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002375 return false;
2376 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002377 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002378 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002379 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002380 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2381 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002382 }
2383 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002384 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002385 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002386
2387 // If we're an interface, we don't need the vtable pointers, so we're done.
2388 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002389 return true;
2390 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002391 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002392 MethodHelper vtable_mh(NULL, this);
2393 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002394 for (size_t i = 0; i < ifcount; ++i) {
2395 InterfaceEntry* interface_entry = iftable->Get(i);
2396 Class* interface = interface_entry->GetInterface();
2397 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2398 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002399 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002400 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2401 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002402 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002403 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002404 // For each method listed in the interface's method list, find the
2405 // matching method in our class's method list. We want to favor the
2406 // subclass over the superclass, which just requires walking
2407 // back from the end of the vtable. (This only matters if the
2408 // superclass defines a private method and this class redefines
2409 // it -- otherwise it would use the same vtable slot. In .dex files
2410 // those don't end up in the virtual method table, so it shouldn't
2411 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002412 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2413 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002414 vtable_mh.ChangeMethod(vtable_method);
2415 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002416 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002417 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002418 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002419 return false;
2420 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002421 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002422 break;
2423 }
2424 }
2425 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002426 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002427 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002428 Method* mir_method = miranda_list[mir];
2429 vtable_mh.ChangeMethod(mir_method);
2430 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002431 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002432 break;
2433 }
2434 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002435 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002436 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002437 miranda_method.reset(AllocMethod());
2438 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2439 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002440 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002441 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002442 }
2443 }
2444 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002445 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002446 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002447 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002448 klass->SetVirtualMethods((old_method_count == 0)
2449 ? AllocObjectArray<Method>(new_method_count)
2450 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002451
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002452 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2453 CHECK(vtable != NULL);
2454 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002455 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002456 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002457 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002458 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002459 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002460 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2461 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2462 klass->SetVirtualMethod(old_method_count + i, method);
2463 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002464 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002465 // TODO: do not assign to the vtable field until it is fully constructed.
2466 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002467 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002468
2469 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2470 for (int i = 0; i < vtable->GetLength(); ++i) {
2471 CHECK(vtable->Get(i) != NULL);
2472 }
2473
2474// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2475
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002476 return true;
2477}
2478
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002479bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2480 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002481 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002482}
2483
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002484bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2485 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002486 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002487 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002488 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002489 return success;
2490}
2491
Brian Carlstromdbc05252011-09-09 01:59:59 -07002492struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002493 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002494 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002495 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002496 fh_->ChangeField(field1);
2497 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2498 fh_->ChangeField(field2);
2499 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002500 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2501 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2502 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2503 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002504 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2505 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2506 if (order1 != order2) {
2507 return order1 < order2;
2508 }
2509
2510 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002511 fh_->ChangeField(field1);
2512 StringPiece name1(fh_->GetName());
2513 fh_->ChangeField(field2);
2514 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002515 return name1 < name2;
2516 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002517
2518 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002519};
2520
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002521bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002522 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002523 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002524
2525 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002526 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002527
2528 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002529 size_t size;
2530 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002531 if (is_static) {
2532 size = klass->GetClassSize();
2533 field_offset = Class::FieldsOffset();
2534 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002535 Class* super_class = klass->GetSuperClass();
2536 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002537 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002538 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002539 }
2540 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002541 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002542
Brian Carlstromdbc05252011-09-09 01:59:59 -07002543 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002544
Brian Carlstromdbc05252011-09-09 01:59:59 -07002545 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002546 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002547 std::deque<Field*> grouped_and_sorted_fields;
2548 for (size_t i = 0; i < num_fields; i++) {
2549 grouped_and_sorted_fields.push_back(fields->Get(i));
2550 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002551 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002552 std::sort(grouped_and_sorted_fields.begin(),
2553 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002554 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002555
2556 // References should be at the front.
2557 size_t current_field = 0;
2558 size_t num_reference_fields = 0;
2559 for (; current_field < num_fields; current_field++) {
2560 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002561 fh.ChangeField(field);
2562 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002563 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002564 if (isPrimitive) {
2565 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002566 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002567 grouped_and_sorted_fields.pop_front();
2568 num_reference_fields++;
2569 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002570 field->SetOffset(field_offset);
2571 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002572 }
2573
2574 // Now we want to pack all of the double-wide fields together. If
2575 // we're not aligned, though, we want to shuffle one 32-bit field
2576 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002577 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002578 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2579 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002580 fh.ChangeField(field);
2581 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002582 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2583 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002584 continue;
2585 }
2586 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002587 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002588 // drop the consumed field
2589 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2590 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002591 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002592 // whether we found a 32-bit field for padding or not, we advance
2593 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002594 }
2595
2596 // Alignment is good, shuffle any double-wide fields forward, and
2597 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002598 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002599 while (!grouped_and_sorted_fields.empty()) {
2600 Field* field = grouped_and_sorted_fields.front();
2601 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002602 fh.ChangeField(field);
2603 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002604 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002605 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002606 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002607 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002608 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002609 ? sizeof(uint64_t)
2610 : sizeof(uint32_t)));
2611 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002612 }
2613
Elliott Hughesadb460d2011-10-05 17:02:34 -07002614 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002615 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2616 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002617 // We know there are no non-reference fields in the Reference classes, and we know
2618 // that 'referent' is alphabetically last, so this is easy...
2619 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002620 fh.ChangeField(fields->Get(num_fields - 1));
2621 StringPiece name(fh.GetName());
2622 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002623 --num_reference_fields;
2624 }
2625
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002626#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002627 // Make sure that all reference fields appear before
2628 // non-reference fields, and all double-wide fields are aligned.
2629 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002630 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002631 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002632 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002633 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002634 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002635 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002636 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2637 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002638 fh.ChangeField(field);
2639 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002640 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002641 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002642 is_primitive = true; // We lied above, so we have to expect a lie here.
2643 }
2644 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002645 if (!seen_non_ref) {
2646 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002647 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002648 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002649 } else {
2650 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002651 }
2652 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002653 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002654 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002655 }
2656#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002657 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002658 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002659 if (is_static) {
2660 klass->SetNumReferenceStaticFields(num_reference_fields);
2661 klass->SetClassSize(size);
2662 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002663 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002664 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002665 klass->SetObjectSize(size);
2666 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002667 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002668 return true;
2669}
2670
2671// Set the bitmap of reference offsets, refOffsets, from the ifields
2672// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002673void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002674 uint32_t reference_offsets = 0;
2675 Class* super_class = klass->GetSuperClass();
2676 if (super_class != NULL) {
2677 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002678 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002679 if (reference_offsets == CLASS_WALK_SUPER) {
2680 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002681 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002682 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002683 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002684 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002685}
2686
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002687void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002688 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002689}
2690
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002691void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002692 uint32_t reference_offsets) {
2693 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002694 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2695 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002696 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002697 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002698 // All of the fields that contain object references are guaranteed
2699 // to be at the beginning of the fields list.
2700 for (size_t i = 0; i < num_reference_fields; ++i) {
2701 // Note that byte_offset is the offset from the beginning of
2702 // object, not the offset into instance data
2703 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002704 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002705 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2706 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2707 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002708 CHECK_NE(new_bit, 0U);
2709 reference_offsets |= new_bit;
2710 } else {
2711 reference_offsets = CLASS_WALK_SUPER;
2712 break;
2713 }
2714 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002715 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002716 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002717 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002718 } else {
2719 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002720 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002721}
2722
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002723String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002724 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002725 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002726 if (resolved != NULL) {
2727 return resolved;
2728 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002729 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2730 int32_t utf16_length = dex_file.GetStringLength(string_id);
2731 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002732 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002733 dex_cache->SetResolvedString(string_idx, string);
2734 return string;
2735}
2736
2737Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002738 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002739 DexCache* dex_cache,
2740 const ClassLoader* class_loader) {
2741 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002742 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002743 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002744 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002745 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002746 // TODO: we used to throw here if resolved's class loader was not the
2747 // boot class loader. This was to permit different classes with the
2748 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002749 dex_cache->SetResolvedType(type_idx, resolved);
2750 } else {
2751 DCHECK(Thread::Current()->IsExceptionPending());
2752 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002753 }
2754 return resolved;
2755}
2756
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002757Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2758 uint32_t method_idx,
2759 DexCache* dex_cache,
2760 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002761 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002762 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2763 if (resolved != NULL) {
2764 return resolved;
2765 }
2766 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2767 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2768 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002769 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002770 return NULL;
2771 }
2772
Ian Rogers0571d352011-11-03 19:51:38 -07002773 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2774 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002775 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002776 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002777 } else if (klass->IsInterface()) {
2778 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002779 } else {
2780 resolved = klass->FindVirtualMethod(name, signature);
2781 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002782 if (resolved != NULL) {
2783 dex_cache->SetResolvedMethod(method_idx, resolved);
2784 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002785 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002786 }
2787 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002788}
2789
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002790Field* ClassLinker::ResolveField(const DexFile& dex_file,
2791 uint32_t field_idx,
2792 DexCache* dex_cache,
2793 const ClassLoader* class_loader,
2794 bool is_static) {
2795 Field* resolved = dex_cache->GetResolvedField(field_idx);
2796 if (resolved != NULL) {
2797 return resolved;
2798 }
2799 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2800 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2801 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002802 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002803 return NULL;
2804 }
2805
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002806 const char* name = dex_file.GetFieldName(field_id);
2807 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002808 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002809 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002810 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002811 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002812 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002813 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002814 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002815 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002816 ThrowNoSuchFieldError(is_static, klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002817 }
2818 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002819}
2820
Ian Rogersad25ac52011-10-04 19:13:33 -07002821const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2822 Class* declaring_class = referrer->GetDeclaringClass();
2823 DexCache* dex_cache = declaring_class->GetDexCache();
2824 const DexFile& dex_file = FindDexFile(dex_cache);
2825 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2826 return dex_file.GetShorty(method_id.proto_idx_);
2827}
2828
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002829void ClassLinker::DumpAllClasses(int flags) const {
2830 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2831 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2832 std::vector<Class*> all_classes;
2833 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002834 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002835 typedef Table::const_iterator It; // TODO: C++0x auto
2836 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2837 all_classes.push_back(it->second);
2838 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002839 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2840 all_classes.push_back(it->second);
2841 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002842 }
2843
2844 for (size_t i = 0; i < all_classes.size(); ++i) {
2845 all_classes[i]->DumpClass(std::cerr, flags);
2846 }
2847}
2848
Elliott Hughescac6cc72011-11-03 20:31:21 -07002849void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2850 MutexLock mu(classes_lock_);
2851 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2852 << classes_.size() << " allocated classes\n";
2853}
2854
Elliott Hughese27955c2011-08-26 15:21:24 -07002855size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002856 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002857 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002858}
2859
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002860pid_t ClassLinker::GetClassesLockOwner() {
2861 return classes_lock_.GetOwner();
2862}
2863
2864pid_t ClassLinker::GetDexLockOwner() {
2865 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002866}
2867
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002868void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
2869 DCHECK(!init_done_);
2870
2871 DCHECK(klass != NULL);
2872 DCHECK(klass->GetClassLoader() == NULL);
2873
2874 DCHECK(class_roots_ != NULL);
2875 DCHECK(class_roots_->Get(class_root) == NULL);
2876 class_roots_->Set(class_root, klass);
2877}
2878
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002879} // namespace art