blob: caf2876b74e20e91bf4b6e6a871ab26cd9932241 [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 Rogersb067ac22011-12-13 18:05:09 -080075void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080076 const StringPiece& name) {
77 ClassHelper kh(c);
78 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080079 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080080 << " 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
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800202ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700203 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800204 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700205 class_linker->Init(boot_class_path);
206 return class_linker.release();
207}
208
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800209ClassLinker* ClassLinker::Create(InternTable* intern_table) {
210 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700211 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700212 return class_linker.release();
213}
214
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800215ClassLinker::ClassLinker(InternTable* intern_table)
216 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700217 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700218 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700219 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700220 init_done_(false),
221 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700222 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700223}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700224
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700225void CreateClassPath(const std::string& class_path,
226 std::vector<const DexFile*>& class_path_vector) {
227 std::vector<std::string> parsed;
228 Split(class_path, ':', parsed);
229 for (size_t i = 0; i < parsed.size(); ++i) {
230 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700231 if (dex_file == NULL) {
232 LOG(WARNING) << "Failed to open dex file " << parsed[i];
233 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700234 class_path_vector.push_back(dex_file);
235 }
236 }
237}
238
239void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800240 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700241
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700242 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700243
Elliott Hughes30646832011-10-13 16:59:46 -0700244 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700245 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
246 CHECK(java_lang_Class.get() != NULL);
247 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700248 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700249 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700250
Elliott Hughes418d20f2011-09-22 14:00:39 -0700251 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700252 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
253 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700254
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700255 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700256 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
257 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700258 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700259 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700260 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700261
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700262 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700263 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
264 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700265
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700266 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700267 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700268
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700269 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700270 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
271 char_array_class->SetComponentType(char_class.get());
272 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700273
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700274 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700275 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
276 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700277 java_lang_String->SetObjectSize(sizeof(String));
278 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400279
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700280 // Create storage for root classes, save away our work so far (requires
281 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700283 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700284 SetClassRoot(kJavaLangClass, java_lang_Class.get());
285 SetClassRoot(kJavaLangObject, java_lang_Object.get());
286 SetClassRoot(kClassArrayClass, class_array_class.get());
287 SetClassRoot(kObjectArrayClass, object_array_class.get());
288 SetClassRoot(kCharArrayClass, char_array_class.get());
289 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700290
291 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700292 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
293 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
294 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
295 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
296 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
297 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
298 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
299 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700302 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303
304 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700305 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700307 IntArray::SetArrayClass(int_array_class.get());
308 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700309
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700310 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700311
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700312 // setup boot_class_path_ and register class_path now that we can
313 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700314 std::vector<const DexFile*> boot_class_path_vector;
315 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700316 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700317 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
318 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700319 CHECK(dex_file != NULL);
320 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700321 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322
Elliott Hughes80609252011-09-23 17:24:51 -0700323 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700324 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700325 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700326 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700327 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700328 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
329
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
331 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700335 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700336
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700337 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700338 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700340 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700342 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700343
344 // now we can use FindSystemClass
345
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700346 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700347 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700349
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700350 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351 java_lang_Object->SetStatus(Class::kStatusNotReady);
352 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700353 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
355 java_lang_String->SetStatus(Class::kStatusNotReady);
356 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700357 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
359
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700360 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
362 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
363
364 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
365 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
366
367 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700368 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700369
370 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
371 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
372
373 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700374 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700375
376 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
377 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
378
379 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
380 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
381
382 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
383 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
384
Elliott Hughes418d20f2011-09-22 14:00:39 -0700385 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700386 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700387
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700388 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700389 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700390
391 // Setup the single, global copies of "interfaces" and "iftable"
392 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
393 CHECK(java_lang_Cloneable != NULL);
394 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
395 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700396 // We assume that Cloneable/Serializable don't have superinterfaces --
397 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700398 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800399 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
400 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700401
Elliott Hughes418d20f2011-09-22 14:00:39 -0700402 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800403 ClassHelper kh(class_array_class.get(), this);
404 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
405 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
406 kh.ChangeClass(object_array_class.get());
407 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
408 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700409 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700410 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700411 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700412 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
Elliott Hughes80609252011-09-23 17:24:51 -0700414 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
415 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700416 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700417
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700419 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700420 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700421
422 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700423 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700424 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700425
Ian Rogers466bb252011-10-14 03:29:56 -0700426 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
427
428 // Create java.lang.reflect.Proxy root
429 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
430 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
431
Brian Carlstrom1f870082011-08-23 16:02:11 -0700432 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700433 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
434 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700435 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436 java_lang_ref_FinalizerReference->SetAccessFlags(
437 java_lang_ref_FinalizerReference->GetAccessFlags() |
438 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700439 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440 java_lang_ref_PhantomReference->SetAccessFlags(
441 java_lang_ref_PhantomReference->GetAccessFlags() |
442 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700443 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444 java_lang_ref_SoftReference->SetAccessFlags(
445 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700446 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700447 java_lang_ref_WeakReference->SetAccessFlags(
448 java_lang_ref_WeakReference->GetAccessFlags() |
449 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700450
Brian Carlstromaded5f72011-10-07 17:15:04 -0700451 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700453 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700454 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
455
456 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
457 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
458 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
459
460 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
461 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
462 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
463 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
464
465 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700466 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
467 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700468 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700469
Brian Carlstroma663ea52011-08-19 23:33:41 -0700470 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700471
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800472 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700473}
474
475void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800476 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700477
478 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700479 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700480 // as the types of the field can't be resolved prior to the runtime being
481 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700482 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700483 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700484 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
485
Elliott Hughesadb460d2011-10-05 17:02:34 -0700486 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
487
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800488 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
489
Brian Carlstrom16192862011-09-12 17:50:06 -0700490 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800491 FieldHelper fh(pendingNext, this);
492 CHECK_STREQ(fh.GetName(), "pendingNext");
493 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
494 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700495
496 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800497 fh.ChangeField(queue);
498 CHECK_STREQ(fh.GetName(), "queue");
499 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
500 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700501
502 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800503 fh.ChangeField(queueNext);
504 CHECK_STREQ(fh.GetName(), "queueNext");
505 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
506 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700507
508 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800509 fh.ChangeField(referent);
510 CHECK_STREQ(fh.GetName(), "referent");
511 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
512 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700513
514 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800515 fh.ChangeField(zombie);
516 CHECK_STREQ(fh.GetName(), "zombie");
517 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
518 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700519
520 Heap::SetReferenceOffsets(referent->GetOffset(),
521 queue->GetOffset(),
522 queueNext->GetOffset(),
523 pendingNext->GetOffset(),
524 zombie->GetOffset());
525
Brian Carlstroma663ea52011-08-19 23:33:41 -0700526 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700527 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700528 ClassRoot class_root = static_cast<ClassRoot>(i);
529 Class* klass = GetClassRoot(class_root);
530 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700531 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700532 // note SetClassRoot does additional validation.
533 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700534 }
535
Elliott Hughes92f14b22011-10-06 12:29:54 -0700536 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700537
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700538 // disable the slow paths in FindClass and CreatePrimitiveClass now
539 // that Object, Class, and Object[] are setup
540 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700541
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800542 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700543}
544
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700545void ClassLinker::RunRootClinits() {
546 Thread* self = Thread::Current();
547 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
548 Class* c = GetClassRoot(ClassRoot(i));
549 if (!c->IsArrayClass() && !c->IsPrimitive()) {
550 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700551 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700552 }
553 }
554}
555
jeffhao262bf462011-10-20 18:36:32 -0700556const OatFile* ClassLinker::GenerateOatFile(const std::string& filename) {
557 std::string oat_filename(GetArtCacheFilenameOrDie(OatFile::DexFilenameToOatFilename(filename)));
558
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800559 std::string dex2oat_string("/system/bin/dex2oat");
560#ifndef NDEBUG
561 dex2oat_string += 'd';
562#endif
563 const char* dex2oat = dex2oat_string.c_str();
564
565 const char* class_path = Runtime::Current()->GetClassPath().c_str();
566
567 std::string boot_image_option_string("--boot-image=");
568 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
569 const char* boot_image_option = boot_image_option_string.c_str();
570
571 std::string dex_file_option_string("--dex-file=");
572 dex_file_option_string += filename;
573 const char* dex_file_option = dex_file_option_string.c_str();
574
575 std::string oat_file_option_string("--oat=");
576 oat_file_option_string += oat_filename;
577 const char* oat_file_option = oat_file_option_string.c_str();
578
jeffhao262bf462011-10-20 18:36:32 -0700579 // fork and exec dex2oat
580 pid_t pid = fork();
581 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800582 // no allocation allowed between fork and exec
583 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700584 "--runtime-arg", "-Xms64m",
585 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500586 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800587 "--runtime-arg", class_path,
588 boot_image_option,
589 dex_file_option,
590 oat_file_option,
jeffhao262bf462011-10-20 18:36:32 -0700591 NULL);
592
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800593 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
jeffhao262bf462011-10-20 18:36:32 -0700594 return NULL;
595 } else {
596 // wait for dex2oat to finish
597 int status;
598 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
599 if (got_pid != pid) {
600 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
601 return NULL;
602 }
603 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800604 LOG(ERROR) << dex2oat << " failed with dex-file=" << filename;
jeffhao262bf462011-10-20 18:36:32 -0700605 return NULL;
606 }
607 }
608 return OatFile::Open(oat_filename, "", NULL);
609}
610
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700611OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700612 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700613 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800614 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700615 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800616 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
617 // check the down cast
618 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700619 std::string oat_filename;
620 oat_filename += runtime->GetHostPrefix();
621 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700622 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700623 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700624 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700625 return NULL;
626 }
627 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
628 uint32_t image_oat_checksum = image_header.GetOatChecksum();
629 if (oat_checksum != image_oat_checksum) {
630 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
631 << " to expected oat checksum " << std::hex << oat_checksum
632 << " in image";
633 return NULL;
634 }
635 oat_files_.push_back(oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800636 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700637 return oat_file;
638}
639
Brian Carlstromae826982011-11-09 01:33:42 -0800640const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
641 for (size_t i = 0; i < oat_files_.size(); i++) {
642 const OatFile* oat_file = oat_files_[i];
643 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800644 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800645 return oat_file;
646 }
647 }
648 return NULL;
649}
650
651const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700652 MutexLock mu(dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800653 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
654 if (oat_file != NULL) {
655 return oat_file;
656 }
657
658 oat_file = FindOatFileFromOatLocation(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
jeffhao262bf462011-10-20 18:36:32 -0700659 if (oat_file != NULL) {
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700660 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
661 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
662 return oat_file;
663 }
664 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
665 << " is older than " << dex_file.GetLocation() << " --- regenerating";
Elliott Hughes234da572011-11-03 22:13:06 -0700666 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
667 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
668 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700669 // Fall through...
jeffhao262bf462011-10-20 18:36:32 -0700670 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700671 // Generate oat file if it wasn't found or was obsolete.
jeffhao262bf462011-10-20 18:36:32 -0700672 oat_file = GenerateOatFile(dex_file.GetLocation());
673 if (oat_file == NULL) {
674 LOG(ERROR) << "Failed to generate oat file from dex file " << dex_file.GetLocation();
675 return NULL;
676 }
677 oat_files_.push_back(oat_file);
678 return oat_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700679}
680
Brian Carlstromae826982011-11-09 01:33:42 -0800681const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700682 for (size_t i = 0; i < oat_files_.size(); i++) {
683 const OatFile* oat_file = oat_files_[i];
684 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800685 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700686 return oat_file;
687 }
688 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700689 return NULL;
690}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700691
Brian Carlstromae826982011-11-09 01:33:42 -0800692const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
693 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700694 if (oat_file != NULL) {
695 return oat_file;
696 }
697
Brian Carlstromae826982011-11-09 01:33:42 -0800698 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700699 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800700 if (oat_location.empty() || oat_location[0] != '/') {
701 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700702 return NULL;
703 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700704
Brian Carlstroma9f19782011-10-13 00:14:47 -0700705 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800706 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800707 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700708 if (oat_file != NULL) {
709 return oat_file;
710 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700711 oat_file = OatFile::Open(cache_location, "", NULL);
712 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800713 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700714 return NULL;
715 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700716 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700717
Brian Carlstromae826982011-11-09 01:33:42 -0800718 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromfad71432011-10-16 20:25:10 -0700719 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700720 return oat_file;
721}
722
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700723void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700724 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800725 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700726 CHECK(!init_done_);
727
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700728 const std::vector<Space*>& spaces = Heap::GetSpaces();
729 for (size_t i = 0; i < spaces.size(); i++) {
730 Space* space = spaces[i] ;
731 if (space->IsImageSpace()) {
732 OatFile* oat_file = OpenOat(space);
733 CHECK(oat_file != NULL) << "Failed to open oat file for image";
734 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
735 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
736
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800737 if (i == 0) {
738 // Special case of setting up the String class early so that we can test arbitrary objects
739 // as being Strings or not
740 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
741 ->AsObjectArray<Class>()->Get(kJavaLangString);
742 String::SetClass(java_lang_String);
743 }
744
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700745 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
746 static_cast<uint32_t>(dex_caches->GetLength()));
747 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700748 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800749 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700750
751 std::string dex_filename;
752 dex_filename += runtime->GetHostPrefix();
753 dex_filename += dex_file_location;
754 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
755 if (dex_file == NULL) {
756 LOG(FATAL) << "Failed to open dex file " << dex_filename
757 << " referenced from oat file as " << dex_file_location;
758 }
759
Brian Carlstromaded5f72011-10-07 17:15:04 -0700760 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
761 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700762
Brian Carlstromdf143242011-10-10 18:05:34 -0700763 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700764 }
765 }
766 }
767
Brian Carlstroma663ea52011-08-19 23:33:41 -0700768 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
769 DCHECK(heap_bitmap != NULL);
770
Brian Carlstroma663ea52011-08-19 23:33:41 -0700771 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700772 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700773
774 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700775 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
776 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700777
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800778 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700779 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
780 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800781 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700782 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700783 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700784 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
785 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
786 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
787 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
788 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
789 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
790 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
791 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700792 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700793 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700794
795 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700796
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800797 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700798}
799
Brian Carlstrom78128a62011-09-15 17:21:19 -0700800void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700801 DCHECK(obj != NULL);
802 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700803 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700804
Elliott Hughesdbb40792011-11-18 17:05:22 -0800805 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700806 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700807 return;
808 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700809 if (obj->IsClass()) {
810 // restore class to ClassLinker::classes_ table
811 Class* klass = obj->AsClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800812 std::string descriptor(ClassHelper(klass, class_linker).GetDescriptor());
Ian Rogers5d76c432011-10-31 21:42:49 -0700813 bool success = class_linker->InsertClass(descriptor, klass, true);
814 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700815 return;
816 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700817}
818
819// Keep in sync with InitCallback. Anything we visit, we need to
820// reinit references to when reinitializing a ClassLinker from a
821// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700822void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
823 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700824
825 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700826 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700827 }
828
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700829 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700830 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700831 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700832 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700833 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700834 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700835 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700836 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700837
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700838 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700839}
840
Elliott Hughesa2155262011-11-16 16:26:58 -0800841void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
842 MutexLock mu(classes_lock_);
843 typedef Table::const_iterator It; // TODO: C++0x auto
844 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
845 if (!visitor(it->second, arg)) {
846 return;
847 }
848 }
849 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
850 if (!visitor(it->second, arg)) {
851 return;
852 }
853 }
854}
855
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700856ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700857 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700858 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700859 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700860 BooleanArray::ResetArrayClass();
861 ByteArray::ResetArrayClass();
862 CharArray::ResetArrayClass();
863 DoubleArray::ResetArrayClass();
864 FloatArray::ResetArrayClass();
865 IntArray::ResetArrayClass();
866 LongArray::ResetArrayClass();
867 ShortArray::ResetArrayClass();
868 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700869 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700870 STLDeleteElements(&boot_class_path_);
871 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700872}
873
874DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700875 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
876 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700877 return NULL;
878 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700879 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
880 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700881 return NULL;
882 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700883 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
884 if (strings.get() == NULL) {
885 return NULL;
886 }
887 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
888 if (types.get() == NULL) {
889 return NULL;
890 }
891 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
892 if (methods.get() == NULL) {
893 return NULL;
894 }
895 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
896 if (fields.get() == NULL) {
897 return NULL;
898 }
899 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
900 if (code_and_direct_methods.get() == NULL) {
901 return NULL;
902 }
903 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
904 if (initialized_static_storage.get() == NULL) {
905 return NULL;
906 }
907
908 dex_cache->Init(location.get(),
909 strings.get(),
910 types.get(),
911 methods.get(),
912 fields.get(),
913 code_and_direct_methods.get(),
914 initialized_static_storage.get());
915 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700916}
917
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700918CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
919 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700920}
921
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700922InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
923 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700924 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
925 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700926 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700927 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700928}
929
Brian Carlstrom4873d462011-08-21 15:23:39 -0700930Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
931 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700932 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700933 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700934 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700935 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700936}
937
Brian Carlstrom4873d462011-08-21 15:23:39 -0700938Class* ClassLinker::AllocClass(size_t class_size) {
939 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700940}
941
Jesse Wilson35baaab2011-08-10 16:18:03 -0400942Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700943 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700944}
945
946Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700947 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700948}
949
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700950ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
951 return ObjectArray<StackTraceElement>::Alloc(
952 GetClassRoot(kJavaLangStackTraceElementArrayClass),
953 length);
954}
955
Brian Carlstromaded5f72011-10-07 17:15:04 -0700956Class* EnsureResolved(Class* klass) {
957 DCHECK(klass != NULL);
958 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700959 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700960 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700961 ObjectLock lock(klass);
962 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700963 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700964 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800965 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700966 return NULL;
967 }
968 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700969 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700970 lock.Wait();
971 }
972 }
973 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700974 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700975 return NULL;
976 }
977 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700978 CHECK(klass->IsResolved()) << PrettyClass(klass);
979 CHECK(!self->IsExceptionPending())
980 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
981 return klass;
982}
983
984Class* ClassLinker::FindClass(const std::string& descriptor,
985 const ClassLoader* class_loader) {
986 CHECK_NE(descriptor.size(), 0U);
987 Thread* self = Thread::Current();
988 DCHECK(self != NULL);
989 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800990 if (descriptor.size() == 1) {
991 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
992 // for primitive classes that aren't backed by dex files.
993 return FindPrimitiveClass(descriptor[0]);
994 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700995 // Find the class in the loaded classes table.
996 Class* klass = LookupClass(descriptor, class_loader);
997 if (klass != NULL) {
998 return EnsureResolved(klass);
999 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001000 // Class is not yet loaded.
1001 if (descriptor[0] == '[') {
1002 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001003
Jesse Wilson47daf872011-11-23 11:42:45 -05001004 } else if (class_loader == NULL) {
1005 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1006 if (pair.second != NULL) {
1007 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1008 }
1009
1010 } else if (ClassLoader::UseCompileTimeClassPath()) {
1011 // first try the boot class path
1012 Class* system_class = FindSystemClass(descriptor);
1013 if (system_class != NULL) {
1014 return system_class;
1015 }
1016 CHECK(self->IsExceptionPending());
1017 self->ClearException();
1018
1019 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001020 const std::vector<const DexFile*>& class_path
1021 = ClassLoader::GetCompileTimeClassPath(class_loader);
1022 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001023 if (pair.second != NULL) {
1024 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001025 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001026
1027 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001028 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001029 ScopedThreadStateChange(self, Thread::kNative);
1030 JNIEnv* env = self->GetJniEnv();
1031 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1032 CHECK(c.get() != NULL);
1033 // TODO: cache method?
1034 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1035 CHECK(mid != NULL);
1036 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1037 if (class_name_object.get() == NULL) {
1038 return NULL;
1039 }
1040 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1041 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
1042 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001043 }
1044
Jesse Wilson47daf872011-11-23 11:42:45 -05001045 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
1046 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001047}
1048
1049Class* ClassLinker::DefineClass(const std::string& descriptor,
1050 const ClassLoader* class_loader,
1051 const DexFile& dex_file,
1052 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001053 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001054 // Load the class from the dex file.
1055 if (!init_done_) {
1056 // finish up init of hand crafted class_roots_
1057 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001058 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001059 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001060 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001061 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001062 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001063 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001064 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001065 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001066 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001067 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001068 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001069 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001070 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001071 }
1072 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001073 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001074 }
1075 klass->SetDexCache(FindDexCache(dex_file));
1076 LoadClass(dex_file, dex_class_def, klass, class_loader);
1077 // Check for a pending exception during load
1078 Thread* self = Thread::Current();
1079 if (self->IsExceptionPending()) {
1080 return NULL;
1081 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001082 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001083 klass->SetClinitThreadId(self->GetTid());
1084 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001085 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001086 if (!success) {
1087 // We may fail to insert if we raced with another thread.
1088 klass->SetClinitThreadId(0);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001089 klass.reset(LookupClass(descriptor, class_loader));
1090 CHECK(klass.get() != NULL);
1091 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001092 }
1093 // Finish loading (if necessary) by finding parents
1094 CHECK(!klass->IsLoaded());
1095 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1096 // Loading failed.
1097 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001098 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001099 lock.NotifyAll();
1100 return NULL;
1101 }
1102 CHECK(klass->IsLoaded());
1103 // Link the class (if necessary)
1104 CHECK(!klass->IsResolved());
1105 if (!LinkClass(klass)) {
1106 // Linking failed.
1107 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001108 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001109 lock.NotifyAll();
1110 return NULL;
1111 }
1112 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001113
1114 /*
1115 * We send CLASS_PREPARE events to the debugger from here. The
1116 * definition of "preparation" is creating the static fields for a
1117 * class and initializing them to the standard default values, but not
1118 * executing any code (that comes later, during "initialization").
1119 *
1120 * We did the static preparation in LinkClass.
1121 *
1122 * The class has been prepared and resolved but possibly not yet verified
1123 * at this point.
1124 */
1125 Dbg::PostClassPrepare(klass.get());
1126
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001127 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001128}
1129
Brian Carlstrom4873d462011-08-21 15:23:39 -07001130// Precomputes size that will be needed for Class, matching LinkStaticFields
1131size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1132 const DexFile::ClassDef& dex_class_def) {
1133 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001134 size_t num_ref = 0;
1135 size_t num_32 = 0;
1136 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001137 if (class_data != NULL) {
1138 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1139 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001140 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001141 char c = descriptor[0];
1142 if (c == 'L' || c == '[') {
1143 num_ref++;
1144 } else if (c == 'J' || c == 'D') {
1145 num_64++;
1146 } else {
1147 num_32++;
1148 }
1149 }
1150 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001151 // start with generic class data
1152 size_t size = sizeof(Class);
1153 // follow with reference fields which must be contiguous at start
1154 size += (num_ref * sizeof(uint32_t));
1155 // if there are 64-bit fields to add, make sure they are aligned
1156 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1157 if (num_32 != 0) {
1158 // use an available 32-bit field for padding
1159 num_32--;
1160 }
1161 size += sizeof(uint32_t); // either way, we are adding a word
1162 DCHECK_EQ(size, RoundUp(size, 8));
1163 }
1164 // tack on any 64-bit fields now that alignment is assured
1165 size += (num_64 * sizeof(uint64_t));
1166 // tack on any remaining 32-bit fields
1167 size += (num_32 * sizeof(uint32_t));
1168 return size;
1169}
1170
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001171void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001172 // Every kind of method should at least get an invoke stub from the oat_method.
1173 // non-abstract methods also get their code pointers.
1174 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001175 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001176
1177 if (method->IsAbstract()) {
1178 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1179 return;
1180 }
1181 if (method->IsNative()) {
1182 // unregistering restores the dlsym lookup stub
1183 method->UnregisterNative();
1184 return;
1185 }
1186}
1187
Brian Carlstromf615a612011-07-23 12:50:34 -07001188void ClassLinker::LoadClass(const DexFile& dex_file,
1189 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001190 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001191 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001192 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001193 CHECK(klass->GetDexCache() != NULL);
1194 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001195 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001196 CHECK(descriptor != NULL);
1197
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001198 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001199 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001200 // Make sure that none of our runtime-only flags are set.
1201 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001202 klass->SetAccessFlags(access_flags);
1203 klass->SetClassLoader(class_loader);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001204 DCHECK(klass->GetPrimitiveType() == Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001205 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001206
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001207 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001208
Ian Rogers0571d352011-11-03 19:51:38 -07001209 // Load fields fields.
1210 const byte* class_data = dex_file.GetClassData(dex_class_def);
1211 if (class_data == NULL) {
1212 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001213 }
Ian Rogers0571d352011-11-03 19:51:38 -07001214 ClassDataItemIterator it(dex_file, class_data);
1215 if (it.NumStaticFields() != 0) {
1216 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1217 }
1218 if (it.NumInstanceFields() != 0) {
1219 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1220 }
1221 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1222 SirtRef<Field> sfield(AllocField());
1223 klass->SetStaticField(i, sfield.get());
1224 LoadField(dex_file, it, klass, sfield);
1225 }
1226 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1227 SirtRef<Field> ifield(AllocField());
1228 klass->SetInstanceField(i, ifield.get());
1229 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001230 }
1231
Brian Carlstromaded5f72011-10-07 17:15:04 -07001232 UniquePtr<const OatFile::OatClass> oat_class;
1233 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001234 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001235 if (oat_file != NULL) {
1236 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1237 if (oat_dex_file != NULL) {
1238 uint32_t class_def_index;
1239 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1240 CHECK(found) << descriptor;
1241 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001242 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001243 }
1244 }
1245 }
Ian Rogers0571d352011-11-03 19:51:38 -07001246 // Load methods.
1247 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001248 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001249 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001250 }
Ian Rogers0571d352011-11-03 19:51:38 -07001251 if (it.NumVirtualMethods() != 0) {
1252 // TODO: append direct methods to class object
1253 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001254 }
Ian Rogers0571d352011-11-03 19:51:38 -07001255 size_t method_index = 0;
1256 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1257 SirtRef<Method> method(AllocMethod());
1258 klass->SetDirectMethod(i, method.get());
1259 LoadMethod(dex_file, it, klass, method);
1260 if (oat_class.get() != NULL) {
1261 LinkCode(method, oat_class.get(), method_index);
1262 }
1263 method_index++;
1264 }
1265 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1266 SirtRef<Method> method(AllocMethod());
1267 klass->SetVirtualMethod(i, method.get());
1268 LoadMethod(dex_file, it, klass, method);
1269 if (oat_class.get() != NULL) {
1270 LinkCode(method, oat_class.get(), method_index);
1271 }
1272 method_index++;
1273 }
1274 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001275}
1276
Ian Rogers0571d352011-11-03 19:51:38 -07001277void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1278 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001279 uint32_t field_idx = it.GetMemberIndex();
1280 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001281 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001282 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001283}
1284
Ian Rogers0571d352011-11-03 19:51:38 -07001285void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1286 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001287 uint32_t method_idx = it.GetMemberIndex();
1288 dst->SetDexMethodIndex(method_idx);
1289 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001290 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001291
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001292
1293 StringPiece method_name(dex_file.GetMethodName(method_id));
1294 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001295 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1296 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001297
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001298 if (method_name == "finalize") {
1299 // Create the prototype for a signature of "()V"
1300 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1301 if (void_string_id != NULL) {
1302 const DexFile::TypeId* void_type_id =
1303 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1304 if (void_type_id != NULL) {
1305 std::vector<uint16_t> no_args;
1306 const DexFile::ProtoId* finalizer_proto =
1307 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1308 if (finalizer_proto != NULL) {
1309 // We have the prototype in the dex file
1310 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1311 klass->SetFinalizable();
1312 } else {
1313 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1314 // The Enum class declares a "final" finalize() method to prevent subclasses from
1315 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1316 // subclasses, so we exclude it here.
1317 // We also want to avoid setting the flag on Object, where we know that finalize() is
1318 // empty.
1319 if (klass_descriptor != "Ljava/lang/Object;" &&
1320 klass_descriptor != "Ljava/lang/Enum;") {
1321 klass->SetFinalizable();
1322 }
1323 }
1324 }
1325 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001326 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001327 }
Ian Rogers0571d352011-11-03 19:51:38 -07001328 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001329 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001330
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001331 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1332 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1333 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1334 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1335 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1336 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001337
Brian Carlstrom934486c2011-07-12 23:42:50 -07001338 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001339}
1340
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001341void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001342 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1343 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001344}
1345
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001346void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1347 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001348 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001349 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001350}
1351
Brian Carlstromaded5f72011-10-07 17:15:04 -07001352bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001353 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001354 for (size_t i = 0; i != dex_files_.size(); ++i) {
1355 if (dex_files_[i] == &dex_file) {
1356 return true;
1357 }
1358 }
1359 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001360}
1361
Brian Carlstromaded5f72011-10-07 17:15:04 -07001362bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001363 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001364 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001365}
1366
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001367void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001368 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001369 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001370 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001371 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001372 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001373}
1374
Brian Carlstromaded5f72011-10-07 17:15:04 -07001375void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001376 {
1377 MutexLock mu(dex_lock_);
1378 if (IsDexFileRegisteredLocked(dex_file)) {
1379 return;
1380 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001381 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001382 // Don't alloc while holding the lock, since allocation may need to
1383 // suspend all threads and another thread may need the dex_lock_ to
1384 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001385 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001386 {
1387 MutexLock mu(dex_lock_);
1388 if (IsDexFileRegisteredLocked(dex_file)) {
1389 return;
1390 }
1391 RegisterDexFileLocked(dex_file, dex_cache);
1392 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001393}
1394
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001395void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001396 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001397 RegisterDexFileLocked(dex_file, dex_cache);
1398}
1399
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001400const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001401 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001402 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001403 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1404 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001405 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001406 }
1407 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001408 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001409 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001410}
1411
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001412DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001413 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001414 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001415 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001416 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001417 }
1418 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001419 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001420 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001421}
1422
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001423Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1424 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001425 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001426 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001427 CHECK(primitive_class != NULL);
1428 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001429 primitive_class->SetPrimitiveType(type);
1430 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001431 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001432 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1433 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001434}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001435
Brian Carlstrombe977852011-07-19 14:54:54 -07001436// Create an array class (i.e. the class object for the array, not the
1437// array itself). "descriptor" looks like "[C" or "[[[[B" or
1438// "[Ljava/lang/String;".
1439//
1440// If "descriptor" refers to an array of primitives, look up the
1441// primitive type's internally-generated class object.
1442//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001443// "class_loader" is the class loader of the class that's referring to
1444// us. It's used to ensure that we're looking for the element type in
1445// the right context. It does NOT become the class loader for the
1446// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001447//
1448// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001449Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001450 const ClassLoader* class_loader) {
1451 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001452
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001453 // Identify the underlying component type
1454 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001455 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001456 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001457 return NULL;
1458 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001459
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001460 // See if the component type is already loaded. Array classes are
1461 // always associated with the class loader of their underlying
1462 // element type -- an array of Strings goes with the loader for
1463 // java/lang/String -- so we need to look for it there. (The
1464 // caller should have checked for the existence of the class
1465 // before calling here, but they did so with *their* class loader,
1466 // not the component type's loader.)
1467 //
1468 // If we find it, the caller adds "loader" to the class' initiating
1469 // loader list, which should prevent us from going through this again.
1470 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001471 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001472 // are the same, because our caller (FindClass) just did the
1473 // lookup. (Even if we get this wrong we still have correct behavior,
1474 // because we effectively do this lookup again when we add the new
1475 // class to the hash table --- necessary because of possible races with
1476 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001477 if (class_loader != component_type->GetClassLoader()) {
1478 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001479 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001480 return new_class;
1481 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001482 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001483
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001484 // Fill out the fields in the Class.
1485 //
1486 // It is possible to execute some methods against arrays, because
1487 // all arrays are subclasses of java_lang_Object_, so we need to set
1488 // up a vtable. We can just point at the one in java_lang_Object_.
1489 //
1490 // Array classes are simple enough that we don't need to do a full
1491 // link step.
1492
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001493 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001494 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001495 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001496 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001497 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001498 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001499 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001500 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001501 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001502 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001503 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001504 }
1505 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001506 if (new_class.get() == NULL) {
1507 new_class.reset(AllocClass(sizeof(Class)));
1508 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001509 return NULL;
1510 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001511 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001512 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001513 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001514 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001515 new_class->SetSuperClass(java_lang_Object);
1516 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001517 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001518 new_class->SetClassLoader(component_type->GetClassLoader());
1519 new_class->SetStatus(Class::kStatusInitialized);
1520 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001521 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001522
1523
1524 // All arrays have java/lang/Cloneable and java/io/Serializable as
1525 // interfaces. We need to set that up here, so that stuff like
1526 // "instanceof" works right.
1527 //
1528 // Note: The GC could run during the call to FindSystemClass,
1529 // so we need to make sure the class object is GC-valid while we're in
1530 // there. Do this by clearing the interface list so the GC will just
1531 // think that the entries are null.
1532
1533
1534 // Use the single, global copies of "interfaces" and "iftable"
1535 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001536 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001537 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001538
1539 // Inherit access flags from the component type. Arrays can't be
1540 // used as a superclass or interface, so we want to add "final"
1541 // and remove "interface".
1542 //
1543 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001544 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001545 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001546 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1547 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001548
Ian Rogers5d76c432011-10-31 21:42:49 -07001549 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001550 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001551 }
1552 // Another thread must have loaded the class after we
1553 // started but before we finished. Abandon what we've
1554 // done.
1555 //
1556 // (Yes, this happens.)
1557
1558 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001559 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001560 DCHECK(other_class != NULL);
1561 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001562}
1563
1564Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001565 switch (Primitive::GetType(type)) {
1566 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001567 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001568 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001569 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001570 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001571 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001572 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001573 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001574 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001575 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001576 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001577 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001578 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001579 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001580 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001581 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001582 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001583 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001584 case Primitive::kPrimNot:
1585 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001586 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001587 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001588 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001589 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001590}
1591
Ian Rogers5d76c432011-10-31 21:42:49 -07001592bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001593 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001594 DexCache* dex_cache = klass->GetDexCache();
1595 std::string source;
1596 if (dex_cache != NULL) {
1597 source += " from ";
1598 source += dex_cache->GetLocation()->ToModifiedUtf8();
1599 }
1600 LOG(INFO) << "Loaded class " << descriptor << source;
1601 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001602 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001603 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001604 Table::iterator it;
1605 if (image_class) {
1606 // TODO: sanity check there's no match in classes_
1607 it = image_classes_.insert(std::make_pair(hash, klass));
1608 } else {
1609 // TODO: sanity check there's no match in image_classes_
1610 it = classes_.insert(std::make_pair(hash, klass));
1611 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001612 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001613}
1614
Brian Carlstromae826982011-11-09 01:33:42 -08001615bool ClassLinker::RemoveClass(const std::string& descriptor, const ClassLoader* class_loader) {
1616 size_t hash = StringPieceHash()(descriptor);
1617 MutexLock mu(classes_lock_);
1618 typedef Table::const_iterator It; // TODO: C++0x auto
1619 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001620 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001621 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1622 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001623 kh.ChangeClass(klass);
1624 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001625 classes_.erase(it);
1626 return true;
1627 }
1628 }
1629 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1630 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001631 kh.ChangeClass(klass);
1632 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001633 image_classes_.erase(it);
1634 return true;
1635 }
1636 }
1637 return false;
1638}
1639
Brian Carlstromaded5f72011-10-07 17:15:04 -07001640Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001641 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001642 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001643 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001644 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001645 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001646 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001647 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001648 kh.ChangeClass(klass);
1649 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001650 return klass;
1651 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001652 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001653 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1654 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001655 kh.ChangeClass(klass);
1656 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001657 return klass;
1658 }
1659 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001660 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001661}
1662
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001663void ClassLinker::LookupClasses(const std::string& descriptor, std::vector<Class*>& classes) {
1664 classes.clear();
1665 size_t hash = StringPieceHash()(descriptor);
1666 MutexLock mu(classes_lock_);
1667 typedef Table::const_iterator It; // TODO: C++0x auto
1668 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001669 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001670 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001671 Class* klass = it->second;
1672 kh.ChangeClass(klass);
1673 if (descriptor == kh.GetDescriptor()) {
1674 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001675 }
1676 }
1677 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001678 Class* klass = it->second;
1679 kh.ChangeClass(klass);
1680 if (descriptor == kh.GetDescriptor()) {
1681 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001682 }
1683 }
1684}
1685
jeffhao98eacac2011-09-14 16:11:53 -07001686void ClassLinker::VerifyClass(Class* klass) {
1687 if (klass->IsVerified()) {
1688 return;
1689 }
1690
1691 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001692 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001693
Ian Rogersd81871c2011-10-03 13:57:23 -07001694 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001695 klass->SetStatus(Class::kStatusVerified);
1696 } else {
1697 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001698 Thread* self = Thread::Current();
1699 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1700 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001701 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001702 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001703 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001704 }
jeffhao98eacac2011-09-14 16:11:53 -07001705}
1706
Jesse Wilson95caa792011-10-12 18:14:17 -04001707Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001708 ClassLoader* loader, ObjectArray<Method>* methods,
1709 ObjectArray<ObjectArray<Class> >* throws) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001710 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass)));
1711 CHECK(klass.get() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001712 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001713 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001714 klass->SetClassLoader(loader);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001715 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001716 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001717 klass->SetDexCache(proxy_class->GetDexCache());
1718 klass->SetDexTypeIndex(-1);
Ian Rogers466bb252011-10-14 03:29:56 -07001719 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001720 klass->SetStatus(Class::kStatusInitialized); // no loading or initializing necessary
Jesse Wilson95caa792011-10-12 18:14:17 -04001721
Ian Rogers466bb252011-10-14 03:29:56 -07001722 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001723 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001724 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001725
Ian Rogers466bb252011-10-14 03:29:56 -07001726 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001727 size_t num_virtual_methods = methods->GetLength();
1728 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1729 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001730 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001731 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001732 }
Ian Rogers466bb252011-10-14 03:29:56 -07001733 // Link the virtual methods, creating vtable and iftables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001734 if (!LinkMethods(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001735 DCHECK(Thread::Current()->IsExceptionPending());
1736 return NULL;
1737 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001738 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001739}
1740
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001741std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1742 DCHECK(proxy_class->IsProxyClass());
1743 String* name = proxy_class->GetName();
1744 DCHECK(name != NULL);
1745 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1746}
1747
1748
1749Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001750 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001751 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001752 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001753 Method* proxy_constructor = proxy_direct_methods->Get(2);
1754 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1755 // code_ too)
1756 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1757 // Make this constructor public and fix the class to be our Proxy version
1758 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001759 constructor->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001760 // Sanity checks
1761 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001762 MethodHelper mh(constructor);
1763 CHECK_STREQ(mh.GetName(), "<init>");
1764 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001765 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001766 return constructor;
1767}
1768
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001769Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1770 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1771 // prototype method
1772 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1773 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001774 // as necessary
1775 Method* method = down_cast<Method*>(prototype->Clone());
1776
1777 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1778 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001779 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001780 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001781
Ian Rogers466bb252011-10-14 03:29:56 -07001782 // At runtime the method looks like a reference and argument saving method, clone the code
1783 // related parameters from this method.
1784 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1785 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1786 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1787 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1788 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Jesse Wilson95caa792011-10-12 18:14:17 -04001789
Ian Rogers466bb252011-10-14 03:29:56 -07001790 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001791 CHECK(!prototype->IsFinal());
1792 CHECK(method->IsFinal());
1793 CHECK(!method->IsAbstract());
1794 MethodHelper mh(method);
1795 const char* method_name = mh.GetName();
1796 const char* method_shorty = mh.GetShorty();
1797 Class* method_return = mh.GetReturnType();
1798
1799 mh.ChangeMethod(prototype.get());
1800
1801 CHECK_STREQ(mh.GetName(), method_name);
1802 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001803
1804 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001805 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001806
1807 return method;
1808}
1809
Brian Carlstrom25c33252011-09-18 15:58:35 -07001810bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001811 CHECK(klass->IsResolved() || klass->IsErroneous())
1812 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001813
Carl Shapirob5573532011-07-12 18:22:59 -07001814 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001815
Brian Carlstrom25c33252011-09-18 15:58:35 -07001816 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001817 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001818 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001819 ObjectLock lock(klass);
1820
Brian Carlstromd1422f82011-09-28 11:37:09 -07001821 if (klass->GetStatus() == Class::kStatusInitialized) {
1822 return true;
1823 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001824
Brian Carlstromd1422f82011-09-28 11:37:09 -07001825 if (klass->IsErroneous()) {
1826 ThrowEarlierClassFailure(klass);
1827 return false;
1828 }
1829
1830 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001831 VerifyClass(klass);
1832 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001833 return false;
1834 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001835 }
1836
Brian Carlstrom25c33252011-09-18 15:58:35 -07001837 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1838 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001839 // if the class has a <clinit> but we can't run it during compilation,
1840 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001841 return false;
1842 }
1843
Brian Carlstromd1422f82011-09-28 11:37:09 -07001844 // If the class is kStatusInitializing, either this thread is
1845 // initializing higher up the stack or another thread has beat us
1846 // to initializing and we need to wait. Either way, this
1847 // invocation of InitializeClass will not be responsible for
1848 // running <clinit> and will return.
1849 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001850 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001851 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001852 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001853 return true;
1854 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001855 // No. That's fine. Wait for another thread to finish initializing.
1856 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001857 }
1858
1859 if (!ValidateSuperClassDescriptors(klass)) {
1860 klass->SetStatus(Class::kStatusError);
1861 return false;
1862 }
1863
Brian Carlstromd1422f82011-09-28 11:37:09 -07001864 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001865
Elliott Hughesdcc24742011-09-07 14:02:44 -07001866 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001867 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001868 }
1869
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001870 uint64_t t0 = NanoTime();
1871
Brian Carlstrom25c33252011-09-18 15:58:35 -07001872 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001873 return false;
1874 }
1875
1876 InitializeStaticFields(klass);
1877
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001878 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001879 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001880 }
1881
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001882 uint64_t t1 = NanoTime();
1883
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001884 {
1885 ObjectLock lock(klass);
1886
1887 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001888 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001889 klass->SetStatus(Class::kStatusError);
1890 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001891 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1892 RuntimeStats* thread_stats = self->GetStats();
1893 ++global_stats->class_init_count;
1894 ++thread_stats->class_init_count;
1895 global_stats->class_init_time_ns += (t1 - t0);
1896 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001897 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001898 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001899 ClassHelper kh(klass);
1900 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08001901 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001902 }
1903 lock.NotifyAll();
1904 }
1905
1906 return true;
1907}
1908
Brian Carlstromd1422f82011-09-28 11:37:09 -07001909bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1910 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001911 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001912 lock.Wait();
1913
1914 // When we wake up, repeat the test for init-in-progress. If
1915 // there's an exception pending (only possible if
1916 // "interruptShouldThrow" was set), bail out.
1917 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001918 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001919 klass->SetStatus(Class::kStatusError);
1920 return false;
1921 }
1922 // Spurious wakeup? Go back to waiting.
1923 if (klass->GetStatus() == Class::kStatusInitializing) {
1924 continue;
1925 }
1926 if (klass->IsErroneous()) {
1927 // The caller wants an exception, but it was thrown in a
1928 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001929 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001930 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001931 return false;
1932 }
1933 if (klass->IsInitialized()) {
1934 return true;
1935 }
1936 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1937 }
1938 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1939}
1940
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001941bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1942 if (klass->IsInterface()) {
1943 return true;
1944 }
1945 // begin with the methods local to the superclass
1946 if (klass->HasSuperClass() &&
1947 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1948 const Class* super = klass->GetSuperClass();
1949 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001950 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001951 if (method != super->GetVirtualMethod(i) &&
1952 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001953 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1954
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001955 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
1956 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
1957 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001958 return false;
1959 }
1960 }
1961 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001962 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1963 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1964 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001965 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1966 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001967 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001968 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001969 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001970 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1971
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001972 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
1973 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
1974 PrettyMethod(method).c_str(),
1975 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001976 return false;
1977 }
1978 }
1979 }
1980 }
1981 return true;
1982}
1983
1984bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001985 const Class* klass1,
1986 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07001987 if (klass1 == klass2) {
1988 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07001989 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001990 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001991 const DexFile::ProtoId& proto_id =
1992 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07001993 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
1994 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001995 if (descriptor == NULL) {
1996 break;
1997 }
1998 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1999 // Found a non-primitive type.
2000 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2001 return false;
2002 }
2003 }
2004 }
2005 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002006 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002007 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002008 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002009 return false;
2010 }
2011 }
2012 return true;
2013}
2014
2015// Returns true if classes referenced by the descriptor are the
2016// same classes in klass1 as they are in klass2.
2017bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002018 const Class* klass1,
2019 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 CHECK(descriptor != NULL);
2021 CHECK(klass1 != NULL);
2022 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002023 if (klass1 == klass2) {
2024 return true;
2025 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002026 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002027 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002028 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002029 // TODO: found2 == NULL
2030 // TODO: lookup found1 in initiating loader list
2031 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002032 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002033 return found1 == found2;
2034 } else {
2035 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002036 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002037}
2038
Brian Carlstrom25c33252011-09-18 15:58:35 -07002039bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002040 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 if (!klass->IsInterface() && klass->HasSuperClass()) {
2042 Class* super_class = klass->GetSuperClass();
2043 if (super_class->GetStatus() != Class::kStatusInitialized) {
2044 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002045 Thread* self = Thread::Current();
2046 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002047 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002048 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002049 // TODO: check for a pending exception
2050 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002051 if (!can_run_clinit) {
2052 // Don't set status to error when we can't run <clinit>.
2053 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2054 klass->SetStatus(Class::kStatusVerified);
2055 return false;
2056 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002057 klass->SetStatus(Class::kStatusError);
2058 klass->NotifyAll();
2059 return false;
2060 }
2061 }
2062 }
2063 return true;
2064}
2065
Brian Carlstrom25c33252011-09-18 15:58:35 -07002066bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002067 CHECK(c != NULL);
2068 if (c->IsInitialized()) {
2069 return true;
2070 }
2071
Elliott Hughes5f791332011-09-15 17:45:30 -07002072 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002073 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002074 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002075 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002076}
2077
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002078void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002079 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002080 const ClassLoader* cl = c->GetClassLoader();
2081 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002082 ClassDataItemIterator it(dex_file, class_data);
2083 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2084 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002085 }
2086}
2087
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002088void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002089 size_t num_static_fields = klass->NumStaticFields();
2090 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002091 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002092 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002093 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002094 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002095 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002096 return;
2097 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002098 ClassHelper kh(klass);
2099 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002100 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002101 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002102 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002103
Ian Rogers0571d352011-11-03 19:51:38 -07002104 if (it.HasNext()) {
2105 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2106 std::map<uint32_t, Field*> field_map;
2107 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2108 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2109 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002110 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002111 }
2112}
2113
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002114bool ClassLinker::LinkClass(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002115 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002116 if (!LinkSuperClass(klass)) {
2117 return false;
2118 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002119 if (!LinkMethods(klass, NULL)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002120 return false;
2121 }
2122 if (!LinkInstanceFields(klass)) {
2123 return false;
2124 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002125 if (!LinkStaticFields(klass)) {
2126 return false;
2127 }
2128 CreateReferenceInstanceOffsets(klass);
2129 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002130 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2131 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002132 return true;
2133}
2134
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002135bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002136 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002137 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2138 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2139 if (class_def == NULL) {
2140 return false;
2141 }
2142 uint16_t super_class_idx = class_def->superclass_idx_;
2143 if (super_class_idx != DexFile::kDexNoIndex16) {
2144 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002145 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002146 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002147 return false;
2148 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002149 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002150 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002151 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2152 if (interfaces != NULL) {
2153 for (size_t i = 0; i < interfaces->Size(); i++) {
2154 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2155 Class* interface = ResolveType(dex_file, idx, klass.get());
2156 if (interface == NULL) {
2157 DCHECK(Thread::Current()->IsExceptionPending());
2158 return false;
2159 }
2160 // Verify
2161 if (!klass->CanAccess(interface)) {
2162 // TODO: the RI seemed to ignore this in my testing.
2163 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2164 "Interface %s implemented by class %s is inaccessible",
2165 PrettyDescriptor(interface).c_str(),
2166 PrettyDescriptor(klass.get()).c_str());
2167 return false;
2168 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002169 }
2170 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002171 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002172 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002173 return true;
2174}
2175
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002176bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002177 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002178 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002179 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002180 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002181 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002182 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002183 return false;
2184 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002185 return true;
2186 }
2187 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002188 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002189 return false;
2190 }
2191 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002192 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002193 Thread* thread = Thread::Current();
2194 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002195 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002196 PrettyDescriptor(super).c_str(),
2197 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002198 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002199 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002200 return false;
2201 }
2202 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002203 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002204 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002205 PrettyDescriptor(super).c_str(),
2206 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002207 return false;
2208 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002209
2210 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2211 if (super->IsFinalizable()) {
2212 klass->SetFinalizable();
2213 }
2214
Elliott Hughes2da50362011-10-10 16:57:08 -07002215 // Inherit reference flags (if any) from the superclass.
2216 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2217 if (reference_flags != 0) {
2218 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2219 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002220 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002221 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002222 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002223 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002224 return false;
2225 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002226
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002227#ifndef NDEBUG
2228 // Ensure super classes are fully resolved prior to resolving fields..
2229 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002230 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002231 super = super->GetSuperClass();
2232 }
2233#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002234 return true;
2235}
2236
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002237// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002238bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002239 if (klass->IsInterface()) {
2240 // No vtable.
2241 size_t count = klass->NumVirtualMethods();
2242 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002243 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002244 return false;
2245 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002246 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002247 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002248 }
jeffhaobdb76512011-09-07 11:43:16 -07002249 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002250 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002251 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002252 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002253 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002254 }
2255 return true;
2256}
2257
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002258bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002259 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002260 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2261 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002262 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002263 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002264 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002266 MethodHelper local_mh(NULL, this);
2267 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002268 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002269 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002270 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002271 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002272 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002273 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002274 super_mh.ChangeMethod(super_method);
2275 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002276 // Verify
2277 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002278 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002279 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002280 PrettyDescriptor(klass.get()).c_str(),
2281 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002282 return false;
2283 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002284 vtable->Set(j, local_method);
2285 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002286 break;
2287 }
2288 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002289 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002290 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002291 vtable->Set(actual_count, local_method);
2292 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002293 actual_count += 1;
2294 }
2295 }
2296 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002297 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002298 return false;
2299 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002300 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002301 CHECK_LE(actual_count, max_count);
2302 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002303 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002304 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002305 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002306 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002307 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002308 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002309 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002310 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002311 return false;
2312 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002313 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002314 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002315 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2316 vtable->Set(i, virtual_method);
2317 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002318 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002319 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002320 }
2321 return true;
2322}
2323
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002324bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002325 size_t super_ifcount;
2326 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002327 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002328 } else {
2329 super_ifcount = 0;
2330 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002331 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002332 ClassHelper kh(klass.get(), this);
2333 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2334 ifcount += num_interfaces;
2335 for (size_t i = 0; i < num_interfaces; i++) {
2336 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2337 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002338 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002339 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002340 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002341 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002342 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002343 return true;
2344 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002345 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002346 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002347 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2348 for (size_t i = 0; i < super_ifcount; i++) {
2349 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2350 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002351 }
2352 // Flatten the interface inheritance hierarchy.
2353 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002354 for (size_t i = 0; i < num_interfaces; i++) {
2355 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002356 DCHECK(interface != NULL);
2357 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002358 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002359 Thread* thread = Thread::Current();
2360 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002361 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002362 PrettyDescriptor(klass.get()).c_str(),
2363 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002364 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002365 return false;
2366 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002367 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002368 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002369 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002370 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2371 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002372 }
2373 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002374 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002375 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002376
2377 // If we're an interface, we don't need the vtable pointers, so we're done.
2378 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002379 return true;
2380 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002381 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002382 MethodHelper vtable_mh(NULL, this);
2383 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002384 for (size_t i = 0; i < ifcount; ++i) {
2385 InterfaceEntry* interface_entry = iftable->Get(i);
2386 Class* interface = interface_entry->GetInterface();
2387 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2388 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002389 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002390 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2391 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002392 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002393 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002394 // For each method listed in the interface's method list, find the
2395 // matching method in our class's method list. We want to favor the
2396 // subclass over the superclass, which just requires walking
2397 // back from the end of the vtable. (This only matters if the
2398 // superclass defines a private method and this class redefines
2399 // it -- otherwise it would use the same vtable slot. In .dex files
2400 // those don't end up in the virtual method table, so it shouldn't
2401 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002402 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2403 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002404 vtable_mh.ChangeMethod(vtable_method);
2405 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002406 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002407 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002408 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002409 return false;
2410 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002411 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002412 break;
2413 }
2414 }
2415 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002416 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002417 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002418 Method* mir_method = miranda_list[mir];
2419 vtable_mh.ChangeMethod(mir_method);
2420 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002421 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002422 break;
2423 }
2424 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002425 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002426 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002427 miranda_method.reset(AllocMethod());
2428 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2429 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002431 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002432 }
2433 }
2434 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002435 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002436 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002437 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002438 klass->SetVirtualMethods((old_method_count == 0)
2439 ? AllocObjectArray<Method>(new_method_count)
2440 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002441
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002442 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2443 CHECK(vtable != NULL);
2444 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002445 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002446 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002447 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002448 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002449 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002450 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2451 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2452 klass->SetVirtualMethod(old_method_count + i, method);
2453 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002454 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002455 // TODO: do not assign to the vtable field until it is fully constructed.
2456 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002457 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002458
2459 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2460 for (int i = 0; i < vtable->GetLength(); ++i) {
2461 CHECK(vtable->Get(i) != NULL);
2462 }
2463
2464// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2465
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002466 return true;
2467}
2468
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002469bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2470 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002471 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002472}
2473
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002474bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2475 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002476 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002477 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002478 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002479 return success;
2480}
2481
Brian Carlstromdbc05252011-09-09 01:59:59 -07002482struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002483 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002484 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002485 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002486 fh_->ChangeField(field1);
2487 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2488 fh_->ChangeField(field2);
2489 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002490 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2491 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2492 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2493 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002494 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2495 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2496 if (order1 != order2) {
2497 return order1 < order2;
2498 }
2499
2500 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002501 fh_->ChangeField(field1);
2502 StringPiece name1(fh_->GetName());
2503 fh_->ChangeField(field2);
2504 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002505 return name1 < name2;
2506 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002507
2508 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002509};
2510
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002511bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002512 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002513 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002514
2515 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002516 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002517
2518 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002519 size_t size;
2520 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002521 if (is_static) {
2522 size = klass->GetClassSize();
2523 field_offset = Class::FieldsOffset();
2524 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002525 Class* super_class = klass->GetSuperClass();
2526 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002527 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002528 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002529 }
2530 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002531 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002532
Brian Carlstromdbc05252011-09-09 01:59:59 -07002533 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002534
Brian Carlstromdbc05252011-09-09 01:59:59 -07002535 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002536 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002537 std::deque<Field*> grouped_and_sorted_fields;
2538 for (size_t i = 0; i < num_fields; i++) {
2539 grouped_and_sorted_fields.push_back(fields->Get(i));
2540 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002541 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002542 std::sort(grouped_and_sorted_fields.begin(),
2543 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002544 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002545
2546 // References should be at the front.
2547 size_t current_field = 0;
2548 size_t num_reference_fields = 0;
2549 for (; current_field < num_fields; current_field++) {
2550 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002551 fh.ChangeField(field);
2552 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002553 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002554 if (isPrimitive) {
2555 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002556 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002557 grouped_and_sorted_fields.pop_front();
2558 num_reference_fields++;
2559 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002560 field->SetOffset(field_offset);
2561 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002562 }
2563
2564 // Now we want to pack all of the double-wide fields together. If
2565 // we're not aligned, though, we want to shuffle one 32-bit field
2566 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002567 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002568 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2569 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002570 fh.ChangeField(field);
2571 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002572 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2573 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002574 continue;
2575 }
2576 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002578 // drop the consumed field
2579 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2580 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002581 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002582 // whether we found a 32-bit field for padding or not, we advance
2583 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 }
2585
2586 // Alignment is good, shuffle any double-wide fields forward, and
2587 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002588 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002589 while (!grouped_and_sorted_fields.empty()) {
2590 Field* field = grouped_and_sorted_fields.front();
2591 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002592 fh.ChangeField(field);
2593 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002594 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002595 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002596 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002597 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002598 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002599 ? sizeof(uint64_t)
2600 : sizeof(uint32_t)));
2601 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002602 }
2603
Elliott Hughesadb460d2011-10-05 17:02:34 -07002604 // 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 -08002605 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2606 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002607 // We know there are no non-reference fields in the Reference classes, and we know
2608 // that 'referent' is alphabetically last, so this is easy...
2609 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002610 fh.ChangeField(fields->Get(num_fields - 1));
2611 StringPiece name(fh.GetName());
2612 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002613 --num_reference_fields;
2614 }
2615
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002616#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002617 // Make sure that all reference fields appear before
2618 // non-reference fields, and all double-wide fields are aligned.
2619 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002620 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002621 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002622 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002623 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002624 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002625 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002626 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2627 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002628 fh.ChangeField(field);
2629 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002630 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002631 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002632 is_primitive = true; // We lied above, so we have to expect a lie here.
2633 }
2634 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002635 if (!seen_non_ref) {
2636 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002637 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002638 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002639 } else {
2640 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002641 }
2642 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002643 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002644 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002645 }
2646#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002647 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002648 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002649 if (is_static) {
2650 klass->SetNumReferenceStaticFields(num_reference_fields);
2651 klass->SetClassSize(size);
2652 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002653 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002654 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002655 klass->SetObjectSize(size);
2656 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002657 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002658 return true;
2659}
2660
2661// Set the bitmap of reference offsets, refOffsets, from the ifields
2662// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002663void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002664 uint32_t reference_offsets = 0;
2665 Class* super_class = klass->GetSuperClass();
2666 if (super_class != NULL) {
2667 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002668 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002669 if (reference_offsets == CLASS_WALK_SUPER) {
2670 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002671 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002672 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002673 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002674 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002675}
2676
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002677void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002678 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002679}
2680
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002681void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002682 uint32_t reference_offsets) {
2683 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002684 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2685 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002686 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002687 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002688 // All of the fields that contain object references are guaranteed
2689 // to be at the beginning of the fields list.
2690 for (size_t i = 0; i < num_reference_fields; ++i) {
2691 // Note that byte_offset is the offset from the beginning of
2692 // object, not the offset into instance data
2693 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002694 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002695 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2696 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2697 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002698 CHECK_NE(new_bit, 0U);
2699 reference_offsets |= new_bit;
2700 } else {
2701 reference_offsets = CLASS_WALK_SUPER;
2702 break;
2703 }
2704 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002705 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002706 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002707 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002708 } else {
2709 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002710 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002711}
2712
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002713String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002714 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002715 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002716 if (resolved != NULL) {
2717 return resolved;
2718 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002719 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2720 int32_t utf16_length = dex_file.GetStringLength(string_id);
2721 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002722 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002723 dex_cache->SetResolvedString(string_idx, string);
2724 return string;
2725}
2726
2727Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002728 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002729 DexCache* dex_cache,
2730 const ClassLoader* class_loader) {
2731 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002732 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002733 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002734 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002735 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002736 // TODO: we used to throw here if resolved's class loader was not the
2737 // boot class loader. This was to permit different classes with the
2738 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002739 dex_cache->SetResolvedType(type_idx, resolved);
2740 } else {
2741 DCHECK(Thread::Current()->IsExceptionPending());
2742 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002743 }
2744 return resolved;
2745}
2746
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002747Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2748 uint32_t method_idx,
2749 DexCache* dex_cache,
2750 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002751 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002752 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2753 if (resolved != NULL) {
2754 return resolved;
2755 }
2756 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2757 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2758 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002759 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002760 return NULL;
2761 }
2762
Ian Rogers0571d352011-11-03 19:51:38 -07002763 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2764 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002765 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002766 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002767 } else if (klass->IsInterface()) {
2768 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002769 } else {
2770 resolved = klass->FindVirtualMethod(name, signature);
2771 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002772 if (resolved != NULL) {
2773 dex_cache->SetResolvedMethod(method_idx, resolved);
2774 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002775 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002776 }
2777 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002778}
2779
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002780Field* ClassLinker::ResolveField(const DexFile& dex_file,
2781 uint32_t field_idx,
2782 DexCache* dex_cache,
2783 const ClassLoader* class_loader,
2784 bool is_static) {
2785 Field* resolved = dex_cache->GetResolvedField(field_idx);
2786 if (resolved != NULL) {
2787 return resolved;
2788 }
2789 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2790 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2791 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002792 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002793 return NULL;
2794 }
2795
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002796 const char* name = dex_file.GetFieldName(field_id);
2797 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002798 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002799 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002800 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002801 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002802 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002803 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002804 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002805 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002806 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2807 }
2808 return resolved;
2809}
2810
2811Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2812 uint32_t field_idx,
2813 DexCache* dex_cache,
2814 const ClassLoader* class_loader) {
2815 Field* resolved = dex_cache->GetResolvedField(field_idx);
2816 if (resolved != NULL) {
2817 return resolved;
2818 }
2819 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2820 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2821 if (klass == NULL) {
2822 DCHECK(Thread::Current()->IsExceptionPending());
2823 return NULL;
2824 }
2825
2826 const char* name = dex_file.GetFieldName(field_id);
2827 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
2828 resolved = klass->FindField(name, type);
2829 if (resolved != NULL) {
2830 dex_cache->SetResolvedField(field_idx, resolved);
2831 } else {
2832 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002833 }
2834 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002835}
2836
Ian Rogersad25ac52011-10-04 19:13:33 -07002837const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2838 Class* declaring_class = referrer->GetDeclaringClass();
2839 DexCache* dex_cache = declaring_class->GetDexCache();
2840 const DexFile& dex_file = FindDexFile(dex_cache);
2841 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2842 return dex_file.GetShorty(method_id.proto_idx_);
2843}
2844
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002845void ClassLinker::DumpAllClasses(int flags) const {
2846 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2847 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2848 std::vector<Class*> all_classes;
2849 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002850 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002851 typedef Table::const_iterator It; // TODO: C++0x auto
2852 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2853 all_classes.push_back(it->second);
2854 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002855 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2856 all_classes.push_back(it->second);
2857 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002858 }
2859
2860 for (size_t i = 0; i < all_classes.size(); ++i) {
2861 all_classes[i]->DumpClass(std::cerr, flags);
2862 }
2863}
2864
Elliott Hughescac6cc72011-11-03 20:31:21 -07002865void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2866 MutexLock mu(classes_lock_);
2867 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2868 << classes_.size() << " allocated classes\n";
2869}
2870
Elliott Hughese27955c2011-08-26 15:21:24 -07002871size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002872 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002873 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002874}
2875
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002876pid_t ClassLinker::GetClassesLockOwner() {
2877 return classes_lock_.GetOwner();
2878}
2879
2880pid_t ClassLinker::GetDexLockOwner() {
2881 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002882}
2883
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002884void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
2885 DCHECK(!init_done_);
2886
2887 DCHECK(klass != NULL);
2888 DCHECK(klass->GetClassLoader() == NULL);
2889
2890 DCHECK(class_roots_ != NULL);
2891 DCHECK(class_roots_->Get(class_root) == NULL);
2892 class_roots_->Set(class_root, klass);
2893}
2894
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002895} // namespace art