blob: e32f8a53a97e597b4702664556af34600567f580 [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
Elliott Hughescc5f9a92011-09-28 19:17:29 -070062void ThrowNoSuchMethodError(const char* kind,
63 Class* c, const StringPiece& name, 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;
Elliott Hughescc5f9a92011-09-28 19:17:29 -070066 msg << "no " << kind << " method " << name << "." << signature
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080067 << " in class " << kh.GetDescriptor()
Elliott Hughescc5f9a92011-09-28 19:17:29 -070068 << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080069 std::string location(kh.GetLocation());
70 if (!location.empty()) {
71 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070072 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070073 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070074}
75
Elliott Hughes4a2b4172011-09-20 17:08:25 -070076void ThrowEarlierClassFailure(Class* c) {
77 /*
78 * The class failed to initialize on a previous attempt, so we want to throw
79 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
80 * failed in verification, in which case v2 5.4.1 says we need to re-throw
81 * the previous error.
82 */
83 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
84
85 if (c->GetVerifyErrorClass() != NULL) {
86 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080087 ClassHelper ve_ch(c->GetVerifyErrorClass());
88 std::string error_descriptor(ve_ch.GetDescriptor());
89 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -070090 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080091 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -070092 }
93}
94
Elliott Hughes4d0207c2011-10-03 19:14:34 -070095void WrapExceptionInInitializer() {
96 JNIEnv* env = Thread::Current()->GetJniEnv();
97
98 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
99 CHECK(cause.get() != NULL);
100
101 env->ExceptionClear();
102
103 // TODO: add java.lang.Error to JniConstants?
104 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
105 CHECK(error_class.get() != NULL);
106 if (env->IsInstanceOf(cause.get(), error_class.get())) {
107 // We only wrap non-Error exceptions; an Error can just be used as-is.
108 env->Throw(cause.get());
109 return;
110 }
111
112 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
113 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
114 CHECK(eiie_class.get() != NULL);
115
116 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
117 CHECK(mid != NULL);
118
119 ScopedLocalRef<jthrowable> eiie(env,
120 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
121 env->Throw(eiie.get());
122}
123
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700124} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700125
Elliott Hughes418d20f2011-09-22 14:00:39 -0700126const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700127 "Ljava/lang/Class;",
128 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700129 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700130 "[Ljava/lang/Object;",
131 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700132 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700133 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700134 "Ljava/lang/reflect/Field;",
135 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700136 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700137 "Ljava/lang/ClassLoader;",
138 "Ldalvik/system/BaseDexClassLoader;",
139 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700140 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700141 "Z",
142 "B",
143 "C",
144 "D",
145 "F",
146 "I",
147 "J",
148 "S",
149 "V",
150 "[Z",
151 "[B",
152 "[C",
153 "[D",
154 "[F",
155 "[I",
156 "[J",
157 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700158 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700159};
160
Elliott Hughes5f791332011-09-15 17:45:30 -0700161class ObjectLock {
162 public:
163 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
164 CHECK(object != NULL);
165 obj_->MonitorEnter(self_);
166 }
167
168 ~ObjectLock() {
169 obj_->MonitorExit(self_);
170 }
171
172 void Wait() {
173 return Monitor::Wait(self_, obj_, 0, 0, false);
174 }
175
176 void Notify() {
177 obj_->Notify();
178 }
179
180 void NotifyAll() {
181 obj_->NotifyAll();
182 }
183
184 private:
185 Thread* self_;
186 Object* obj_;
187 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
188};
189
Brian Carlstromae826982011-11-09 01:33:42 -0800190ClassLinker* ClassLinker::Create(bool verbose,
191 const std::string& boot_class_path,
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700192 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700193 CHECK_NE(boot_class_path.size(), 0U);
Brian Carlstromae826982011-11-09 01:33:42 -0800194 UniquePtr<ClassLinker> class_linker(new ClassLinker(verbose, intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700195 class_linker->Init(boot_class_path);
196 return class_linker.release();
197}
198
Brian Carlstromae826982011-11-09 01:33:42 -0800199ClassLinker* ClassLinker::Create(bool verbose, InternTable* intern_table) {
200 UniquePtr<ClassLinker> class_linker(new ClassLinker(verbose, intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700201 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700202 return class_linker.release();
203}
204
Brian Carlstromae826982011-11-09 01:33:42 -0800205ClassLinker::ClassLinker(bool verbose, InternTable* intern_table)
206 : verbose_(verbose),
207 dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700208 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700209 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700210 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700211 init_done_(false),
212 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700213 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700214}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700215
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700216void CreateClassPath(const std::string& class_path,
217 std::vector<const DexFile*>& class_path_vector) {
218 std::vector<std::string> parsed;
219 Split(class_path, ':', parsed);
220 for (size_t i = 0; i < parsed.size(); ++i) {
221 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700222 if (dex_file == NULL) {
223 LOG(WARNING) << "Failed to open dex file " << parsed[i];
224 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700225 class_path_vector.push_back(dex_file);
226 }
227 }
228}
229
230void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700231 const Runtime* runtime = Runtime::Current();
232 if (runtime->IsVerboseStartup()) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700233 LOG(INFO) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700234 }
235
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700236 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700237
Elliott Hughes30646832011-10-13 16:59:46 -0700238 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700239 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
240 CHECK(java_lang_Class.get() != NULL);
241 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700243 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700244
Elliott Hughes418d20f2011-09-22 14:00:39 -0700245 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700246 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
247 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700248
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700249 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700250 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
251 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700252 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700253 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700254 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700255
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700256 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700257 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
258 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700259
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700260 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700261 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700262
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700264 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
265 char_array_class->SetComponentType(char_class.get());
266 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700267
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700268 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700269 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
270 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 java_lang_String->SetObjectSize(sizeof(String));
272 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400273
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700274 // Create storage for root classes, save away our work so far (requires
275 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700276 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700277 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700278 SetClassRoot(kJavaLangClass, java_lang_Class.get());
279 SetClassRoot(kJavaLangObject, java_lang_Object.get());
280 SetClassRoot(kClassArrayClass, class_array_class.get());
281 SetClassRoot(kObjectArrayClass, object_array_class.get());
282 SetClassRoot(kCharArrayClass, char_array_class.get());
283 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284
285 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700286 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
287 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
288 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
289 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
290 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
291 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
292 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
293 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700296 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297
298 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700299 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700301 IntArray::SetArrayClass(int_array_class.get());
302 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700304 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700305
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700306 // setup boot_class_path_ and register class_path now that we can
307 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700308 std::vector<const DexFile*> boot_class_path_vector;
309 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700310 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700311 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
312 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700313 CHECK(dex_file != NULL);
314 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700315 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700316
Elliott Hughes80609252011-09-23 17:24:51 -0700317 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700318 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700319 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700320 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700321 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700322 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
323
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700324 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
325 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700327 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700328 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700329 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700330
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700332 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700333 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700334 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700335 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700336 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337
338 // now we can use FindSystemClass
339
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700340 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700341 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700342 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700343
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700344 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345 java_lang_Object->SetStatus(Class::kStatusNotReady);
346 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
349 java_lang_String->SetStatus(Class::kStatusNotReady);
350 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700351 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700352 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
353
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700354 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
356 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
357
358 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
359 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
360
361 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700362 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363
364 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
365 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
366
367 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700368 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700369
370 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
371 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
372
373 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
374 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
375
376 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
377 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
378
Elliott Hughes418d20f2011-09-22 14:00:39 -0700379 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700380 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700381
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700382 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700383 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384
385 // Setup the single, global copies of "interfaces" and "iftable"
386 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
387 CHECK(java_lang_Cloneable != NULL);
388 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
389 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700390 // We assume that Cloneable/Serializable don't have superinterfaces --
391 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700392 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800393 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
394 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700395
Elliott Hughes418d20f2011-09-22 14:00:39 -0700396 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800397 ClassHelper kh(class_array_class.get(), this);
398 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
399 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
400 kh.ChangeClass(object_array_class.get());
401 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
402 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700403 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700404 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700405 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700406 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407
Elliott Hughes80609252011-09-23 17:24:51 -0700408 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
409 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700410 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700411
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700412 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700413 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700414 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700415
416 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700417 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700418 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700419
Ian Rogers466bb252011-10-14 03:29:56 -0700420 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
421
422 // Create java.lang.reflect.Proxy root
423 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
424 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
425
Brian Carlstrom1f870082011-08-23 16:02:11 -0700426 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700427 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
428 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700429 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700430 java_lang_ref_FinalizerReference->SetAccessFlags(
431 java_lang_ref_FinalizerReference->GetAccessFlags() |
432 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700433 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700434 java_lang_ref_PhantomReference->SetAccessFlags(
435 java_lang_ref_PhantomReference->GetAccessFlags() |
436 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700437 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700438 java_lang_ref_SoftReference->SetAccessFlags(
439 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700440 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441 java_lang_ref_WeakReference->SetAccessFlags(
442 java_lang_ref_WeakReference->GetAccessFlags() |
443 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700444
Brian Carlstromaded5f72011-10-07 17:15:04 -0700445 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700446 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700447 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700448 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
449
450 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
451 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
452 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
453
454 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
455 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
456 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
457 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
458
459 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700460 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
461 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700462 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700463
Brian Carlstroma663ea52011-08-19 23:33:41 -0700464 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700465
466 if (runtime->IsVerboseStartup()) {
467 LOG(INFO) << "ClassLinker::InitFrom exiting";
468 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700469}
470
471void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700472 const Runtime* runtime = Runtime::Current();
473 if (runtime->IsVerboseStartup()) {
474 LOG(INFO) << "ClassLinker::FinishInit entering";
475 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700476
477 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700478 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700479 // as the types of the field can't be resolved prior to the runtime being
480 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700481 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700482 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700483 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
484
Elliott Hughesadb460d2011-10-05 17:02:34 -0700485 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
486
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800487 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
488
Brian Carlstrom16192862011-09-12 17:50:06 -0700489 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800490 FieldHelper fh(pendingNext, this);
491 CHECK_STREQ(fh.GetName(), "pendingNext");
492 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
493 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700494
495 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800496 fh.ChangeField(queue);
497 CHECK_STREQ(fh.GetName(), "queue");
498 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
499 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700500
501 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800502 fh.ChangeField(queueNext);
503 CHECK_STREQ(fh.GetName(), "queueNext");
504 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
505 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700506
507 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800508 fh.ChangeField(referent);
509 CHECK_STREQ(fh.GetName(), "referent");
510 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
511 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700512
513 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800514 fh.ChangeField(zombie);
515 CHECK_STREQ(fh.GetName(), "zombie");
516 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
517 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700518
519 Heap::SetReferenceOffsets(referent->GetOffset(),
520 queue->GetOffset(),
521 queueNext->GetOffset(),
522 pendingNext->GetOffset(),
523 zombie->GetOffset());
524
Brian Carlstroma663ea52011-08-19 23:33:41 -0700525 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700526 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700527 ClassRoot class_root = static_cast<ClassRoot>(i);
528 Class* klass = GetClassRoot(class_root);
529 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700530 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700531 // note SetClassRoot does additional validation.
532 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700533 }
534
Elliott Hughes92f14b22011-10-06 12:29:54 -0700535 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700536
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700537 // disable the slow paths in FindClass and CreatePrimitiveClass now
538 // that Object, Class, and Object[] are setup
539 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700540
541 if (runtime->IsVerboseStartup()) {
542 LOG(INFO) << "ClassLinker::FinishInit exiting";
543 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700544}
545
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700546void ClassLinker::RunRootClinits() {
547 Thread* self = Thread::Current();
548 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
549 Class* c = GetClassRoot(ClassRoot(i));
550 if (!c->IsArrayClass() && !c->IsPrimitive()) {
551 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700552 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700553 }
554 }
555}
556
jeffhao262bf462011-10-20 18:36:32 -0700557const OatFile* ClassLinker::GenerateOatFile(const std::string& filename) {
558 std::string oat_filename(GetArtCacheFilenameOrDie(OatFile::DexFilenameToOatFilename(filename)));
559
560 // fork and exec dex2oat
561 pid_t pid = fork();
562 if (pid == 0) {
563 std::string boot_image_option("--boot-image=");
564 boot_image_option += Heap::GetSpaces()[0]->GetImageFilename();
565
566 std::string dex_file_option("--dex-file=");
567 dex_file_option += filename;
568
569 std::string oat_file_option("--oat=");
570 oat_file_option += oat_filename;
571
Elliott Hughes234da572011-11-03 22:13:06 -0700572 std::string dex2oat("/system/bin/dex2oat");
573#ifndef NDEBUG
574 dex2oat += 'd';
575#endif
576
577 execl(dex2oat.c_str(), dex2oat.c_str(),
jeffhao5d840402011-10-24 17:09:45 -0700578 "--runtime-arg", "-Xms64m",
579 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500580 "--runtime-arg", "-classpath",
581 "--runtime-arg", Runtime::Current()->GetClassPath().c_str(),
jeffhao262bf462011-10-20 18:36:32 -0700582 boot_image_option.c_str(),
583 dex_file_option.c_str(),
584 oat_file_option.c_str(),
585 NULL);
586
587 PLOG(FATAL) << "execl(dex2oatd) failed";
588 return NULL;
589 } else {
590 // wait for dex2oat to finish
591 int status;
592 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
593 if (got_pid != pid) {
594 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
595 return NULL;
596 }
597 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
598 LOG(ERROR) << "dex2oatd failed with dex-file=" << filename;
599 return NULL;
600 }
601 }
602 return OatFile::Open(oat_filename, "", NULL);
603}
604
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700605OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700606 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700607 const Runtime* runtime = Runtime::Current();
608 if (runtime->IsVerboseStartup()) {
609 LOG(INFO) << "ClassLinker::OpenOat entering";
610 }
611 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800612 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
613 // check the down cast
614 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700615 std::string oat_filename;
616 oat_filename += runtime->GetHostPrefix();
617 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700618 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700619 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700620 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700621 return NULL;
622 }
623 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
624 uint32_t image_oat_checksum = image_header.GetOatChecksum();
625 if (oat_checksum != image_oat_checksum) {
626 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
627 << " to expected oat checksum " << std::hex << oat_checksum
628 << " in image";
629 return NULL;
630 }
631 oat_files_.push_back(oat_file);
632 if (runtime->IsVerboseStartup()) {
633 LOG(INFO) << "ClassLinker::OpenOat exiting";
634 }
635 return oat_file;
636}
637
Brian Carlstromae826982011-11-09 01:33:42 -0800638const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
639 for (size_t i = 0; i < oat_files_.size(); i++) {
640 const OatFile* oat_file = oat_files_[i];
641 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800642 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800643 return oat_file;
644 }
645 }
646 return NULL;
647}
648
649const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700650 MutexLock mu(dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800651 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
652 if (oat_file != NULL) {
653 return oat_file;
654 }
655
656 oat_file = FindOatFileFromOatLocation(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
jeffhao262bf462011-10-20 18:36:32 -0700657 if (oat_file != NULL) {
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700658 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
659 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
660 return oat_file;
661 }
662 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
663 << " is older than " << dex_file.GetLocation() << " --- regenerating";
Elliott Hughes234da572011-11-03 22:13:06 -0700664 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
665 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
666 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700667 // Fall through...
jeffhao262bf462011-10-20 18:36:32 -0700668 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700669 // Generate oat file if it wasn't found or was obsolete.
jeffhao262bf462011-10-20 18:36:32 -0700670 oat_file = GenerateOatFile(dex_file.GetLocation());
671 if (oat_file == NULL) {
672 LOG(ERROR) << "Failed to generate oat file from dex file " << dex_file.GetLocation();
673 return NULL;
674 }
675 oat_files_.push_back(oat_file);
676 return oat_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700677}
678
Brian Carlstromae826982011-11-09 01:33:42 -0800679const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700680 for (size_t i = 0; i < oat_files_.size(); i++) {
681 const OatFile* oat_file = oat_files_[i];
682 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800683 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700684 return oat_file;
685 }
686 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700687 return NULL;
688}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700689
Brian Carlstromae826982011-11-09 01:33:42 -0800690const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
691 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700692 if (oat_file != NULL) {
693 return oat_file;
694 }
695
Brian Carlstromae826982011-11-09 01:33:42 -0800696 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700697 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800698 if (oat_location.empty() || oat_location[0] != '/') {
699 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700700 return NULL;
701 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700702
Brian Carlstroma9f19782011-10-13 00:14:47 -0700703 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Brian Carlstromae826982011-11-09 01:33:42 -0800704 std::string cache_location = GetArtCacheFilenameOrDie(oat_location);
705 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700706 if (oat_file != NULL) {
707 return oat_file;
708 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700709 oat_file = OatFile::Open(cache_location, "", NULL);
710 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800711 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700712 return NULL;
713 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700714 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700715
Brian Carlstromae826982011-11-09 01:33:42 -0800716 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromfad71432011-10-16 20:25:10 -0700717 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700718 return oat_file;
719}
720
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700721void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700722 const Runtime* runtime = Runtime::Current();
723 if (runtime->IsVerboseStartup()) {
724 LOG(INFO) << "ClassLinker::InitFromImage entering";
725 }
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));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700749 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
750
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
797 if (runtime->IsVerboseStartup()) {
798 LOG(INFO) << "ClassLinker::InitFromImage exiting";
799 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700800}
801
Brian Carlstrom78128a62011-09-15 17:21:19 -0700802void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700803 DCHECK(obj != NULL);
804 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700805 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700806
Elliott Hughesdbb40792011-11-18 17:05:22 -0800807 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700808 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700809 return;
810 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700811 if (obj->IsClass()) {
812 // restore class to ClassLinker::classes_ table
813 Class* klass = obj->AsClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800814 std::string descriptor(ClassHelper(klass, class_linker).GetDescriptor());
Ian Rogers5d76c432011-10-31 21:42:49 -0700815 bool success = class_linker->InsertClass(descriptor, klass, true);
816 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700817 return;
818 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700819}
820
821// Keep in sync with InitCallback. Anything we visit, we need to
822// reinit references to when reinitializing a ClassLinker from a
823// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700824void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
825 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700826
827 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700828 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700829 }
830
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700831 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700832 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700833 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700834 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700835 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700836 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700837 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700838 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700839
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700840 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700841}
842
Elliott Hughesa2155262011-11-16 16:26:58 -0800843void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
844 MutexLock mu(classes_lock_);
845 typedef Table::const_iterator It; // TODO: C++0x auto
846 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
847 if (!visitor(it->second, arg)) {
848 return;
849 }
850 }
851 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
852 if (!visitor(it->second, arg)) {
853 return;
854 }
855 }
856}
857
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700858ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700859 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700860 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700861 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700862 BooleanArray::ResetArrayClass();
863 ByteArray::ResetArrayClass();
864 CharArray::ResetArrayClass();
865 DoubleArray::ResetArrayClass();
866 FloatArray::ResetArrayClass();
867 IntArray::ResetArrayClass();
868 LongArray::ResetArrayClass();
869 ShortArray::ResetArrayClass();
870 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700871 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700872 STLDeleteElements(&boot_class_path_);
873 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700874}
875
876DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700877 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
878 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700879 return NULL;
880 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700881 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
882 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700883 return NULL;
884 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700885 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
886 if (strings.get() == NULL) {
887 return NULL;
888 }
889 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
890 if (types.get() == NULL) {
891 return NULL;
892 }
893 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
894 if (methods.get() == NULL) {
895 return NULL;
896 }
897 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
898 if (fields.get() == NULL) {
899 return NULL;
900 }
901 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
902 if (code_and_direct_methods.get() == NULL) {
903 return NULL;
904 }
905 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
906 if (initialized_static_storage.get() == NULL) {
907 return NULL;
908 }
909
910 dex_cache->Init(location.get(),
911 strings.get(),
912 types.get(),
913 methods.get(),
914 fields.get(),
915 code_and_direct_methods.get(),
916 initialized_static_storage.get());
917 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700918}
919
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700920CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
921 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700922}
923
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700924InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
925 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700926 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
927 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700928 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700929 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700930}
931
Brian Carlstrom4873d462011-08-21 15:23:39 -0700932Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
933 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700934 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700935 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700936 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700937 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700938}
939
Brian Carlstrom4873d462011-08-21 15:23:39 -0700940Class* ClassLinker::AllocClass(size_t class_size) {
941 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700942}
943
Jesse Wilson35baaab2011-08-10 16:18:03 -0400944Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700945 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700946}
947
948Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700949 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700950}
951
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700952ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
953 return ObjectArray<StackTraceElement>::Alloc(
954 GetClassRoot(kJavaLangStackTraceElementArrayClass),
955 length);
956}
957
Brian Carlstromaded5f72011-10-07 17:15:04 -0700958Class* EnsureResolved(Class* klass) {
959 DCHECK(klass != NULL);
960 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700961 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700962 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700963 ObjectLock lock(klass);
964 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700965 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700966 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800967 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700968 return NULL;
969 }
970 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700971 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700972 lock.Wait();
973 }
974 }
975 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700976 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700977 return NULL;
978 }
979 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700980 CHECK(klass->IsResolved()) << PrettyClass(klass);
981 CHECK(!self->IsExceptionPending())
982 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
983 return klass;
984}
985
986Class* ClassLinker::FindClass(const std::string& descriptor,
987 const ClassLoader* class_loader) {
988 CHECK_NE(descriptor.size(), 0U);
989 Thread* self = Thread::Current();
990 DCHECK(self != NULL);
991 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800992 if (descriptor.size() == 1) {
993 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
994 // for primitive classes that aren't backed by dex files.
995 return FindPrimitiveClass(descriptor[0]);
996 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700997 // Find the class in the loaded classes table.
998 Class* klass = LookupClass(descriptor, class_loader);
999 if (klass != NULL) {
1000 return EnsureResolved(klass);
1001 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001002 // Class is not yet loaded.
1003 if (descriptor[0] == '[') {
1004 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001005
Jesse Wilson47daf872011-11-23 11:42:45 -05001006 } else if (class_loader == NULL) {
1007 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1008 if (pair.second != NULL) {
1009 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1010 }
1011
1012 } else if (ClassLoader::UseCompileTimeClassPath()) {
1013 // first try the boot class path
1014 Class* system_class = FindSystemClass(descriptor);
1015 if (system_class != NULL) {
1016 return system_class;
1017 }
1018 CHECK(self->IsExceptionPending());
1019 self->ClearException();
1020
1021 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001022 const std::vector<const DexFile*>& class_path
1023 = ClassLoader::GetCompileTimeClassPath(class_loader);
1024 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001025 if (pair.second != NULL) {
1026 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001027 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001028
1029 } else {
1030 std::string class_name_string = DescriptorToDot(descriptor);
1031 ScopedThreadStateChange(self, Thread::kNative);
1032 JNIEnv* env = self->GetJniEnv();
1033 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1034 CHECK(c.get() != NULL);
1035 // TODO: cache method?
1036 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1037 CHECK(mid != NULL);
1038 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1039 if (class_name_object.get() == NULL) {
1040 return NULL;
1041 }
1042 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1043 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
1044 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001045 }
1046
Jesse Wilson47daf872011-11-23 11:42:45 -05001047 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
1048 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001049}
1050
1051Class* ClassLinker::DefineClass(const std::string& descriptor,
1052 const ClassLoader* class_loader,
1053 const DexFile& dex_file,
1054 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001055 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001056 // Load the class from the dex file.
1057 if (!init_done_) {
1058 // finish up init of hand crafted class_roots_
1059 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001060 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001061 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001062 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001063 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001064 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001065 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001066 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001067 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001068 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001069 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001070 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001071 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001072 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001073 }
1074 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001075 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001076 }
1077 klass->SetDexCache(FindDexCache(dex_file));
1078 LoadClass(dex_file, dex_class_def, klass, class_loader);
1079 // Check for a pending exception during load
1080 Thread* self = Thread::Current();
1081 if (self->IsExceptionPending()) {
1082 return NULL;
1083 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001084 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001085 klass->SetClinitThreadId(self->GetTid());
1086 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001087 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001088 if (!success) {
1089 // We may fail to insert if we raced with another thread.
1090 klass->SetClinitThreadId(0);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001091 klass.reset(LookupClass(descriptor, class_loader));
1092 CHECK(klass.get() != NULL);
1093 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001094 }
1095 // Finish loading (if necessary) by finding parents
1096 CHECK(!klass->IsLoaded());
1097 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1098 // Loading failed.
1099 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001100 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001101 lock.NotifyAll();
1102 return NULL;
1103 }
1104 CHECK(klass->IsLoaded());
1105 // Link the class (if necessary)
1106 CHECK(!klass->IsResolved());
1107 if (!LinkClass(klass)) {
1108 // Linking failed.
1109 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001110 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001111 lock.NotifyAll();
1112 return NULL;
1113 }
1114 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001115
1116 /*
1117 * We send CLASS_PREPARE events to the debugger from here. The
1118 * definition of "preparation" is creating the static fields for a
1119 * class and initializing them to the standard default values, but not
1120 * executing any code (that comes later, during "initialization").
1121 *
1122 * We did the static preparation in LinkClass.
1123 *
1124 * The class has been prepared and resolved but possibly not yet verified
1125 * at this point.
1126 */
1127 Dbg::PostClassPrepare(klass.get());
1128
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001129 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001130}
1131
Brian Carlstrom4873d462011-08-21 15:23:39 -07001132// Precomputes size that will be needed for Class, matching LinkStaticFields
1133size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1134 const DexFile::ClassDef& dex_class_def) {
1135 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001136 size_t num_ref = 0;
1137 size_t num_32 = 0;
1138 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001139 if (class_data != NULL) {
1140 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1141 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001142 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001143 char c = descriptor[0];
1144 if (c == 'L' || c == '[') {
1145 num_ref++;
1146 } else if (c == 'J' || c == 'D') {
1147 num_64++;
1148 } else {
1149 num_32++;
1150 }
1151 }
1152 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001153 // start with generic class data
1154 size_t size = sizeof(Class);
1155 // follow with reference fields which must be contiguous at start
1156 size += (num_ref * sizeof(uint32_t));
1157 // if there are 64-bit fields to add, make sure they are aligned
1158 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1159 if (num_32 != 0) {
1160 // use an available 32-bit field for padding
1161 num_32--;
1162 }
1163 size += sizeof(uint32_t); // either way, we are adding a word
1164 DCHECK_EQ(size, RoundUp(size, 8));
1165 }
1166 // tack on any 64-bit fields now that alignment is assured
1167 size += (num_64 * sizeof(uint64_t));
1168 // tack on any remaining 32-bit fields
1169 size += (num_32 * sizeof(uint32_t));
1170 return size;
1171}
1172
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001173void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001174 // Every kind of method should at least get an invoke stub from the oat_method.
1175 // non-abstract methods also get their code pointers.
1176 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001177 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001178
1179 if (method->IsAbstract()) {
1180 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1181 return;
1182 }
1183 if (method->IsNative()) {
1184 // unregistering restores the dlsym lookup stub
1185 method->UnregisterNative();
1186 return;
1187 }
1188}
1189
Brian Carlstromf615a612011-07-23 12:50:34 -07001190void ClassLinker::LoadClass(const DexFile& dex_file,
1191 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001192 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001193 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001194 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001195 CHECK(klass->GetDexCache() != NULL);
1196 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001197 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001198 CHECK(descriptor != NULL);
1199
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001200 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001201 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001202 // Make sure that none of our runtime-only flags are set.
1203 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001204 klass->SetAccessFlags(access_flags);
1205 klass->SetClassLoader(class_loader);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001206 DCHECK(klass->GetPrimitiveType() == Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001207 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001208
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001209 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001210
Ian Rogers0571d352011-11-03 19:51:38 -07001211 // Load fields fields.
1212 const byte* class_data = dex_file.GetClassData(dex_class_def);
1213 if (class_data == NULL) {
1214 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001215 }
Ian Rogers0571d352011-11-03 19:51:38 -07001216 ClassDataItemIterator it(dex_file, class_data);
1217 if (it.NumStaticFields() != 0) {
1218 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1219 }
1220 if (it.NumInstanceFields() != 0) {
1221 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1222 }
1223 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1224 SirtRef<Field> sfield(AllocField());
1225 klass->SetStaticField(i, sfield.get());
1226 LoadField(dex_file, it, klass, sfield);
1227 }
1228 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1229 SirtRef<Field> ifield(AllocField());
1230 klass->SetInstanceField(i, ifield.get());
1231 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001232 }
1233
Brian Carlstromaded5f72011-10-07 17:15:04 -07001234 UniquePtr<const OatFile::OatClass> oat_class;
1235 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001236 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001237 if (oat_file != NULL) {
1238 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1239 if (oat_dex_file != NULL) {
1240 uint32_t class_def_index;
1241 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1242 CHECK(found) << descriptor;
1243 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001244 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001245 }
1246 }
1247 }
Ian Rogers0571d352011-11-03 19:51:38 -07001248 // Load methods.
1249 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001250 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001251 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001252 }
Ian Rogers0571d352011-11-03 19:51:38 -07001253 if (it.NumVirtualMethods() != 0) {
1254 // TODO: append direct methods to class object
1255 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001256 }
Ian Rogers0571d352011-11-03 19:51:38 -07001257 size_t method_index = 0;
1258 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1259 SirtRef<Method> method(AllocMethod());
1260 klass->SetDirectMethod(i, method.get());
1261 LoadMethod(dex_file, it, klass, method);
1262 if (oat_class.get() != NULL) {
1263 LinkCode(method, oat_class.get(), method_index);
1264 }
1265 method_index++;
1266 }
1267 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1268 SirtRef<Method> method(AllocMethod());
1269 klass->SetVirtualMethod(i, method.get());
1270 LoadMethod(dex_file, it, klass, method);
1271 if (oat_class.get() != NULL) {
1272 LinkCode(method, oat_class.get(), method_index);
1273 }
1274 method_index++;
1275 }
1276 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001277}
1278
Ian Rogers0571d352011-11-03 19:51:38 -07001279void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1280 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001281 uint32_t field_idx = it.GetMemberIndex();
1282 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001283 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001284 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001285}
1286
Ian Rogers0571d352011-11-03 19:51:38 -07001287void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1288 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001289 uint32_t method_idx = it.GetMemberIndex();
1290 dst->SetDexMethodIndex(method_idx);
1291 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001292 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001293
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001294
1295 StringPiece method_name(dex_file.GetMethodName(method_id));
1296 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001297 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1298 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001299
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001300 if (method_name == "finalize") {
1301 // Create the prototype for a signature of "()V"
1302 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1303 if (void_string_id != NULL) {
1304 const DexFile::TypeId* void_type_id =
1305 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1306 if (void_type_id != NULL) {
1307 std::vector<uint16_t> no_args;
1308 const DexFile::ProtoId* finalizer_proto =
1309 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1310 if (finalizer_proto != NULL) {
1311 // We have the prototype in the dex file
1312 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1313 klass->SetFinalizable();
1314 } else {
1315 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1316 // The Enum class declares a "final" finalize() method to prevent subclasses from
1317 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1318 // subclasses, so we exclude it here.
1319 // We also want to avoid setting the flag on Object, where we know that finalize() is
1320 // empty.
1321 if (klass_descriptor != "Ljava/lang/Object;" &&
1322 klass_descriptor != "Ljava/lang/Enum;") {
1323 klass->SetFinalizable();
1324 }
1325 }
1326 }
1327 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001328 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001329 }
Ian Rogers0571d352011-11-03 19:51:38 -07001330 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001331 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001332
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001333 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1334 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1335 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1336 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1337 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1338 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001339
Brian Carlstrom934486c2011-07-12 23:42:50 -07001340 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001341}
1342
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001343void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001344 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1345 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001346}
1347
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001348void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1349 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001350 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001351 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001352}
1353
Brian Carlstromaded5f72011-10-07 17:15:04 -07001354bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001355 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001356 for (size_t i = 0; i != dex_files_.size(); ++i) {
1357 if (dex_files_[i] == &dex_file) {
1358 return true;
1359 }
1360 }
1361 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001362}
1363
Brian Carlstromaded5f72011-10-07 17:15:04 -07001364bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001365 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001366 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001367}
1368
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001369void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001370 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001371 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001372 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001373 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001374 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001375}
1376
Brian Carlstromaded5f72011-10-07 17:15:04 -07001377void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001378 {
1379 MutexLock mu(dex_lock_);
1380 if (IsDexFileRegisteredLocked(dex_file)) {
1381 return;
1382 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001383 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001384 // Don't alloc while holding the lock, since allocation may need to
1385 // suspend all threads and another thread may need the dex_lock_ to
1386 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001387 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001388 {
1389 MutexLock mu(dex_lock_);
1390 if (IsDexFileRegisteredLocked(dex_file)) {
1391 return;
1392 }
1393 RegisterDexFileLocked(dex_file, dex_cache);
1394 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001395}
1396
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001397void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001398 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001399 RegisterDexFileLocked(dex_file, dex_cache);
1400}
1401
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001402const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001403 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001404 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001405 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1406 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001407 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001408 }
1409 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001410 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001411 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001412}
1413
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001414DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001415 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001416 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001417 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001418 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001419 }
1420 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001421 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001422 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001423}
1424
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001425Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1426 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001427 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001428 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001429 CHECK(primitive_class != NULL);
1430 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001431 primitive_class->SetPrimitiveType(type);
1432 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001433 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001434 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1435 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001436}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001437
Brian Carlstrombe977852011-07-19 14:54:54 -07001438// Create an array class (i.e. the class object for the array, not the
1439// array itself). "descriptor" looks like "[C" or "[[[[B" or
1440// "[Ljava/lang/String;".
1441//
1442// If "descriptor" refers to an array of primitives, look up the
1443// primitive type's internally-generated class object.
1444//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001445// "class_loader" is the class loader of the class that's referring to
1446// us. It's used to ensure that we're looking for the element type in
1447// the right context. It does NOT become the class loader for the
1448// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001449//
1450// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001451Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001452 const ClassLoader* class_loader) {
1453 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001454
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001455 // Identify the underlying component type
1456 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001457 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001458 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001459 return NULL;
1460 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001461
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001462 // See if the component type is already loaded. Array classes are
1463 // always associated with the class loader of their underlying
1464 // element type -- an array of Strings goes with the loader for
1465 // java/lang/String -- so we need to look for it there. (The
1466 // caller should have checked for the existence of the class
1467 // before calling here, but they did so with *their* class loader,
1468 // not the component type's loader.)
1469 //
1470 // If we find it, the caller adds "loader" to the class' initiating
1471 // loader list, which should prevent us from going through this again.
1472 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001473 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001474 // are the same, because our caller (FindClass) just did the
1475 // lookup. (Even if we get this wrong we still have correct behavior,
1476 // because we effectively do this lookup again when we add the new
1477 // class to the hash table --- necessary because of possible races with
1478 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001479 if (class_loader != component_type->GetClassLoader()) {
1480 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001481 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001482 return new_class;
1483 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001484 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001485
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001486 // Fill out the fields in the Class.
1487 //
1488 // It is possible to execute some methods against arrays, because
1489 // all arrays are subclasses of java_lang_Object_, so we need to set
1490 // up a vtable. We can just point at the one in java_lang_Object_.
1491 //
1492 // Array classes are simple enough that we don't need to do a full
1493 // link step.
1494
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001495 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001496 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001497 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001498 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001499 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001500 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001501 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001502 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001503 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001504 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001505 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001506 }
1507 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001508 if (new_class.get() == NULL) {
1509 new_class.reset(AllocClass(sizeof(Class)));
1510 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001511 return NULL;
1512 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001513 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001514 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001515 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001516 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001517 new_class->SetSuperClass(java_lang_Object);
1518 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001519 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001520 new_class->SetClassLoader(component_type->GetClassLoader());
1521 new_class->SetStatus(Class::kStatusInitialized);
1522 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001523 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001524
1525
1526 // All arrays have java/lang/Cloneable and java/io/Serializable as
1527 // interfaces. We need to set that up here, so that stuff like
1528 // "instanceof" works right.
1529 //
1530 // Note: The GC could run during the call to FindSystemClass,
1531 // so we need to make sure the class object is GC-valid while we're in
1532 // there. Do this by clearing the interface list so the GC will just
1533 // think that the entries are null.
1534
1535
1536 // Use the single, global copies of "interfaces" and "iftable"
1537 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001538 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001539 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001540
1541 // Inherit access flags from the component type. Arrays can't be
1542 // used as a superclass or interface, so we want to add "final"
1543 // and remove "interface".
1544 //
1545 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001546 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001547 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001548 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1549 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001550
Ian Rogers5d76c432011-10-31 21:42:49 -07001551 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001552 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001553 }
1554 // Another thread must have loaded the class after we
1555 // started but before we finished. Abandon what we've
1556 // done.
1557 //
1558 // (Yes, this happens.)
1559
1560 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001561 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001562 DCHECK(other_class != NULL);
1563 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001564}
1565
1566Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001567 switch (Primitive::GetType(type)) {
1568 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001569 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001570 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001571 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001572 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001573 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001574 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001575 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001576 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001577 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001578 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001579 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001580 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001581 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001582 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001583 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001584 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001585 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001586 case Primitive::kPrimNot:
1587 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001588 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001589 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001590 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001591 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001592}
1593
Ian Rogers5d76c432011-10-31 21:42:49 -07001594bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass, bool image_class) {
Brian Carlstromae826982011-11-09 01:33:42 -08001595 if (verbose_) {
1596 DexCache* dex_cache = klass->GetDexCache();
1597 std::string source;
1598 if (dex_cache != NULL) {
1599 source += " from ";
1600 source += dex_cache->GetLocation()->ToModifiedUtf8();
1601 }
1602 LOG(INFO) << "Loaded class " << descriptor << source;
1603 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001604 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001605 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001606 Table::iterator it;
1607 if (image_class) {
1608 // TODO: sanity check there's no match in classes_
1609 it = image_classes_.insert(std::make_pair(hash, klass));
1610 } else {
1611 // TODO: sanity check there's no match in image_classes_
1612 it = classes_.insert(std::make_pair(hash, klass));
1613 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001614 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001615}
1616
Brian Carlstromae826982011-11-09 01:33:42 -08001617bool ClassLinker::RemoveClass(const std::string& descriptor, const ClassLoader* class_loader) {
1618 size_t hash = StringPieceHash()(descriptor);
1619 MutexLock mu(classes_lock_);
1620 typedef Table::const_iterator It; // TODO: C++0x auto
1621 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001622 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001623 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1624 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001625 kh.ChangeClass(klass);
1626 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001627 classes_.erase(it);
1628 return true;
1629 }
1630 }
1631 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1632 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001633 kh.ChangeClass(klass);
1634 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001635 image_classes_.erase(it);
1636 return true;
1637 }
1638 }
1639 return false;
1640}
1641
Brian Carlstromaded5f72011-10-07 17:15:04 -07001642Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001643 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001644 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001645 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001646 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001647 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001648 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001649 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001650 kh.ChangeClass(klass);
1651 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001652 return klass;
1653 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001654 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001655 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1656 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001657 kh.ChangeClass(klass);
1658 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001659 return klass;
1660 }
1661 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001662 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001663}
1664
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001665void ClassLinker::LookupClasses(const std::string& descriptor, std::vector<Class*>& classes) {
1666 classes.clear();
1667 size_t hash = StringPieceHash()(descriptor);
1668 MutexLock mu(classes_lock_);
1669 typedef Table::const_iterator It; // TODO: C++0x auto
1670 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001671 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001672 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001673 Class* klass = it->second;
1674 kh.ChangeClass(klass);
1675 if (descriptor == kh.GetDescriptor()) {
1676 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001677 }
1678 }
1679 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001680 Class* klass = it->second;
1681 kh.ChangeClass(klass);
1682 if (descriptor == kh.GetDescriptor()) {
1683 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001684 }
1685 }
1686}
1687
jeffhao98eacac2011-09-14 16:11:53 -07001688void ClassLinker::VerifyClass(Class* klass) {
1689 if (klass->IsVerified()) {
1690 return;
1691 }
1692
1693 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001694 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001695
Ian Rogersd81871c2011-10-03 13:57:23 -07001696 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001697 klass->SetStatus(Class::kStatusVerified);
1698 } else {
1699 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001700 Thread* self = Thread::Current();
1701 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1702 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001703 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001704 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001705 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001706 }
jeffhao98eacac2011-09-14 16:11:53 -07001707}
1708
Jesse Wilson95caa792011-10-12 18:14:17 -04001709Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001710 ClassLoader* loader, ObjectArray<Method>* methods,
1711 ObjectArray<ObjectArray<Class> >* throws) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001712 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass)));
1713 CHECK(klass.get() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001714 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001715 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001716 klass->SetClassLoader(loader);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001717 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001718 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001719 klass->SetDexCache(proxy_class->GetDexCache());
1720 klass->SetDexTypeIndex(-1);
Ian Rogers466bb252011-10-14 03:29:56 -07001721 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001722 klass->SetStatus(Class::kStatusInitialized); // no loading or initializing necessary
Jesse Wilson95caa792011-10-12 18:14:17 -04001723
Ian Rogers466bb252011-10-14 03:29:56 -07001724 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001725 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001726 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001727
Ian Rogers466bb252011-10-14 03:29:56 -07001728 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001729 size_t num_virtual_methods = methods->GetLength();
1730 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1731 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001732 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001733 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001734 }
Ian Rogers466bb252011-10-14 03:29:56 -07001735 // Link the virtual methods, creating vtable and iftables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001736 if (!LinkMethods(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001737 DCHECK(Thread::Current()->IsExceptionPending());
1738 return NULL;
1739 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001740 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001741}
1742
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001743std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1744 DCHECK(proxy_class->IsProxyClass());
1745 String* name = proxy_class->GetName();
1746 DCHECK(name != NULL);
1747 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1748}
1749
1750
1751Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001752 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001753 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001754 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001755 Method* proxy_constructor = proxy_direct_methods->Get(2);
1756 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1757 // code_ too)
1758 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1759 // Make this constructor public and fix the class to be our Proxy version
1760 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001761 constructor->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001762 // Sanity checks
1763 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001764 MethodHelper mh(constructor);
1765 CHECK_STREQ(mh.GetName(), "<init>");
1766 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001767 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001768 return constructor;
1769}
1770
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001771Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1772 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1773 // prototype method
1774 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1775 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001776 // as necessary
1777 Method* method = down_cast<Method*>(prototype->Clone());
1778
1779 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1780 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001781 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001782 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001783
Ian Rogers466bb252011-10-14 03:29:56 -07001784 // At runtime the method looks like a reference and argument saving method, clone the code
1785 // related parameters from this method.
1786 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1787 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1788 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1789 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1790 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Jesse Wilson95caa792011-10-12 18:14:17 -04001791
Ian Rogers466bb252011-10-14 03:29:56 -07001792 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001793 CHECK(!prototype->IsFinal());
1794 CHECK(method->IsFinal());
1795 CHECK(!method->IsAbstract());
1796 MethodHelper mh(method);
1797 const char* method_name = mh.GetName();
1798 const char* method_shorty = mh.GetShorty();
1799 Class* method_return = mh.GetReturnType();
1800
1801 mh.ChangeMethod(prototype.get());
1802
1803 CHECK_STREQ(mh.GetName(), method_name);
1804 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001805
1806 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001807 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001808
1809 return method;
1810}
1811
Brian Carlstrom25c33252011-09-18 15:58:35 -07001812bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001813 CHECK(klass->IsResolved() || klass->IsErroneous())
1814 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001815
Carl Shapirob5573532011-07-12 18:22:59 -07001816 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001817
Brian Carlstrom25c33252011-09-18 15:58:35 -07001818 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001819 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001820 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001821 ObjectLock lock(klass);
1822
Brian Carlstromd1422f82011-09-28 11:37:09 -07001823 if (klass->GetStatus() == Class::kStatusInitialized) {
1824 return true;
1825 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001826
Brian Carlstromd1422f82011-09-28 11:37:09 -07001827 if (klass->IsErroneous()) {
1828 ThrowEarlierClassFailure(klass);
1829 return false;
1830 }
1831
1832 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001833 VerifyClass(klass);
1834 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001835 return false;
1836 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001837 }
1838
Brian Carlstrom25c33252011-09-18 15:58:35 -07001839 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1840 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001841 // if the class has a <clinit> but we can't run it during compilation,
1842 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001843 return false;
1844 }
1845
Brian Carlstromd1422f82011-09-28 11:37:09 -07001846 // If the class is kStatusInitializing, either this thread is
1847 // initializing higher up the stack or another thread has beat us
1848 // to initializing and we need to wait. Either way, this
1849 // invocation of InitializeClass will not be responsible for
1850 // running <clinit> and will return.
1851 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001852 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001853 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001854 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001855 return true;
1856 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001857 // No. That's fine. Wait for another thread to finish initializing.
1858 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001859 }
1860
1861 if (!ValidateSuperClassDescriptors(klass)) {
1862 klass->SetStatus(Class::kStatusError);
1863 return false;
1864 }
1865
Brian Carlstromd1422f82011-09-28 11:37:09 -07001866 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001867
Elliott Hughesdcc24742011-09-07 14:02:44 -07001868 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001869 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001870 }
1871
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001872 uint64_t t0 = NanoTime();
1873
Brian Carlstrom25c33252011-09-18 15:58:35 -07001874 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001875 return false;
1876 }
1877
1878 InitializeStaticFields(klass);
1879
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001880 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001881 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001882 }
1883
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001884 uint64_t t1 = NanoTime();
1885
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001886 {
1887 ObjectLock lock(klass);
1888
1889 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001890 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001891 klass->SetStatus(Class::kStatusError);
1892 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001893 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1894 RuntimeStats* thread_stats = self->GetStats();
1895 ++global_stats->class_init_count;
1896 ++thread_stats->class_init_count;
1897 global_stats->class_init_time_ns += (t1 - t0);
1898 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001899 klass->SetStatus(Class::kStatusInitialized);
Brian Carlstromae826982011-11-09 01:33:42 -08001900 if (verbose_) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001901 ClassHelper kh(klass);
1902 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08001903 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001904 }
1905 lock.NotifyAll();
1906 }
1907
1908 return true;
1909}
1910
Brian Carlstromd1422f82011-09-28 11:37:09 -07001911bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1912 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001913 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001914 lock.Wait();
1915
1916 // When we wake up, repeat the test for init-in-progress. If
1917 // there's an exception pending (only possible if
1918 // "interruptShouldThrow" was set), bail out.
1919 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001920 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001921 klass->SetStatus(Class::kStatusError);
1922 return false;
1923 }
1924 // Spurious wakeup? Go back to waiting.
1925 if (klass->GetStatus() == Class::kStatusInitializing) {
1926 continue;
1927 }
1928 if (klass->IsErroneous()) {
1929 // The caller wants an exception, but it was thrown in a
1930 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001931 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001932 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001933 return false;
1934 }
1935 if (klass->IsInitialized()) {
1936 return true;
1937 }
1938 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1939 }
1940 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1941}
1942
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001943bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1944 if (klass->IsInterface()) {
1945 return true;
1946 }
1947 // begin with the methods local to the superclass
1948 if (klass->HasSuperClass() &&
1949 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1950 const Class* super = klass->GetSuperClass();
1951 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001952 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001953 if (method != super->GetVirtualMethod(i) &&
1954 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001955 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1956
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001957 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
1958 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
1959 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001960 return false;
1961 }
1962 }
1963 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001964 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1965 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1966 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1968 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001969 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001970 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001971 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001972 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1973
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001974 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
1975 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
1976 PrettyMethod(method).c_str(),
1977 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001978 return false;
1979 }
1980 }
1981 }
1982 }
1983 return true;
1984}
1985
1986bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001987 const Class* klass1,
1988 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07001989 if (klass1 == klass2) {
1990 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07001991 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001992 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001993 const DexFile::ProtoId& proto_id =
1994 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07001995 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
1996 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001997 if (descriptor == NULL) {
1998 break;
1999 }
2000 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2001 // Found a non-primitive type.
2002 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2003 return false;
2004 }
2005 }
2006 }
2007 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002008 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002009 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002010 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002011 return false;
2012 }
2013 }
2014 return true;
2015}
2016
2017// Returns true if classes referenced by the descriptor are the
2018// same classes in klass1 as they are in klass2.
2019bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002020 const Class* klass1,
2021 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002022 CHECK(descriptor != NULL);
2023 CHECK(klass1 != NULL);
2024 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002025 if (klass1 == klass2) {
2026 return true;
2027 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002028 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002029 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002030 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002031 // TODO: found2 == NULL
2032 // TODO: lookup found1 in initiating loader list
2033 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002034 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002035 return found1 == found2;
2036 } else {
2037 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002038 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002039}
2040
Brian Carlstrom25c33252011-09-18 15:58:35 -07002041bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002042 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002043 if (!klass->IsInterface() && klass->HasSuperClass()) {
2044 Class* super_class = klass->GetSuperClass();
2045 if (super_class->GetStatus() != Class::kStatusInitialized) {
2046 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002047 Thread* self = Thread::Current();
2048 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002049 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002050 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002051 // TODO: check for a pending exception
2052 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002053 if (!can_run_clinit) {
2054 // Don't set status to error when we can't run <clinit>.
2055 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2056 klass->SetStatus(Class::kStatusVerified);
2057 return false;
2058 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002059 klass->SetStatus(Class::kStatusError);
2060 klass->NotifyAll();
2061 return false;
2062 }
2063 }
2064 }
2065 return true;
2066}
2067
Brian Carlstrom25c33252011-09-18 15:58:35 -07002068bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002069 CHECK(c != NULL);
2070 if (c->IsInitialized()) {
2071 return true;
2072 }
2073
Elliott Hughes5f791332011-09-15 17:45:30 -07002074 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002075 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002076 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002077 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002078}
2079
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002080void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002081 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002082 const ClassLoader* cl = c->GetClassLoader();
2083 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002084 ClassDataItemIterator it(dex_file, class_data);
2085 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2086 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002087 }
2088}
2089
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002090void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002091 size_t num_static_fields = klass->NumStaticFields();
2092 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002093 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002094 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002095 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002096 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002097 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002098 return;
2099 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002100 ClassHelper kh(klass);
2101 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002102 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002103 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002104 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002105
Ian Rogers0571d352011-11-03 19:51:38 -07002106 if (it.HasNext()) {
2107 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2108 std::map<uint32_t, Field*> field_map;
2109 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2110 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2111 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002112 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002113 }
2114}
2115
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002116bool ClassLinker::LinkClass(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002117 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118 if (!LinkSuperClass(klass)) {
2119 return false;
2120 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002121 if (!LinkMethods(klass, NULL)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002122 return false;
2123 }
2124 if (!LinkInstanceFields(klass)) {
2125 return false;
2126 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002127 if (!LinkStaticFields(klass)) {
2128 return false;
2129 }
2130 CreateReferenceInstanceOffsets(klass);
2131 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002132 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2133 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002134 return true;
2135}
2136
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002137bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002138 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002139 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2140 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2141 if (class_def == NULL) {
2142 return false;
2143 }
2144 uint16_t super_class_idx = class_def->superclass_idx_;
2145 if (super_class_idx != DexFile::kDexNoIndex16) {
2146 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002147 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002148 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002149 return false;
2150 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002151 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002152 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002153 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2154 if (interfaces != NULL) {
2155 for (size_t i = 0; i < interfaces->Size(); i++) {
2156 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2157 Class* interface = ResolveType(dex_file, idx, klass.get());
2158 if (interface == NULL) {
2159 DCHECK(Thread::Current()->IsExceptionPending());
2160 return false;
2161 }
2162 // Verify
2163 if (!klass->CanAccess(interface)) {
2164 // TODO: the RI seemed to ignore this in my testing.
2165 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2166 "Interface %s implemented by class %s is inaccessible",
2167 PrettyDescriptor(interface).c_str(),
2168 PrettyDescriptor(klass.get()).c_str());
2169 return false;
2170 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002171 }
2172 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002173 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002174 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002175 return true;
2176}
2177
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002178bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002179 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002180 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002181 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002182 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002183 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002184 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002185 return false;
2186 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002187 return true;
2188 }
2189 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002190 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002191 return false;
2192 }
2193 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002194 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002195 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002196 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002197 PrettyDescriptor(super).c_str(),
2198 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002199 super->IsFinal() ? "declared final" : "an interface");
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);
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002359 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002360 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002361 PrettyDescriptor(klass.get()).c_str(),
2362 PrettyDescriptor(ih.GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002363 return false;
2364 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002365 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002366 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002367 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002368 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2369 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002370 }
2371 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002372 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002373 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002374
2375 // If we're an interface, we don't need the vtable pointers, so we're done.
2376 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002377 return true;
2378 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002379 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002380 MethodHelper vtable_mh(NULL, this);
2381 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002382 for (size_t i = 0; i < ifcount; ++i) {
2383 InterfaceEntry* interface_entry = iftable->Get(i);
2384 Class* interface = interface_entry->GetInterface();
2385 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2386 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002387 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002388 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2389 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002390 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002391 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002392 // For each method listed in the interface's method list, find the
2393 // matching method in our class's method list. We want to favor the
2394 // subclass over the superclass, which just requires walking
2395 // back from the end of the vtable. (This only matters if the
2396 // superclass defines a private method and this class redefines
2397 // it -- otherwise it would use the same vtable slot. In .dex files
2398 // those don't end up in the virtual method table, so it shouldn't
2399 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002400 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2401 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002402 vtable_mh.ChangeMethod(vtable_method);
2403 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002404 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002405 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002406 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002407 return false;
2408 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002409 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002410 break;
2411 }
2412 }
2413 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002414 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002415 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002416 Method* mir_method = miranda_list[mir];
2417 vtable_mh.ChangeMethod(mir_method);
2418 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002419 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002420 break;
2421 }
2422 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002423 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002424 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002425 miranda_method.reset(AllocMethod());
2426 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2427 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002428 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002429 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 }
2431 }
2432 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002433 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002434 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002435 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002436 klass->SetVirtualMethods((old_method_count == 0)
2437 ? AllocObjectArray<Method>(new_method_count)
2438 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002439
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002440 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2441 CHECK(vtable != NULL);
2442 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002443 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002444 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002445 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002446 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002447 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002448 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2449 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2450 klass->SetVirtualMethod(old_method_count + i, method);
2451 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002452 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002453 // TODO: do not assign to the vtable field until it is fully constructed.
2454 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002455 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002456
2457 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2458 for (int i = 0; i < vtable->GetLength(); ++i) {
2459 CHECK(vtable->Get(i) != NULL);
2460 }
2461
2462// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2463
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002464 return true;
2465}
2466
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002467bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2468 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002469 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002470}
2471
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002472bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2473 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002474 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002475 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002476 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002477 return success;
2478}
2479
Brian Carlstromdbc05252011-09-09 01:59:59 -07002480struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002481 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002482 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002483 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002484 fh_->ChangeField(field1);
2485 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2486 fh_->ChangeField(field2);
2487 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002488 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2489 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2490 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2491 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002492 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2493 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2494 if (order1 != order2) {
2495 return order1 < order2;
2496 }
2497
2498 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002499 fh_->ChangeField(field1);
2500 StringPiece name1(fh_->GetName());
2501 fh_->ChangeField(field2);
2502 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002503 return name1 < name2;
2504 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002505
2506 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002507};
2508
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002509bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002510 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002511 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002512
2513 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002514 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002515
2516 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002517 size_t size;
2518 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002519 if (is_static) {
2520 size = klass->GetClassSize();
2521 field_offset = Class::FieldsOffset();
2522 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002523 Class* super_class = klass->GetSuperClass();
2524 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002525 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002526 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002527 }
2528 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002529 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002530
Brian Carlstromdbc05252011-09-09 01:59:59 -07002531 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002532
Brian Carlstromdbc05252011-09-09 01:59:59 -07002533 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002534 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002535 std::deque<Field*> grouped_and_sorted_fields;
2536 for (size_t i = 0; i < num_fields; i++) {
2537 grouped_and_sorted_fields.push_back(fields->Get(i));
2538 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002539 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002540 std::sort(grouped_and_sorted_fields.begin(),
2541 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002542 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002543
2544 // References should be at the front.
2545 size_t current_field = 0;
2546 size_t num_reference_fields = 0;
2547 for (; current_field < num_fields; current_field++) {
2548 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002549 fh.ChangeField(field);
2550 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002551 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002552 if (isPrimitive) {
2553 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002554 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002555 grouped_and_sorted_fields.pop_front();
2556 num_reference_fields++;
2557 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002558 field->SetOffset(field_offset);
2559 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002560 }
2561
2562 // Now we want to pack all of the double-wide fields together. If
2563 // we're not aligned, though, we want to shuffle one 32-bit field
2564 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002565 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002566 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2567 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002568 fh.ChangeField(field);
2569 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002570 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2571 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002572 continue;
2573 }
2574 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002575 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002576 // drop the consumed field
2577 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2578 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002579 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002580 // whether we found a 32-bit field for padding or not, we advance
2581 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002582 }
2583
2584 // Alignment is good, shuffle any double-wide fields forward, and
2585 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002586 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002587 while (!grouped_and_sorted_fields.empty()) {
2588 Field* field = grouped_and_sorted_fields.front();
2589 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002590 fh.ChangeField(field);
2591 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002592 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002593 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002594 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002595 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002596 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002597 ? sizeof(uint64_t)
2598 : sizeof(uint32_t)));
2599 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002600 }
2601
Elliott Hughesadb460d2011-10-05 17:02:34 -07002602 // 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 -08002603 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2604 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002605 // We know there are no non-reference fields in the Reference classes, and we know
2606 // that 'referent' is alphabetically last, so this is easy...
2607 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002608 fh.ChangeField(fields->Get(num_fields - 1));
2609 StringPiece name(fh.GetName());
2610 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002611 --num_reference_fields;
2612 }
2613
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002614#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002615 // Make sure that all reference fields appear before
2616 // non-reference fields, and all double-wide fields are aligned.
2617 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002618 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002619 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002620 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002621 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002622 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002623 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002624 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2625 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002626 fh.ChangeField(field);
2627 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002628 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002629 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002630 is_primitive = true; // We lied above, so we have to expect a lie here.
2631 }
2632 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002633 if (!seen_non_ref) {
2634 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002635 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002636 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002637 } else {
2638 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002639 }
2640 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002641 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002642 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002643 }
2644#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002645 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002646 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002647 if (is_static) {
2648 klass->SetNumReferenceStaticFields(num_reference_fields);
2649 klass->SetClassSize(size);
2650 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002651 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002652 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002653 klass->SetObjectSize(size);
2654 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002655 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002656 return true;
2657}
2658
2659// Set the bitmap of reference offsets, refOffsets, from the ifields
2660// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002661void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002662 uint32_t reference_offsets = 0;
2663 Class* super_class = klass->GetSuperClass();
2664 if (super_class != NULL) {
2665 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002666 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002667 if (reference_offsets == CLASS_WALK_SUPER) {
2668 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002669 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002670 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002671 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002672 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002673}
2674
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002675void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002676 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002677}
2678
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002679void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002680 uint32_t reference_offsets) {
2681 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002682 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2683 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002684 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002685 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002686 // All of the fields that contain object references are guaranteed
2687 // to be at the beginning of the fields list.
2688 for (size_t i = 0; i < num_reference_fields; ++i) {
2689 // Note that byte_offset is the offset from the beginning of
2690 // object, not the offset into instance data
2691 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002692 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002693 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2694 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2695 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002696 CHECK_NE(new_bit, 0U);
2697 reference_offsets |= new_bit;
2698 } else {
2699 reference_offsets = CLASS_WALK_SUPER;
2700 break;
2701 }
2702 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002703 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002704 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002705 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002706 } else {
2707 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002708 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002709}
2710
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002711String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002712 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002713 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002714 if (resolved != NULL) {
2715 return resolved;
2716 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002717 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2718 int32_t utf16_length = dex_file.GetStringLength(string_id);
2719 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002720 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002721 dex_cache->SetResolvedString(string_idx, string);
2722 return string;
2723}
2724
2725Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002726 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002727 DexCache* dex_cache,
2728 const ClassLoader* class_loader) {
2729 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002730 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002731 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002732 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002733 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002734 // TODO: we used to throw here if resolved's class loader was not the
2735 // boot class loader. This was to permit different classes with the
2736 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002737 dex_cache->SetResolvedType(type_idx, resolved);
2738 } else {
2739 DCHECK(Thread::Current()->IsExceptionPending());
2740 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002741 }
2742 return resolved;
2743}
2744
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002745Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2746 uint32_t method_idx,
2747 DexCache* dex_cache,
2748 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002749 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002750 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2751 if (resolved != NULL) {
2752 return resolved;
2753 }
2754 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2755 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2756 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002757 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002758 return NULL;
2759 }
2760
Ian Rogers0571d352011-11-03 19:51:38 -07002761 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2762 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002763 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002764 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002765 } else if (klass->IsInterface()) {
2766 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002767 } else {
2768 resolved = klass->FindVirtualMethod(name, signature);
2769 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002770 if (resolved != NULL) {
2771 dex_cache->SetResolvedMethod(method_idx, resolved);
2772 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002773 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002774 }
2775 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002776}
2777
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002778Field* ClassLinker::ResolveField(const DexFile& dex_file,
2779 uint32_t field_idx,
2780 DexCache* dex_cache,
2781 const ClassLoader* class_loader,
2782 bool is_static) {
2783 Field* resolved = dex_cache->GetResolvedField(field_idx);
2784 if (resolved != NULL) {
2785 return resolved;
2786 }
2787 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2788 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2789 if (klass == NULL) {
2790 return NULL;
2791 }
2792
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002793 const char* name = dex_file.GetFieldName(field_id);
2794 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002795 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002796 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002797 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002798 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002799 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002800 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002801 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002802 } else {
Jesse Wilson47daf872011-11-23 11:42:45 -05002803 // TODO: this check fails when the app class path contains a class from the boot class path
2804 CHECK(Thread::Current()->IsExceptionPending())
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002805 << PrettyClass(klass) << " " << name << " " << type << " " << is_static;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002806 }
2807 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002808}
2809
Ian Rogersad25ac52011-10-04 19:13:33 -07002810const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2811 Class* declaring_class = referrer->GetDeclaringClass();
2812 DexCache* dex_cache = declaring_class->GetDexCache();
2813 const DexFile& dex_file = FindDexFile(dex_cache);
2814 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2815 return dex_file.GetShorty(method_id.proto_idx_);
2816}
2817
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002818void ClassLinker::DumpAllClasses(int flags) const {
2819 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2820 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2821 std::vector<Class*> all_classes;
2822 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002823 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002824 typedef Table::const_iterator It; // TODO: C++0x auto
2825 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2826 all_classes.push_back(it->second);
2827 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002828 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2829 all_classes.push_back(it->second);
2830 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002831 }
2832
2833 for (size_t i = 0; i < all_classes.size(); ++i) {
2834 all_classes[i]->DumpClass(std::cerr, flags);
2835 }
2836}
2837
Elliott Hughescac6cc72011-11-03 20:31:21 -07002838void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2839 MutexLock mu(classes_lock_);
2840 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2841 << classes_.size() << " allocated classes\n";
2842}
2843
Elliott Hughese27955c2011-08-26 15:21:24 -07002844size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002845 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002846 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002847}
2848
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002849pid_t ClassLinker::GetClassesLockOwner() {
2850 return classes_lock_.GetOwner();
2851}
2852
2853pid_t ClassLinker::GetDexLockOwner() {
2854 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002855}
2856
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002857void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
2858 DCHECK(!init_done_);
2859
2860 DCHECK(klass != NULL);
2861 DCHECK(klass->GetClassLoader() == NULL);
2862
2863 DCHECK(class_roots_ != NULL);
2864 DCHECK(class_roots_->Get(class_root) == NULL);
2865 class_roots_->Set(class_root, klass);
2866}
2867
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002868} // namespace art