blob: b06d1086bb2ea135328d1a5eb13f910be14f4d68 [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 Carlstromd601af82012-01-06 10:15:19 -08005#include <fcntl.h>
6#include <sys/file.h>
7#include <sys/stat.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -08008#include <sys/types.h>
9#include <sys/wait.h>
10
Brian Carlstromdbc05252011-09-09 01:59:59 -070011#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070012#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070013#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070014#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070015
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070016#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070017#include "class_loader.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080018#include "debugger.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070019#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070020#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070021#include "dex_verifier.h"
22#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070023#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070024#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070026#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070027#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070028#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070030#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070031#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070032#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070033#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070034#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070035#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070036#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070037#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070039
40namespace art {
41
Elliott Hughes4a2b4172011-09-20 17:08:25 -070042namespace {
43
Elliott Hughes362f9bc2011-10-17 18:56:41 -070044void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070045void ThrowNoClassDefFoundError(const char* fmt, ...) {
46 va_list args;
47 va_start(args, fmt);
48 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
49 va_end(args);
50}
51
Elliott Hughes362f9bc2011-10-17 18:56:41 -070052void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070053void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070054 va_list args;
55 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070056 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070057 va_end(args);
58}
59
Elliott Hughes362f9bc2011-10-17 18:56:41 -070060void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070061void ThrowLinkageError(const char* fmt, ...) {
62 va_list args;
63 va_start(args, fmt);
64 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
65 va_end(args);
66}
67
Ian Rogers9f1ab122011-12-12 08:52:43 -080068void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
69 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080070 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070071 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080072 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
73 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080074 std::string location(kh.GetLocation());
75 if (!location.empty()) {
76 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070077 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070078 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070079}
80
Ian Rogersb067ac22011-12-13 18:05:09 -080081void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080082 const StringPiece& name) {
83 ClassHelper kh(c);
84 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080085 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080086 << " in class " << kh.GetDescriptor() << " or its superclasses";
87 std::string location(kh.GetLocation());
88 if (!location.empty()) {
89 msg << " (defined in " << location << ")";
90 }
91 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
92}
93
Ian Rogerscab01012012-01-10 17:35:46 -080094void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
95void ThrowNullPointerException(const char* fmt, ...) {
96 va_list args;
97 va_start(args, fmt);
98 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
99 va_end(args);
100}
101
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700102void ThrowEarlierClassFailure(Class* c) {
103 /*
104 * The class failed to initialize on a previous attempt, so we want to throw
105 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
106 * failed in verification, in which case v2 5.4.1 says we need to re-throw
107 * the previous error.
108 */
109 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
110
111 if (c->GetVerifyErrorClass() != NULL) {
112 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800113 ClassHelper ve_ch(c->GetVerifyErrorClass());
114 std::string error_descriptor(ve_ch.GetDescriptor());
115 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700116 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800117 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118 }
119}
120
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700121void WrapExceptionInInitializer() {
122 JNIEnv* env = Thread::Current()->GetJniEnv();
123
124 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
125 CHECK(cause.get() != NULL);
126
127 env->ExceptionClear();
128
129 // TODO: add java.lang.Error to JniConstants?
130 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
131 CHECK(error_class.get() != NULL);
132 if (env->IsInstanceOf(cause.get(), error_class.get())) {
133 // We only wrap non-Error exceptions; an Error can just be used as-is.
134 env->Throw(cause.get());
135 return;
136 }
137
138 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
139 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
140 CHECK(eiie_class.get() != NULL);
141
142 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
143 CHECK(mid != NULL);
144
145 ScopedLocalRef<jthrowable> eiie(env,
146 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
147 env->Throw(eiie.get());
148}
149
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800150static size_t Hash(const char* s) {
151 // This is the java.lang.String hashcode for convenience, not interoperability.
152 size_t hash = 0;
153 for (; *s != '\0'; ++s) {
154 hash = hash * 31 + *s;
155 }
156 return hash;
157}
158
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700159} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700160
Elliott Hughes418d20f2011-09-22 14:00:39 -0700161const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700162 "Ljava/lang/Class;",
163 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700164 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700165 "[Ljava/lang/Object;",
166 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700167 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700168 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700169 "Ljava/lang/reflect/Field;",
170 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700171 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700172 "Ljava/lang/ClassLoader;",
173 "Ldalvik/system/BaseDexClassLoader;",
174 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700175 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700176 "Z",
177 "B",
178 "C",
179 "D",
180 "F",
181 "I",
182 "J",
183 "S",
184 "V",
185 "[Z",
186 "[B",
187 "[C",
188 "[D",
189 "[F",
190 "[I",
191 "[J",
192 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700193 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700194};
195
Elliott Hughes5f791332011-09-15 17:45:30 -0700196class ObjectLock {
197 public:
198 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
199 CHECK(object != NULL);
200 obj_->MonitorEnter(self_);
201 }
202
203 ~ObjectLock() {
204 obj_->MonitorExit(self_);
205 }
206
207 void Wait() {
208 return Monitor::Wait(self_, obj_, 0, 0, false);
209 }
210
211 void Notify() {
212 obj_->Notify();
213 }
214
215 void NotifyAll() {
216 obj_->NotifyAll();
217 }
218
219 private:
220 Thread* self_;
221 Object* obj_;
222 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
223};
224
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800225ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700226 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800227 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700228 class_linker->Init(boot_class_path);
229 return class_linker.release();
230}
231
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800232ClassLinker* ClassLinker::Create(InternTable* intern_table) {
233 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700234 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700235 return class_linker.release();
236}
237
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800238ClassLinker::ClassLinker(InternTable* intern_table)
239 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700240 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700241 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700243 init_done_(false),
244 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700245 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700246}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700247
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700248void CreateClassPath(const std::string& class_path,
249 std::vector<const DexFile*>& class_path_vector) {
250 std::vector<std::string> parsed;
251 Split(class_path, ':', parsed);
252 for (size_t i = 0; i < parsed.size(); ++i) {
253 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700254 if (dex_file == NULL) {
255 LOG(WARNING) << "Failed to open dex file " << parsed[i];
256 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700257 class_path_vector.push_back(dex_file);
258 }
259 }
260}
261
262void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800263 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700264
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700265 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700266
Elliott Hughes30646832011-10-13 16:59:46 -0700267 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700268 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
269 CHECK(java_lang_Class.get() != NULL);
270 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700272 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700273
Elliott Hughes418d20f2011-09-22 14:00:39 -0700274 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700275 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
276 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700277
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700278 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700279 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
280 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700281 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700284
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700286 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
287 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700288
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700289 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700290 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700291
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700293 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
294 char_array_class->SetComponentType(char_class.get());
295 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700296
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700298 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
299 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300 java_lang_String->SetObjectSize(sizeof(String));
301 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400302
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303 // Create storage for root classes, save away our work so far (requires
304 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700305 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700306 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700307 SetClassRoot(kJavaLangClass, java_lang_Class.get());
308 SetClassRoot(kJavaLangObject, java_lang_Object.get());
309 SetClassRoot(kClassArrayClass, class_array_class.get());
310 SetClassRoot(kObjectArrayClass, object_array_class.get());
311 SetClassRoot(kCharArrayClass, char_array_class.get());
312 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313
314 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700315 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
316 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
317 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
318 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
319 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
320 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
321 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
322 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700323
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700324 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700325 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326
327 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700328 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700329 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 IntArray::SetArrayClass(int_array_class.get());
331 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700333 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700334
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700335 // setup boot_class_path_ and register class_path now that we can
336 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700337 std::vector<const DexFile*> boot_class_path_vector;
338 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700339 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700340 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
341 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700342 CHECK(dex_file != NULL);
343 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700344 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345
Elliott Hughes80609252011-09-23 17:24:51 -0700346 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700349 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700351 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
352
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700353 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
354 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700356 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700358 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700360 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700361 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700363 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700365 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366
367 // now we can use FindSystemClass
368
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700369 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700370 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700371 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700372
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700373 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 java_lang_Object->SetStatus(Class::kStatusNotReady);
375 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700376 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
378 java_lang_String->SetStatus(Class::kStatusNotReady);
379 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700380 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
382
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700383 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
385 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
386
387 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
388 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
389
390 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700391 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392
393 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
394 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
395
396 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700397 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398
399 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
400 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
401
402 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
403 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
404
405 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
406 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
407
Elliott Hughes418d20f2011-09-22 14:00:39 -0700408 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700409 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700410
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700412 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
414 // Setup the single, global copies of "interfaces" and "iftable"
415 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
416 CHECK(java_lang_Cloneable != NULL);
417 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
418 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419 // We assume that Cloneable/Serializable don't have superinterfaces --
420 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700421 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800422 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
423 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700424
Elliott Hughes418d20f2011-09-22 14:00:39 -0700425 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800426 ClassHelper kh(class_array_class.get(), this);
427 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
428 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
429 kh.ChangeClass(object_array_class.get());
430 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
431 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700432 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700433 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700434 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700435 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436
Elliott Hughes80609252011-09-23 17:24:51 -0700437 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
438 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700439 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700440
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700442 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700443 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444
445 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700446 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700447 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700448
Ian Rogers466bb252011-10-14 03:29:56 -0700449 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
450
451 // Create java.lang.reflect.Proxy root
452 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
453 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
454
Brian Carlstrom1f870082011-08-23 16:02:11 -0700455 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700456 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
457 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700458 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459 java_lang_ref_FinalizerReference->SetAccessFlags(
460 java_lang_ref_FinalizerReference->GetAccessFlags() |
461 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700462 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463 java_lang_ref_PhantomReference->SetAccessFlags(
464 java_lang_ref_PhantomReference->GetAccessFlags() |
465 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700466 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467 java_lang_ref_SoftReference->SetAccessFlags(
468 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700469 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470 java_lang_ref_WeakReference->SetAccessFlags(
471 java_lang_ref_WeakReference->GetAccessFlags() |
472 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700473
Brian Carlstromaded5f72011-10-07 17:15:04 -0700474 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700476 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
478
479 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
480 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
481 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
482
483 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
484 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
485 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
486 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
487
488 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700489 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
490 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700491 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700492
Brian Carlstroma663ea52011-08-19 23:33:41 -0700493 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700494
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800495 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700496}
497
498void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800499 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700500
501 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700502 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700503 // as the types of the field can't be resolved prior to the runtime being
504 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700505 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700506 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700507 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
508
Elliott Hughesadb460d2011-10-05 17:02:34 -0700509 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
510
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800511 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
512
Brian Carlstrom16192862011-09-12 17:50:06 -0700513 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800514 FieldHelper fh(pendingNext, this);
515 CHECK_STREQ(fh.GetName(), "pendingNext");
516 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
517 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700518
519 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800520 fh.ChangeField(queue);
521 CHECK_STREQ(fh.GetName(), "queue");
522 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
523 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700524
525 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800526 fh.ChangeField(queueNext);
527 CHECK_STREQ(fh.GetName(), "queueNext");
528 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
529 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700530
531 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800532 fh.ChangeField(referent);
533 CHECK_STREQ(fh.GetName(), "referent");
534 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
535 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700536
537 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800538 fh.ChangeField(zombie);
539 CHECK_STREQ(fh.GetName(), "zombie");
540 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
541 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700542
543 Heap::SetReferenceOffsets(referent->GetOffset(),
544 queue->GetOffset(),
545 queueNext->GetOffset(),
546 pendingNext->GetOffset(),
547 zombie->GetOffset());
548
Brian Carlstroma663ea52011-08-19 23:33:41 -0700549 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700551 ClassRoot class_root = static_cast<ClassRoot>(i);
552 Class* klass = GetClassRoot(class_root);
553 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700555 // note SetClassRoot does additional validation.
556 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700557 }
558
Elliott Hughes92f14b22011-10-06 12:29:54 -0700559 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700560
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700561 // disable the slow paths in FindClass and CreatePrimitiveClass now
562 // that Object, Class, and Object[] are setup
563 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700564
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800565 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700566}
567
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700568void ClassLinker::RunRootClinits() {
569 Thread* self = Thread::Current();
570 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
571 Class* c = GetClassRoot(ClassRoot(i));
572 if (!c->IsArrayClass() && !c->IsPrimitive()) {
573 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700574 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700575 }
576 }
577}
578
Brian Carlstromd601af82012-01-06 10:15:19 -0800579bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
580 int oat_fd,
581 const std::string& oat_cache_filename) {
jeffhao262bf462011-10-20 18:36:32 -0700582
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800583 std::string dex2oat_string("/system/bin/dex2oat");
584#ifndef NDEBUG
585 dex2oat_string += 'd';
586#endif
587 const char* dex2oat = dex2oat_string.c_str();
588
589 const char* class_path = Runtime::Current()->GetClassPath().c_str();
590
591 std::string boot_image_option_string("--boot-image=");
592 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
593 const char* boot_image_option = boot_image_option_string.c_str();
594
595 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800596 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800597 const char* dex_file_option = dex_file_option_string.c_str();
598
Brian Carlstromd601af82012-01-06 10:15:19 -0800599 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800600 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800601 const char* oat_fd_option = oat_fd_option_string.c_str();
602
603 std::string oat_name_option_string("--oat-name=");
604 oat_name_option_string += oat_cache_filename;
605 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800606
jeffhao262bf462011-10-20 18:36:32 -0700607 // fork and exec dex2oat
608 pid_t pid = fork();
609 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800610 // no allocation allowed between fork and exec
611 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700612 "--runtime-arg", "-Xms64m",
613 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500614 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800615 "--runtime-arg", class_path,
616 boot_image_option,
617 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800618 oat_fd_option,
619 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700620 NULL);
621
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800622 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800623 return false;
jeffhao262bf462011-10-20 18:36:32 -0700624 } else {
625 // wait for dex2oat to finish
626 int status;
627 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
628 if (got_pid != pid) {
629 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800630 return false;
jeffhao262bf462011-10-20 18:36:32 -0700631 }
632 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800633 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
634 return false;
jeffhao262bf462011-10-20 18:36:32 -0700635 }
636 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800637 return true;
jeffhao262bf462011-10-20 18:36:32 -0700638}
639
Brian Carlstrom866c8622012-01-06 16:35:13 -0800640void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
641 MutexLock mu(dex_lock_);
642 RegisterOatFileLocked(oat_file);
643}
644
645void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
646 dex_lock_.AssertHeld();
647 oat_files_.push_back(&oat_file);
648}
649
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700650OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700651 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700652 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800653 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800655 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
656 // check the down cast
657 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700658 std::string oat_filename;
659 oat_filename += runtime->GetHostPrefix();
660 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700661 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700662 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700663 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700664 return NULL;
665 }
666 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
667 uint32_t image_oat_checksum = image_header.GetOatChecksum();
668 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800669 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700670 << " to expected oat checksum " << std::hex << oat_checksum
671 << " in image";
672 return NULL;
673 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800674 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800675 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700676 return oat_file;
677}
678
Brian Carlstromae826982011-11-09 01:33:42 -0800679const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
680 for (size_t i = 0; i < oat_files_.size(); i++) {
681 const OatFile* oat_file = oat_files_[i];
682 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800683 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800684 return oat_file;
685 }
686 }
687 return NULL;
688}
689
Brian Carlstromd601af82012-01-06 10:15:19 -0800690class LockedFd {
691 public:
692 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
693 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
694 if (fd == -1) {
695 PLOG(ERROR) << "Failed to open file '" << name << "'";
696 return NULL;
697 }
698 fchmod(fd, mode);
699
700 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
701 // try to lock non-blocking so we can log if we need may need to block
702 int result = flock(fd, LOCK_EX | LOCK_NB);
703 if (result == -1) {
704 LOG(WARNING) << "sleeping while locking file " << name;
705 // retry blocking
706 result = flock(fd, LOCK_EX);
707 }
708 if (result == -1) {
709 PLOG(ERROR) << "Failed to lock file '" << name << "'";
710 close(fd);
711 return NULL;
712 }
713 return new LockedFd(fd);
714 }
715
716 int GetFd() const {
717 return fd_;
718 }
719
720 ~LockedFd() {
721 if (fd_ != -1) {
722 int result = flock(fd_, LOCK_UN);
723 if (result == -1) {
724 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
725 }
726 close(fd_);
727 }
728 }
729
730 private:
731 explicit LockedFd(int fd) : fd_(fd) {}
732
733 int fd_;
734};
735
Brian Carlstromae826982011-11-09 01:33:42 -0800736const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700737 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800738 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
739 if (open_oat_file != NULL) {
740 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800741 }
742
Brian Carlstromd601af82012-01-06 10:15:19 -0800743 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800744 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
745 if (open_oat_file != NULL) {
746 return open_oat_file;
747 }
748
Brian Carlstromd601af82012-01-06 10:15:19 -0800749 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800750 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
751 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800752 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
753 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800754 RegisterOatFileLocked(*oat_file.get());
755 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800756 }
757 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
758 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
759 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
760 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
761 }
762 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700763 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800764 // Try to generate oat file if it wasn't found or was obsolete.
765 // Note we can be racing with another runtime to do this.
766 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
767 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
768 if (locked_fd.get() == NULL) {
769 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
770 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700771 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800772 // Check to see if the fd we opened and locked matches the file in
773 // the filesystem. If they don't, then somebody else unlinked ours
774 // and created a new file, and we need to use that one instead. (If
775 // we caught them between the unlink and the create, we'll get an
776 // ENOENT from the file stat.)
777 struct stat fd_stat;
778 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
779 if (fd_stat_result != 0) {
780 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
781 return NULL;
782 }
783 struct stat file_stat;
784 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
785 if (file_stat_result != 0
786 || fd_stat.st_dev != file_stat.st_dev
787 || fd_stat.st_ino != file_stat.st_ino) {
788 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
789 usleep(250 * 1000); // if something is hosed, don't peg machine
790 continue;
791 }
792
793 // We have the correct file open and locked. If the file size is
794 // zero, then it was just created by us and we can generate its
795 // contents. If not, someone else created it. Either way, we'll
796 // loop to retry opening the file.
797 if (fd_stat.st_size == 0) {
798 bool success = GenerateOatFile(dex_file.GetLocation(),
799 locked_fd->GetFd(),
800 oat_cache_filename);
801 if (!success) {
802 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
803 return NULL;
804 }
805 }
jeffhao262bf462011-10-20 18:36:32 -0700806 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800807 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700808}
809
Brian Carlstromae826982011-11-09 01:33:42 -0800810const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700811 for (size_t i = 0; i < oat_files_.size(); i++) {
812 const OatFile* oat_file = oat_files_[i];
813 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800814 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700815 return oat_file;
816 }
817 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700818 return NULL;
819}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700820
Brian Carlstromae826982011-11-09 01:33:42 -0800821const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800822 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700823 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800824 if (oat_location.empty() || oat_location[0] != '/') {
825 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700826 return NULL;
827 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700828
Brian Carlstroma9f19782011-10-13 00:14:47 -0700829 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800830 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800831 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700832 if (oat_file != NULL) {
833 return oat_file;
834 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700835 oat_file = OatFile::Open(cache_location, "", NULL);
836 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800837 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700838 return NULL;
839 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700840 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700841
Brian Carlstromae826982011-11-09 01:33:42 -0800842 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700843 return oat_file;
844}
845
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700846void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800847 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700848 CHECK(!init_done_);
849
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700850 const std::vector<Space*>& spaces = Heap::GetSpaces();
851 for (size_t i = 0; i < spaces.size(); i++) {
852 Space* space = spaces[i] ;
853 if (space->IsImageSpace()) {
854 OatFile* oat_file = OpenOat(space);
855 CHECK(oat_file != NULL) << "Failed to open oat file for image";
856 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
857 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
858
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800859 if (i == 0) {
860 // Special case of setting up the String class early so that we can test arbitrary objects
861 // as being Strings or not
862 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
863 ->AsObjectArray<Class>()->Get(kJavaLangString);
864 String::SetClass(java_lang_String);
865 }
866
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700867 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
868 static_cast<uint32_t>(dex_caches->GetLength()));
869 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700870 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800871 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800872 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
873 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700874 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800875 LOG(FATAL) << "Failed to open dex file " << dex_file_location
876 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700877 }
878
Brian Carlstromaded5f72011-10-07 17:15:04 -0700879 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700880
Brian Carlstromdf143242011-10-10 18:05:34 -0700881 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700882 }
883 }
884 }
885
Brian Carlstroma663ea52011-08-19 23:33:41 -0700886 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
887 DCHECK(heap_bitmap != NULL);
888
Brian Carlstroma663ea52011-08-19 23:33:41 -0700889 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700890 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700891
892 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700893 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
894 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700895
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800896 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700897 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
898 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800899 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700900 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700901 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700902 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
903 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
904 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
905 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
906 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
907 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
908 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
909 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700910 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700911 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700912
913 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700914
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800915 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700916}
917
Brian Carlstrom78128a62011-09-15 17:21:19 -0700918void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700919 DCHECK(obj != NULL);
920 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700921 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700922
Elliott Hughesdbb40792011-11-18 17:05:22 -0800923 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700924 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700925 return;
926 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700927 if (obj->IsClass()) {
928 // restore class to ClassLinker::classes_ table
929 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800930 ClassHelper kh(klass, class_linker);
931 bool success = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
Ian Rogers5d76c432011-10-31 21:42:49 -0700932 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700933 return;
934 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700935}
936
937// Keep in sync with InitCallback. Anything we visit, we need to
938// reinit references to when reinitializing a ClassLinker from a
939// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700940void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
941 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700942
943 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700944 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700945 }
946
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700947 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700948 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700949 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700950 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700951 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700952 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700953 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700954 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700955
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700956 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700957}
958
Elliott Hughesa2155262011-11-16 16:26:58 -0800959void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
960 MutexLock mu(classes_lock_);
961 typedef Table::const_iterator It; // TODO: C++0x auto
962 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
963 if (!visitor(it->second, arg)) {
964 return;
965 }
966 }
967 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
968 if (!visitor(it->second, arg)) {
969 return;
970 }
971 }
972}
973
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700974ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700975 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700976 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700977 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700978 BooleanArray::ResetArrayClass();
979 ByteArray::ResetArrayClass();
980 CharArray::ResetArrayClass();
981 DoubleArray::ResetArrayClass();
982 FloatArray::ResetArrayClass();
983 IntArray::ResetArrayClass();
984 LongArray::ResetArrayClass();
985 ShortArray::ResetArrayClass();
986 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700987 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700988 STLDeleteElements(&boot_class_path_);
989 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700990}
991
992DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700993 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
994 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700995 return NULL;
996 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700997 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
998 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700999 return NULL;
1000 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001001 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1002 if (strings.get() == NULL) {
1003 return NULL;
1004 }
1005 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1006 if (types.get() == NULL) {
1007 return NULL;
1008 }
1009 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1010 if (methods.get() == NULL) {
1011 return NULL;
1012 }
1013 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1014 if (fields.get() == NULL) {
1015 return NULL;
1016 }
1017 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1018 if (code_and_direct_methods.get() == NULL) {
1019 return NULL;
1020 }
1021 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1022 if (initialized_static_storage.get() == NULL) {
1023 return NULL;
1024 }
1025
1026 dex_cache->Init(location.get(),
1027 strings.get(),
1028 types.get(),
1029 methods.get(),
1030 fields.get(),
1031 code_and_direct_methods.get(),
1032 initialized_static_storage.get());
1033 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001034}
1035
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001036CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1037 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001038}
1039
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001040InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1041 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001042 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1043 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001044 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001045 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001046}
1047
Brian Carlstrom4873d462011-08-21 15:23:39 -07001048Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1049 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001050 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001051 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001052 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001053 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001054}
1055
Brian Carlstrom4873d462011-08-21 15:23:39 -07001056Class* ClassLinker::AllocClass(size_t class_size) {
1057 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001058}
1059
Jesse Wilson35baaab2011-08-10 16:18:03 -04001060Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001061 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001062}
1063
1064Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001065 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001066}
1067
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001068ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1069 return ObjectArray<StackTraceElement>::Alloc(
1070 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1071 length);
1072}
1073
Brian Carlstromaded5f72011-10-07 17:15:04 -07001074Class* EnsureResolved(Class* klass) {
1075 DCHECK(klass != NULL);
1076 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001077 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001078 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001079 ObjectLock lock(klass);
1080 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001081 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001082 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001083 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001084 return NULL;
1085 }
1086 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001087 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001088 lock.Wait();
1089 }
1090 }
1091 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001092 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001093 return NULL;
1094 }
1095 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001096 CHECK(klass->IsResolved()) << PrettyClass(klass);
1097 CHECK(!self->IsExceptionPending())
1098 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1099 return klass;
1100}
1101
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001102Class* ClassLinker::FindSystemClass(const char* descriptor) {
1103 return FindClass(descriptor, NULL);
1104}
1105
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001106Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
1107 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001108 Thread* self = Thread::Current();
1109 DCHECK(self != NULL);
1110 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001111 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001112 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1113 // for primitive classes that aren't backed by dex files.
1114 return FindPrimitiveClass(descriptor[0]);
1115 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001116 // Find the class in the loaded classes table.
1117 Class* klass = LookupClass(descriptor, class_loader);
1118 if (klass != NULL) {
1119 return EnsureResolved(klass);
1120 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 // Class is not yet loaded.
1122 if (descriptor[0] == '[') {
1123 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001124
Jesse Wilson47daf872011-11-23 11:42:45 -05001125 } else if (class_loader == NULL) {
1126 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1127 if (pair.second != NULL) {
1128 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1129 }
1130
1131 } else if (ClassLoader::UseCompileTimeClassPath()) {
1132 // first try the boot class path
1133 Class* system_class = FindSystemClass(descriptor);
1134 if (system_class != NULL) {
1135 return system_class;
1136 }
1137 CHECK(self->IsExceptionPending());
1138 self->ClearException();
1139
1140 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001141 const std::vector<const DexFile*>& class_path
1142 = ClassLoader::GetCompileTimeClassPath(class_loader);
1143 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001144 if (pair.second != NULL) {
1145 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001146 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001147
1148 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001149 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001150 ScopedThreadStateChange(self, Thread::kNative);
1151 JNIEnv* env = self->GetJniEnv();
1152 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1153 CHECK(c.get() != NULL);
1154 // TODO: cache method?
1155 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1156 CHECK(mid != NULL);
1157 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1158 if (class_name_object.get() == NULL) {
1159 return NULL;
1160 }
1161 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1162 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
Ian Rogerscab01012012-01-10 17:35:46 -08001163 if (result.get() == NULL) {
1164 // broken loader - throw NPE to be compatible with Dalvik
1165 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1166 class_name_string.c_str());
1167 return NULL;
1168 } else if (!env->ExceptionOccurred()) {
1169 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001170 return Decode<Class*>(env, result.get());
1171 } else {
1172 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1173 // TODO: initialize the cause of the NCDFE to this exception
1174 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001175 }
1176
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001177 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001178 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001179}
1180
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001181Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001182 const ClassLoader* class_loader,
1183 const DexFile& dex_file,
1184 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001185 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001186 // Load the class from the dex file.
1187 if (!init_done_) {
1188 // finish up init of hand crafted class_roots_
1189 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001190 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001191 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001192 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001193 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001194 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001195 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001196 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001197 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001198 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001199 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001200 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001201 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001202 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001203 }
1204 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001205 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001206 }
1207 klass->SetDexCache(FindDexCache(dex_file));
1208 LoadClass(dex_file, dex_class_def, klass, class_loader);
1209 // Check for a pending exception during load
1210 Thread* self = Thread::Current();
1211 if (self->IsExceptionPending()) {
1212 return NULL;
1213 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001214 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001215 klass->SetClinitThreadId(self->GetTid());
1216 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001217 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001218 if (!success) {
1219 // We may fail to insert if we raced with another thread.
1220 klass->SetClinitThreadId(0);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001221 klass.reset(LookupClass(descriptor.data(), class_loader));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001222 CHECK(klass.get() != NULL);
1223 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001224 }
1225 // Finish loading (if necessary) by finding parents
1226 CHECK(!klass->IsLoaded());
1227 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1228 // Loading failed.
1229 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001230 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001231 lock.NotifyAll();
1232 return NULL;
1233 }
1234 CHECK(klass->IsLoaded());
1235 // Link the class (if necessary)
1236 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001237 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001238 // Linking failed.
1239 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001240 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001241 lock.NotifyAll();
1242 return NULL;
1243 }
1244 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001245
1246 /*
1247 * We send CLASS_PREPARE events to the debugger from here. The
1248 * definition of "preparation" is creating the static fields for a
1249 * class and initializing them to the standard default values, but not
1250 * executing any code (that comes later, during "initialization").
1251 *
1252 * We did the static preparation in LinkClass.
1253 *
1254 * The class has been prepared and resolved but possibly not yet verified
1255 * at this point.
1256 */
1257 Dbg::PostClassPrepare(klass.get());
1258
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001259 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001260}
1261
Brian Carlstrom4873d462011-08-21 15:23:39 -07001262// Precomputes size that will be needed for Class, matching LinkStaticFields
1263size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1264 const DexFile::ClassDef& dex_class_def) {
1265 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001266 size_t num_ref = 0;
1267 size_t num_32 = 0;
1268 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001269 if (class_data != NULL) {
1270 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1271 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001272 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001273 char c = descriptor[0];
1274 if (c == 'L' || c == '[') {
1275 num_ref++;
1276 } else if (c == 'J' || c == 'D') {
1277 num_64++;
1278 } else {
1279 num_32++;
1280 }
1281 }
1282 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001283 // start with generic class data
1284 size_t size = sizeof(Class);
1285 // follow with reference fields which must be contiguous at start
1286 size += (num_ref * sizeof(uint32_t));
1287 // if there are 64-bit fields to add, make sure they are aligned
1288 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1289 if (num_32 != 0) {
1290 // use an available 32-bit field for padding
1291 num_32--;
1292 }
1293 size += sizeof(uint32_t); // either way, we are adding a word
1294 DCHECK_EQ(size, RoundUp(size, 8));
1295 }
1296 // tack on any 64-bit fields now that alignment is assured
1297 size += (num_64 * sizeof(uint64_t));
1298 // tack on any remaining 32-bit fields
1299 size += (num_32 * sizeof(uint32_t));
1300 return size;
1301}
1302
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001303void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001304 // Every kind of method should at least get an invoke stub from the oat_method.
1305 // non-abstract methods also get their code pointers.
1306 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001307 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001308
1309 if (method->IsAbstract()) {
1310 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1311 return;
1312 }
1313 if (method->IsNative()) {
1314 // unregistering restores the dlsym lookup stub
1315 method->UnregisterNative();
1316 return;
1317 }
1318}
1319
Brian Carlstromf615a612011-07-23 12:50:34 -07001320void ClassLinker::LoadClass(const DexFile& dex_file,
1321 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001322 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001323 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001324 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001325 CHECK(klass->GetDexCache() != NULL);
1326 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001327 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001328 CHECK(descriptor != NULL);
1329
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001330 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001331 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001332 // Make sure that none of our runtime-only flags are set.
1333 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001334 klass->SetAccessFlags(access_flags);
1335 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001336 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001337 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001338
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001339 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001340
Ian Rogers0571d352011-11-03 19:51:38 -07001341 // Load fields fields.
1342 const byte* class_data = dex_file.GetClassData(dex_class_def);
1343 if (class_data == NULL) {
1344 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001345 }
Ian Rogers0571d352011-11-03 19:51:38 -07001346 ClassDataItemIterator it(dex_file, class_data);
1347 if (it.NumStaticFields() != 0) {
1348 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1349 }
1350 if (it.NumInstanceFields() != 0) {
1351 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1352 }
1353 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1354 SirtRef<Field> sfield(AllocField());
1355 klass->SetStaticField(i, sfield.get());
1356 LoadField(dex_file, it, klass, sfield);
1357 }
1358 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1359 SirtRef<Field> ifield(AllocField());
1360 klass->SetInstanceField(i, ifield.get());
1361 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001362 }
1363
Brian Carlstromaded5f72011-10-07 17:15:04 -07001364 UniquePtr<const OatFile::OatClass> oat_class;
1365 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001366 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001367 if (oat_file != NULL) {
1368 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1369 if (oat_dex_file != NULL) {
1370 uint32_t class_def_index;
1371 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1372 CHECK(found) << descriptor;
1373 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001374 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001375 }
1376 }
1377 }
Ian Rogers0571d352011-11-03 19:51:38 -07001378 // Load methods.
1379 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001380 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001381 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001382 }
Ian Rogers0571d352011-11-03 19:51:38 -07001383 if (it.NumVirtualMethods() != 0) {
1384 // TODO: append direct methods to class object
1385 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001386 }
Ian Rogers0571d352011-11-03 19:51:38 -07001387 size_t method_index = 0;
1388 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1389 SirtRef<Method> method(AllocMethod());
1390 klass->SetDirectMethod(i, method.get());
1391 LoadMethod(dex_file, it, klass, method);
1392 if (oat_class.get() != NULL) {
1393 LinkCode(method, oat_class.get(), method_index);
1394 }
1395 method_index++;
1396 }
1397 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1398 SirtRef<Method> method(AllocMethod());
1399 klass->SetVirtualMethod(i, method.get());
1400 LoadMethod(dex_file, it, klass, method);
1401 if (oat_class.get() != NULL) {
1402 LinkCode(method, oat_class.get(), method_index);
1403 }
1404 method_index++;
1405 }
1406 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001407}
1408
Ian Rogers0571d352011-11-03 19:51:38 -07001409void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1410 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001411 uint32_t field_idx = it.GetMemberIndex();
1412 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001413 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001414 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001415}
1416
Ian Rogers0571d352011-11-03 19:51:38 -07001417void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1418 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001419 uint32_t method_idx = it.GetMemberIndex();
1420 dst->SetDexMethodIndex(method_idx);
1421 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001422 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001423
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001424
1425 StringPiece method_name(dex_file.GetMethodName(method_id));
1426 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001427 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1428 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001429
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001430 if (method_name == "finalize") {
1431 // Create the prototype for a signature of "()V"
1432 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1433 if (void_string_id != NULL) {
1434 const DexFile::TypeId* void_type_id =
1435 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1436 if (void_type_id != NULL) {
1437 std::vector<uint16_t> no_args;
1438 const DexFile::ProtoId* finalizer_proto =
1439 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1440 if (finalizer_proto != NULL) {
1441 // We have the prototype in the dex file
1442 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1443 klass->SetFinalizable();
1444 } else {
1445 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1446 // The Enum class declares a "final" finalize() method to prevent subclasses from
1447 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1448 // subclasses, so we exclude it here.
1449 // We also want to avoid setting the flag on Object, where we know that finalize() is
1450 // empty.
1451 if (klass_descriptor != "Ljava/lang/Object;" &&
1452 klass_descriptor != "Ljava/lang/Enum;") {
1453 klass->SetFinalizable();
1454 }
1455 }
1456 }
1457 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001458 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001459 }
Ian Rogers0571d352011-11-03 19:51:38 -07001460 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001461 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001462
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001463 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1464 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1465 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1466 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1467 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1468 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001469
Brian Carlstrom934486c2011-07-12 23:42:50 -07001470 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001471}
1472
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001473void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001474 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1475 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001476}
1477
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001478void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1479 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001480 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001481 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001482}
1483
Brian Carlstromaded5f72011-10-07 17:15:04 -07001484bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001485 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001486 for (size_t i = 0; i != dex_files_.size(); ++i) {
1487 if (dex_files_[i] == &dex_file) {
1488 return true;
1489 }
1490 }
1491 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001492}
1493
Brian Carlstromaded5f72011-10-07 17:15:04 -07001494bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001495 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001496 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001497}
1498
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001499void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001500 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001501 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001502 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001503 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001504 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001505}
1506
Brian Carlstromaded5f72011-10-07 17:15:04 -07001507void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001508 {
1509 MutexLock mu(dex_lock_);
1510 if (IsDexFileRegisteredLocked(dex_file)) {
1511 return;
1512 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001513 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001514 // Don't alloc while holding the lock, since allocation may need to
1515 // suspend all threads and another thread may need the dex_lock_ to
1516 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001517 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001518 {
1519 MutexLock mu(dex_lock_);
1520 if (IsDexFileRegisteredLocked(dex_file)) {
1521 return;
1522 }
1523 RegisterDexFileLocked(dex_file, dex_cache);
1524 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001525}
1526
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001527void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001528 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001529 RegisterDexFileLocked(dex_file, dex_cache);
1530}
1531
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001532const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001533 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001534 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001535 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1536 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001537 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001538 }
1539 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001540 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001541 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001542}
1543
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001544DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001545 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001546 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001547 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001548 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001549 }
1550 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001551 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001552 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001553}
1554
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001555Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1556 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001557 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001558 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001559 CHECK(primitive_class != NULL);
1560 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001561 primitive_class->SetPrimitiveType(type);
1562 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001563 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001564 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1565 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001566}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001567
Brian Carlstrombe977852011-07-19 14:54:54 -07001568// Create an array class (i.e. the class object for the array, not the
1569// array itself). "descriptor" looks like "[C" or "[[[[B" or
1570// "[Ljava/lang/String;".
1571//
1572// If "descriptor" refers to an array of primitives, look up the
1573// primitive type's internally-generated class object.
1574//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001575// "class_loader" is the class loader of the class that's referring to
1576// us. It's used to ensure that we're looking for the element type in
1577// the right context. It does NOT become the class loader for the
1578// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001579//
1580// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001581Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001582 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001583
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001584 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001585 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001586 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001587 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001588 return NULL;
1589 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001590
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001591 // See if the component type is already loaded. Array classes are
1592 // always associated with the class loader of their underlying
1593 // element type -- an array of Strings goes with the loader for
1594 // java/lang/String -- so we need to look for it there. (The
1595 // caller should have checked for the existence of the class
1596 // before calling here, but they did so with *their* class loader,
1597 // not the component type's loader.)
1598 //
1599 // If we find it, the caller adds "loader" to the class' initiating
1600 // loader list, which should prevent us from going through this again.
1601 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001602 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001603 // are the same, because our caller (FindClass) just did the
1604 // lookup. (Even if we get this wrong we still have correct behavior,
1605 // because we effectively do this lookup again when we add the new
1606 // class to the hash table --- necessary because of possible races with
1607 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001608 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001609 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001610 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001611 return new_class;
1612 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001613 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001614
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001615 // Fill out the fields in the Class.
1616 //
1617 // It is possible to execute some methods against arrays, because
1618 // all arrays are subclasses of java_lang_Object_, so we need to set
1619 // up a vtable. We can just point at the one in java_lang_Object_.
1620 //
1621 // Array classes are simple enough that we don't need to do a full
1622 // link step.
1623
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001624 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001625 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001626 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001627 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001628 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001629 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001630 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001631 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001632 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001633 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001634 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001635 }
1636 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001637 if (new_class.get() == NULL) {
1638 new_class.reset(AllocClass(sizeof(Class)));
1639 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001640 return NULL;
1641 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001642 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001643 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001644 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001645 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001646 new_class->SetSuperClass(java_lang_Object);
1647 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001648 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001649 new_class->SetClassLoader(component_type->GetClassLoader());
1650 new_class->SetStatus(Class::kStatusInitialized);
1651 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001652 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001653
1654
1655 // All arrays have java/lang/Cloneable and java/io/Serializable as
1656 // interfaces. We need to set that up here, so that stuff like
1657 // "instanceof" works right.
1658 //
1659 // Note: The GC could run during the call to FindSystemClass,
1660 // so we need to make sure the class object is GC-valid while we're in
1661 // there. Do this by clearing the interface list so the GC will just
1662 // think that the entries are null.
1663
1664
1665 // Use the single, global copies of "interfaces" and "iftable"
1666 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001667 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001668 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001669
1670 // Inherit access flags from the component type. Arrays can't be
1671 // used as a superclass or interface, so we want to add "final"
1672 // and remove "interface".
1673 //
1674 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001675 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001676 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001677 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1678 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001679
Ian Rogers5d76c432011-10-31 21:42:49 -07001680 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001681 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001682 }
1683 // Another thread must have loaded the class after we
1684 // started but before we finished. Abandon what we've
1685 // done.
1686 //
1687 // (Yes, this happens.)
1688
1689 // Grab the winning class.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001690 Class* other_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001691 DCHECK(other_class != NULL);
1692 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001693}
1694
1695Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001696 switch (Primitive::GetType(type)) {
1697 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001698 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001699 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001700 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001701 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001702 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001703 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001704 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001705 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001706 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001707 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001708 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001709 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001710 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001711 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001712 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001713 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001714 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001715 case Primitive::kPrimNot:
1716 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001717 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001718 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001719 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001720 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001721}
1722
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001723bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001724 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001725 DexCache* dex_cache = klass->GetDexCache();
1726 std::string source;
1727 if (dex_cache != NULL) {
1728 source += " from ";
1729 source += dex_cache->GetLocation()->ToModifiedUtf8();
1730 }
1731 LOG(INFO) << "Loaded class " << descriptor << source;
1732 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001733 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001734 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001735 Table::iterator it;
1736 if (image_class) {
1737 // TODO: sanity check there's no match in classes_
1738 it = image_classes_.insert(std::make_pair(hash, klass));
1739 } else {
1740 // TODO: sanity check there's no match in image_classes_
1741 it = classes_.insert(std::make_pair(hash, klass));
1742 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001743 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001744}
1745
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001746bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1747 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001748 MutexLock mu(classes_lock_);
1749 typedef Table::const_iterator It; // TODO: C++0x auto
1750 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001751 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001752 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1753 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001754 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001755 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001756 classes_.erase(it);
1757 return true;
1758 }
1759 }
1760 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1761 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001762 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001763 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001764 image_classes_.erase(it);
1765 return true;
1766 }
1767 }
1768 return false;
1769}
1770
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001771Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1772 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001773 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001774 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001775 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001776 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001777 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001778 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001779 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001780 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001781 return klass;
1782 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001783 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001784 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1785 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001786 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001787 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001788 return klass;
1789 }
1790 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001791 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001792}
1793
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001794void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001795 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001796 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001797 MutexLock mu(classes_lock_);
1798 typedef Table::const_iterator It; // TODO: C++0x auto
1799 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001800 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001801 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001802 Class* klass = it->second;
1803 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001804 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001805 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001806 }
1807 }
1808 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001809 Class* klass = it->second;
1810 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001811 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001812 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001813 }
1814 }
1815}
1816
jeffhao98eacac2011-09-14 16:11:53 -07001817void ClassLinker::VerifyClass(Class* klass) {
1818 if (klass->IsVerified()) {
1819 return;
1820 }
1821
1822 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001823 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001824
Ian Rogersd81871c2011-10-03 13:57:23 -07001825 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001826 klass->SetStatus(Class::kStatusVerified);
1827 } else {
1828 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001829 Thread* self = Thread::Current();
1830 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1831 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001832 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001833 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001834 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001835 }
jeffhao98eacac2011-09-14 16:11:53 -07001836}
1837
Ian Rogersc2b44472011-12-14 21:17:17 -08001838static void CheckProxyConstructor(Method* constructor);
1839static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1840
Jesse Wilson95caa792011-10-12 18:14:17 -04001841Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001842 ClassLoader* loader, ObjectArray<Method>* methods,
1843 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001844 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001845 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001846 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001847 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001848 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001849 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001850 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001851 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001852 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001853 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001854
1855 klass->SetStatus(Class::kStatusIdx);
1856
1857 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1858
1859 // Create static field that holds throws, instance fields are inherited
1860 klass->SetSFields(AllocObjectArray<Field>(1));
1861 SirtRef<Field> sfield(AllocField());
1862 klass->SetStaticField(0, sfield.get());
1863 sfield->SetDexFieldIndex(-1);
1864 sfield->SetDeclaringClass(klass.get());
1865 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001866
Ian Rogers466bb252011-10-14 03:29:56 -07001867 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001868 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001869 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001870
Ian Rogers466bb252011-10-14 03:29:56 -07001871 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001872 size_t num_virtual_methods = methods->GetLength();
1873 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1874 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001875 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001876 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001877 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001878
1879 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1880 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1881 DCHECK(!Thread::Current()->IsExceptionPending());
1882
1883 // Link the fields and virtual methods, creating vtable and iftables
1884 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001885 DCHECK(Thread::Current()->IsExceptionPending());
1886 return NULL;
1887 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001888 sfield->SetObject(NULL, throws); // initialize throws field
1889 klass->SetStatus(Class::kStatusInitialized);
1890
1891 // sanity checks
1892#ifndef NDEBUG
1893 bool debug = true;
1894#else
1895 bool debug = false;
1896#endif
1897 if (debug) {
1898 CHECK(klass->GetIFields() == NULL);
1899 CheckProxyConstructor(klass->GetDirectMethod(0));
1900 for (size_t i = 0; i < num_virtual_methods; ++i) {
1901 SirtRef<Method> prototype(methods->Get(i));
1902 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1903 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001904 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08001905 throws_field_name += name->ToModifiedUtf8();
1906 throws_field_name += ".throws";
1907 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1908
1909 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1910 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1911 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001912 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001913}
1914
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001915std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1916 DCHECK(proxy_class->IsProxyClass());
1917 String* name = proxy_class->GetName();
1918 DCHECK(name != NULL);
1919 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1920}
1921
1922
1923Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001924 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001925 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001926 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001927 Method* proxy_constructor = proxy_direct_methods->Get(2);
1928 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1929 // code_ too)
1930 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1931 // Make this constructor public and fix the class to be our Proxy version
1932 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001933 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001934 return constructor;
1935}
1936
1937static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001938 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001939 MethodHelper mh(constructor);
1940 CHECK_STREQ(mh.GetName(), "<init>");
1941 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001942 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001943}
1944
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001945Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1946 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1947 // prototype method
1948 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1949 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001950 // as necessary
1951 Method* method = down_cast<Method*>(prototype->Clone());
1952
1953 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1954 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001955 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001956 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001957
Ian Rogers466bb252011-10-14 03:29:56 -07001958 // At runtime the method looks like a reference and argument saving method, clone the code
1959 // related parameters from this method.
1960 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1961 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1962 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1963 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1964 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001965 return method;
1966}
Jesse Wilson95caa792011-10-12 18:14:17 -04001967
Ian Rogersc2b44472011-12-14 21:17:17 -08001968static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001969 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001970 CHECK(!prototype->IsFinal());
1971 CHECK(method->IsFinal());
1972 CHECK(!method->IsAbstract());
1973 MethodHelper mh(method);
1974 const char* method_name = mh.GetName();
1975 const char* method_shorty = mh.GetShorty();
1976 Class* method_return = mh.GetReturnType();
1977
1978 mh.ChangeMethod(prototype.get());
1979
1980 CHECK_STREQ(mh.GetName(), method_name);
1981 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001982
1983 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001984 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001985}
1986
Brian Carlstrom25c33252011-09-18 15:58:35 -07001987bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001988 CHECK(klass->IsResolved() || klass->IsErroneous())
1989 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001990
Carl Shapirob5573532011-07-12 18:22:59 -07001991 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001992
Brian Carlstrom25c33252011-09-18 15:58:35 -07001993 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001994 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001995 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001996 ObjectLock lock(klass);
1997
Brian Carlstromd1422f82011-09-28 11:37:09 -07001998 if (klass->GetStatus() == Class::kStatusInitialized) {
1999 return true;
2000 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002001
Brian Carlstromd1422f82011-09-28 11:37:09 -07002002 if (klass->IsErroneous()) {
2003 ThrowEarlierClassFailure(klass);
2004 return false;
2005 }
2006
2007 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002008 VerifyClass(klass);
2009 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002010 return false;
2011 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002012 }
2013
Brian Carlstrom25c33252011-09-18 15:58:35 -07002014 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2015 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002016 // if the class has a <clinit> but we can't run it during compilation,
2017 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07002018 return false;
2019 }
2020
Brian Carlstromd1422f82011-09-28 11:37:09 -07002021 // If the class is kStatusInitializing, either this thread is
2022 // initializing higher up the stack or another thread has beat us
2023 // to initializing and we need to wait. Either way, this
2024 // invocation of InitializeClass will not be responsible for
2025 // running <clinit> and will return.
2026 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002027 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002028 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002029 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002030 return true;
2031 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002032 // No. That's fine. Wait for another thread to finish initializing.
2033 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002034 }
2035
2036 if (!ValidateSuperClassDescriptors(klass)) {
2037 klass->SetStatus(Class::kStatusError);
2038 return false;
2039 }
2040
Brian Carlstromd1422f82011-09-28 11:37:09 -07002041 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002042
Elliott Hughesdcc24742011-09-07 14:02:44 -07002043 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002044 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002045 }
2046
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002047 uint64_t t0 = NanoTime();
2048
Brian Carlstrom25c33252011-09-18 15:58:35 -07002049 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002050 return false;
2051 }
2052
2053 InitializeStaticFields(klass);
2054
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002055 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002056 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002057 }
2058
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002059 uint64_t t1 = NanoTime();
2060
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002061 {
2062 ObjectLock lock(klass);
2063
2064 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002065 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002066 klass->SetStatus(Class::kStatusError);
2067 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002068 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2069 RuntimeStats* thread_stats = self->GetStats();
2070 ++global_stats->class_init_count;
2071 ++thread_stats->class_init_count;
2072 global_stats->class_init_time_ns += (t1 - t0);
2073 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002074 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002075 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002076 ClassHelper kh(klass);
2077 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002078 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002079 }
2080 lock.NotifyAll();
2081 }
2082
2083 return true;
2084}
2085
Brian Carlstromd1422f82011-09-28 11:37:09 -07002086bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2087 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002088 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002089 lock.Wait();
2090
2091 // When we wake up, repeat the test for init-in-progress. If
2092 // there's an exception pending (only possible if
2093 // "interruptShouldThrow" was set), bail out.
2094 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002095 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002096 klass->SetStatus(Class::kStatusError);
2097 return false;
2098 }
2099 // Spurious wakeup? Go back to waiting.
2100 if (klass->GetStatus() == Class::kStatusInitializing) {
2101 continue;
2102 }
2103 if (klass->IsErroneous()) {
2104 // The caller wants an exception, but it was thrown in a
2105 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002106 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002107 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002108 return false;
2109 }
2110 if (klass->IsInitialized()) {
2111 return true;
2112 }
2113 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2114 }
2115 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2116}
2117
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2119 if (klass->IsInterface()) {
2120 return true;
2121 }
2122 // begin with the methods local to the superclass
2123 if (klass->HasSuperClass() &&
2124 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2125 const Class* super = klass->GetSuperClass();
2126 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002127 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002128 if (method != super->GetVirtualMethod(i) &&
2129 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002130 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2131
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002132 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2133 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2134 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002135 return false;
2136 }
2137 }
2138 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002139 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2140 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2141 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002142 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2143 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002144 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002145 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002146 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002147 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2148
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002149 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2150 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2151 PrettyMethod(method).c_str(),
2152 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002153 return false;
2154 }
2155 }
2156 }
2157 }
2158 return true;
2159}
2160
2161bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002162 const Class* klass1,
2163 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002164 if (klass1 == klass2) {
2165 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002166 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002167 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002168 const DexFile::ProtoId& proto_id =
2169 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002170 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2171 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002172 if (descriptor == NULL) {
2173 break;
2174 }
2175 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2176 // Found a non-primitive type.
2177 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2178 return false;
2179 }
2180 }
2181 }
2182 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002183 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002184 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002185 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002186 return false;
2187 }
2188 }
2189 return true;
2190}
2191
2192// Returns true if classes referenced by the descriptor are the
2193// same classes in klass1 as they are in klass2.
2194bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002195 const Class* klass1,
2196 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002197 CHECK(descriptor != NULL);
2198 CHECK(klass1 != NULL);
2199 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002200 if (klass1 == klass2) {
2201 return true;
2202 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002203 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002204 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002205 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002206 // TODO: found2 == NULL
2207 // TODO: lookup found1 in initiating loader list
2208 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002209 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002210 return found1 == found2;
2211 } else {
2212 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002213 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002214}
2215
Brian Carlstrom25c33252011-09-18 15:58:35 -07002216bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002217 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002218 if (!klass->IsInterface() && klass->HasSuperClass()) {
2219 Class* super_class = klass->GetSuperClass();
2220 if (super_class->GetStatus() != Class::kStatusInitialized) {
2221 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002222 Thread* self = Thread::Current();
2223 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002224 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002225 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002226 // TODO: check for a pending exception
2227 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002228 if (!can_run_clinit) {
2229 // Don't set status to error when we can't run <clinit>.
2230 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2231 klass->SetStatus(Class::kStatusVerified);
2232 return false;
2233 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002234 klass->SetStatus(Class::kStatusError);
2235 klass->NotifyAll();
2236 return false;
2237 }
2238 }
2239 }
2240 return true;
2241}
2242
Brian Carlstrom25c33252011-09-18 15:58:35 -07002243bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002244 CHECK(c != NULL);
2245 if (c->IsInitialized()) {
2246 return true;
2247 }
2248
Elliott Hughes5f791332011-09-15 17:45:30 -07002249 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002250 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002251 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002252 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002253}
2254
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002255void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002256 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002257 const ClassLoader* cl = c->GetClassLoader();
2258 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002259 ClassDataItemIterator it(dex_file, class_data);
2260 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2261 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002262 }
2263}
2264
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002266 size_t num_static_fields = klass->NumStaticFields();
2267 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002268 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002269 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002270 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002271 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002272 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002273 return;
2274 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002275 ClassHelper kh(klass);
2276 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002277 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002278 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002279 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002280
Ian Rogers0571d352011-11-03 19:51:38 -07002281 if (it.HasNext()) {
2282 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2283 std::map<uint32_t, Field*> field_map;
2284 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2285 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2286 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002287 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288 }
2289}
2290
Ian Rogersc2b44472011-12-14 21:17:17 -08002291bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002292 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002293 if (!LinkSuperClass(klass)) {
2294 return false;
2295 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002296 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002297 return false;
2298 }
2299 if (!LinkInstanceFields(klass)) {
2300 return false;
2301 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002302 if (!LinkStaticFields(klass)) {
2303 return false;
2304 }
2305 CreateReferenceInstanceOffsets(klass);
2306 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002307 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2308 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309 return true;
2310}
2311
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002312bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002313 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002314 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2315 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002316 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002317 uint16_t super_class_idx = class_def->superclass_idx_;
2318 if (super_class_idx != DexFile::kDexNoIndex16) {
2319 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002320 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002321 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002322 return false;
2323 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002324 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002325 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002326 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2327 if (interfaces != NULL) {
2328 for (size_t i = 0; i < interfaces->Size(); i++) {
2329 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2330 Class* interface = ResolveType(dex_file, idx, klass.get());
2331 if (interface == NULL) {
2332 DCHECK(Thread::Current()->IsExceptionPending());
2333 return false;
2334 }
2335 // Verify
2336 if (!klass->CanAccess(interface)) {
2337 // TODO: the RI seemed to ignore this in my testing.
2338 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2339 "Interface %s implemented by class %s is inaccessible",
2340 PrettyDescriptor(interface).c_str(),
2341 PrettyDescriptor(klass.get()).c_str());
2342 return false;
2343 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002344 }
2345 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002346 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002347 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002348 return true;
2349}
2350
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002351bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002352 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002353 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002354 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002355 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002356 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002357 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358 return false;
2359 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002360 return true;
2361 }
2362 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002363 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002364 return false;
2365 }
2366 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002367 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002368 Thread* thread = Thread::Current();
2369 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002370 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002371 PrettyDescriptor(super).c_str(),
2372 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002373 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002374 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002375 return false;
2376 }
2377 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002378 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002379 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002380 PrettyDescriptor(super).c_str(),
2381 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002382 return false;
2383 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002384
2385 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2386 if (super->IsFinalizable()) {
2387 klass->SetFinalizable();
2388 }
2389
Elliott Hughes2da50362011-10-10 16:57:08 -07002390 // Inherit reference flags (if any) from the superclass.
2391 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2392 if (reference_flags != 0) {
2393 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2394 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002395 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002396 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002397 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002398 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002399 return false;
2400 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002401
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002402#ifndef NDEBUG
2403 // Ensure super classes are fully resolved prior to resolving fields..
2404 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002405 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002406 super = super->GetSuperClass();
2407 }
2408#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002409 return true;
2410}
2411
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002412// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002413bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002414 if (klass->IsInterface()) {
2415 // No vtable.
2416 size_t count = klass->NumVirtualMethods();
2417 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002418 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002419 return false;
2420 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002421 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002422 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002423 }
jeffhaobdb76512011-09-07 11:43:16 -07002424 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002425 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002426 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002427 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002428 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002429 }
2430 return true;
2431}
2432
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002433bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002434 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002435 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2436 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002437 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002438 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002439 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002440 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002441 MethodHelper local_mh(NULL, this);
2442 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002443 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002444 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002445 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002446 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002447 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002448 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002449 super_mh.ChangeMethod(super_method);
2450 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002451 // Verify
2452 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002453 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002454 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002455 PrettyDescriptor(klass.get()).c_str(),
2456 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002457 return false;
2458 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002459 vtable->Set(j, local_method);
2460 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002461 break;
2462 }
2463 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002464 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002465 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002466 vtable->Set(actual_count, local_method);
2467 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002468 actual_count += 1;
2469 }
2470 }
2471 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002472 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002473 return false;
2474 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002475 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002476 CHECK_LE(actual_count, max_count);
2477 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002478 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002479 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002480 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002481 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002482 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002483 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002484 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002485 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002486 return false;
2487 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002488 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002489 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002490 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2491 vtable->Set(i, virtual_method);
2492 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002493 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002494 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002495 }
2496 return true;
2497}
2498
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002499bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002500 size_t super_ifcount;
2501 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002502 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002503 } else {
2504 super_ifcount = 0;
2505 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002506 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002507 ClassHelper kh(klass.get(), this);
2508 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2509 ifcount += num_interfaces;
2510 for (size_t i = 0; i < num_interfaces; i++) {
2511 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2512 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002513 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002514 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002515 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002516 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002517 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002518 return true;
2519 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002520 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002521 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002522 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2523 for (size_t i = 0; i < super_ifcount; i++) {
2524 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2525 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002526 }
2527 // Flatten the interface inheritance hierarchy.
2528 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002529 for (size_t i = 0; i < num_interfaces; i++) {
2530 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002531 DCHECK(interface != NULL);
2532 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002533 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002534 Thread* thread = Thread::Current();
2535 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002536 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002537 PrettyDescriptor(klass.get()).c_str(),
2538 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002539 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002540 return false;
2541 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002542 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002543 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002544 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002545 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2546 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002547 }
2548 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002549 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002550 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002551
2552 // If we're an interface, we don't need the vtable pointers, so we're done.
2553 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002554 return true;
2555 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002556 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002557 MethodHelper vtable_mh(NULL, this);
2558 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002559 for (size_t i = 0; i < ifcount; ++i) {
2560 InterfaceEntry* interface_entry = iftable->Get(i);
2561 Class* interface = interface_entry->GetInterface();
2562 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2563 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002564 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002565 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2566 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002567 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002568 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002569 // For each method listed in the interface's method list, find the
2570 // matching method in our class's method list. We want to favor the
2571 // subclass over the superclass, which just requires walking
2572 // back from the end of the vtable. (This only matters if the
2573 // superclass defines a private method and this class redefines
2574 // it -- otherwise it would use the same vtable slot. In .dex files
2575 // those don't end up in the virtual method table, so it shouldn't
2576 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2578 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002579 vtable_mh.ChangeMethod(vtable_method);
2580 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002581 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002582 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002583 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 return false;
2585 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002586 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002587 break;
2588 }
2589 }
2590 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002591 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002592 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002593 Method* mir_method = miranda_list[mir];
2594 vtable_mh.ChangeMethod(mir_method);
2595 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002596 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 break;
2598 }
2599 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002600 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002601 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002602 miranda_method.reset(AllocMethod());
2603 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2604 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002605 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002606 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002607 }
2608 }
2609 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002610 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002611 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002612 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002613 klass->SetVirtualMethods((old_method_count == 0)
2614 ? AllocObjectArray<Method>(new_method_count)
2615 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002616
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002617 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2618 CHECK(vtable != NULL);
2619 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002620 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002621 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002622 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002623 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002624 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002625 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2626 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2627 klass->SetVirtualMethod(old_method_count + i, method);
2628 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002629 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002630 // TODO: do not assign to the vtable field until it is fully constructed.
2631 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002632 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002633
2634 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2635 for (int i = 0; i < vtable->GetLength(); ++i) {
2636 CHECK(vtable->Get(i) != NULL);
2637 }
2638
2639// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2640
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002641 return true;
2642}
2643
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002644bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2645 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002646 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002647}
2648
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002649bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2650 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002651 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002652 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002653 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002654 return success;
2655}
2656
Brian Carlstromdbc05252011-09-09 01:59:59 -07002657struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002658 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002659 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002660 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002661 fh_->ChangeField(field1);
2662 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2663 fh_->ChangeField(field2);
2664 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002665 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2666 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2667 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2668 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002669 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2670 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2671 if (order1 != order2) {
2672 return order1 < order2;
2673 }
2674
2675 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002676 fh_->ChangeField(field1);
2677 StringPiece name1(fh_->GetName());
2678 fh_->ChangeField(field2);
2679 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002680 return name1 < name2;
2681 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002682
2683 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002684};
2685
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002686bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002687 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002688 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002689
2690 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002691 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002692
2693 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002694 size_t size;
2695 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002696 if (is_static) {
2697 size = klass->GetClassSize();
2698 field_offset = Class::FieldsOffset();
2699 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002700 Class* super_class = klass->GetSuperClass();
2701 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002702 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002703 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002704 }
2705 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002706 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002707
Brian Carlstromdbc05252011-09-09 01:59:59 -07002708 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002709
Brian Carlstromdbc05252011-09-09 01:59:59 -07002710 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002711 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002712 std::deque<Field*> grouped_and_sorted_fields;
2713 for (size_t i = 0; i < num_fields; i++) {
2714 grouped_and_sorted_fields.push_back(fields->Get(i));
2715 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002716 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002717 std::sort(grouped_and_sorted_fields.begin(),
2718 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002719 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002720
2721 // References should be at the front.
2722 size_t current_field = 0;
2723 size_t num_reference_fields = 0;
2724 for (; current_field < num_fields; current_field++) {
2725 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002726 fh.ChangeField(field);
2727 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002728 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002729 if (isPrimitive) {
2730 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002731 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002732 grouped_and_sorted_fields.pop_front();
2733 num_reference_fields++;
2734 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002735 field->SetOffset(field_offset);
2736 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002737 }
2738
2739 // Now we want to pack all of the double-wide fields together. If
2740 // we're not aligned, though, we want to shuffle one 32-bit field
2741 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002742 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002743 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2744 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002745 fh.ChangeField(field);
2746 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002747 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2748 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002749 continue;
2750 }
2751 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002752 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002753 // drop the consumed field
2754 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2755 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002756 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002757 // whether we found a 32-bit field for padding or not, we advance
2758 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002759 }
2760
2761 // Alignment is good, shuffle any double-wide fields forward, and
2762 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002763 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002764 while (!grouped_and_sorted_fields.empty()) {
2765 Field* field = grouped_and_sorted_fields.front();
2766 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002767 fh.ChangeField(field);
2768 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002769 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002770 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002771 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002772 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002773 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002774 ? sizeof(uint64_t)
2775 : sizeof(uint32_t)));
2776 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002777 }
2778
Elliott Hughesadb460d2011-10-05 17:02:34 -07002779 // 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 -08002780 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2781 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002782 // We know there are no non-reference fields in the Reference classes, and we know
2783 // that 'referent' is alphabetically last, so this is easy...
2784 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002785 fh.ChangeField(fields->Get(num_fields - 1));
2786 StringPiece name(fh.GetName());
2787 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002788 --num_reference_fields;
2789 }
2790
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002791#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002792 // Make sure that all reference fields appear before
2793 // non-reference fields, and all double-wide fields are aligned.
2794 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002795 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002796 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002797 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002798 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002799 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002800 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002801 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2802 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002803 fh.ChangeField(field);
2804 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002805 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002806 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002807 is_primitive = true; // We lied above, so we have to expect a lie here.
2808 }
2809 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002810 if (!seen_non_ref) {
2811 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002812 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002813 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002814 } else {
2815 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002816 }
2817 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002818 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002819 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002820 }
2821#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002822 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002823 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002824 if (is_static) {
2825 klass->SetNumReferenceStaticFields(num_reference_fields);
2826 klass->SetClassSize(size);
2827 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002828 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002829 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002830 klass->SetObjectSize(size);
2831 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002832 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002833 return true;
2834}
2835
2836// Set the bitmap of reference offsets, refOffsets, from the ifields
2837// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002838void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002839 uint32_t reference_offsets = 0;
2840 Class* super_class = klass->GetSuperClass();
2841 if (super_class != NULL) {
2842 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002843 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002844 if (reference_offsets == CLASS_WALK_SUPER) {
2845 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002846 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002847 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002848 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002849 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002850}
2851
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002852void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002853 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002854}
2855
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002856void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002857 uint32_t reference_offsets) {
2858 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002859 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2860 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002861 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002862 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002863 // All of the fields that contain object references are guaranteed
2864 // to be at the beginning of the fields list.
2865 for (size_t i = 0; i < num_reference_fields; ++i) {
2866 // Note that byte_offset is the offset from the beginning of
2867 // object, not the offset into instance data
2868 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002869 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002870 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2871 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2872 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002873 CHECK_NE(new_bit, 0U);
2874 reference_offsets |= new_bit;
2875 } else {
2876 reference_offsets = CLASS_WALK_SUPER;
2877 break;
2878 }
2879 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002880 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002881 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002882 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002883 } else {
2884 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002885 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002886}
2887
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002888String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002889 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002890 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002891 if (resolved != NULL) {
2892 return resolved;
2893 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002894 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2895 int32_t utf16_length = dex_file.GetStringLength(string_id);
2896 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002897 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002898 dex_cache->SetResolvedString(string_idx, string);
2899 return string;
2900}
2901
2902Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002903 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002904 DexCache* dex_cache,
2905 const ClassLoader* class_loader) {
2906 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002907 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002908 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002909 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002910 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002911 // TODO: we used to throw here if resolved's class loader was not the
2912 // boot class loader. This was to permit different classes with the
2913 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002914 dex_cache->SetResolvedType(type_idx, resolved);
2915 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08002916 CHECK(Thread::Current()->IsExceptionPending())
2917 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002918 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002919 }
2920 return resolved;
2921}
2922
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002923Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2924 uint32_t method_idx,
2925 DexCache* dex_cache,
2926 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002927 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002928 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2929 if (resolved != NULL) {
2930 return resolved;
2931 }
2932 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2933 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2934 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002935 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002936 return NULL;
2937 }
2938
Ian Rogers0571d352011-11-03 19:51:38 -07002939 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2940 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002941 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002942 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002943 } else if (klass->IsInterface()) {
2944 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002945 } else {
2946 resolved = klass->FindVirtualMethod(name, signature);
2947 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002948 if (resolved != NULL) {
2949 dex_cache->SetResolvedMethod(method_idx, resolved);
2950 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002951 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002952 }
2953 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002954}
2955
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002956Field* ClassLinker::ResolveField(const DexFile& dex_file,
2957 uint32_t field_idx,
2958 DexCache* dex_cache,
2959 const ClassLoader* class_loader,
2960 bool is_static) {
2961 Field* resolved = dex_cache->GetResolvedField(field_idx);
2962 if (resolved != NULL) {
2963 return resolved;
2964 }
2965 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2966 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2967 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002968 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002969 return NULL;
2970 }
2971
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002972 const char* name = dex_file.GetFieldName(field_id);
2973 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002974 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002975 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002976 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002977 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002978 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002979 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002980 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002981 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002982 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2983 }
2984 return resolved;
2985}
2986
2987Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2988 uint32_t field_idx,
2989 DexCache* dex_cache,
2990 const ClassLoader* class_loader) {
2991 Field* resolved = dex_cache->GetResolvedField(field_idx);
2992 if (resolved != NULL) {
2993 return resolved;
2994 }
2995 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2996 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2997 if (klass == NULL) {
2998 DCHECK(Thread::Current()->IsExceptionPending());
2999 return NULL;
3000 }
3001
3002 const char* name = dex_file.GetFieldName(field_id);
3003 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3004 resolved = klass->FindField(name, type);
3005 if (resolved != NULL) {
3006 dex_cache->SetResolvedField(field_idx, resolved);
3007 } else {
3008 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003009 }
3010 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003011}
3012
Ian Rogersad25ac52011-10-04 19:13:33 -07003013const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3014 Class* declaring_class = referrer->GetDeclaringClass();
3015 DexCache* dex_cache = declaring_class->GetDexCache();
3016 const DexFile& dex_file = FindDexFile(dex_cache);
3017 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3018 return dex_file.GetShorty(method_id.proto_idx_);
3019}
3020
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003021void ClassLinker::DumpAllClasses(int flags) const {
3022 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3023 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3024 std::vector<Class*> all_classes;
3025 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003026 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003027 typedef Table::const_iterator It; // TODO: C++0x auto
3028 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3029 all_classes.push_back(it->second);
3030 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003031 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3032 all_classes.push_back(it->second);
3033 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003034 }
3035
3036 for (size_t i = 0; i < all_classes.size(); ++i) {
3037 all_classes[i]->DumpClass(std::cerr, flags);
3038 }
3039}
3040
Elliott Hughescac6cc72011-11-03 20:31:21 -07003041void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3042 MutexLock mu(classes_lock_);
3043 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3044 << classes_.size() << " allocated classes\n";
3045}
3046
Elliott Hughese27955c2011-08-26 15:21:24 -07003047size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003048 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003049 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003050}
3051
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003052pid_t ClassLinker::GetClassesLockOwner() {
3053 return classes_lock_.GetOwner();
3054}
3055
3056pid_t ClassLinker::GetDexLockOwner() {
3057 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003058}
3059
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003060void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3061 DCHECK(!init_done_);
3062
3063 DCHECK(klass != NULL);
3064 DCHECK(klass->GetClassLoader() == NULL);
3065
3066 DCHECK(class_roots_ != NULL);
3067 DCHECK(class_roots_->Get(class_root) == NULL);
3068 class_roots_->Set(class_root, klass);
3069}
3070
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003071} // namespace art