blob: b3858953d61c2642531f669c5a2d445c725cf14a [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
Elliott Hughes4a2b4172011-09-20 17:08:25 -070094void ThrowEarlierClassFailure(Class* c) {
95 /*
96 * The class failed to initialize on a previous attempt, so we want to throw
97 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
98 * failed in verification, in which case v2 5.4.1 says we need to re-throw
99 * the previous error.
100 */
101 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
102
103 if (c->GetVerifyErrorClass() != NULL) {
104 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800105 ClassHelper ve_ch(c->GetVerifyErrorClass());
106 std::string error_descriptor(ve_ch.GetDescriptor());
107 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700108 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800109 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700110 }
111}
112
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700113void WrapExceptionInInitializer() {
114 JNIEnv* env = Thread::Current()->GetJniEnv();
115
116 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
117 CHECK(cause.get() != NULL);
118
119 env->ExceptionClear();
120
121 // TODO: add java.lang.Error to JniConstants?
122 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
123 CHECK(error_class.get() != NULL);
124 if (env->IsInstanceOf(cause.get(), error_class.get())) {
125 // We only wrap non-Error exceptions; an Error can just be used as-is.
126 env->Throw(cause.get());
127 return;
128 }
129
130 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
131 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
132 CHECK(eiie_class.get() != NULL);
133
134 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
135 CHECK(mid != NULL);
136
137 ScopedLocalRef<jthrowable> eiie(env,
138 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
139 env->Throw(eiie.get());
140}
141
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800142static size_t Hash(const char* s) {
143 // This is the java.lang.String hashcode for convenience, not interoperability.
144 size_t hash = 0;
145 for (; *s != '\0'; ++s) {
146 hash = hash * 31 + *s;
147 }
148 return hash;
149}
150
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700151} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700152
Elliott Hughes418d20f2011-09-22 14:00:39 -0700153const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700154 "Ljava/lang/Class;",
155 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700156 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700157 "[Ljava/lang/Object;",
158 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700159 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700160 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700161 "Ljava/lang/reflect/Field;",
162 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700163 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700164 "Ljava/lang/ClassLoader;",
165 "Ldalvik/system/BaseDexClassLoader;",
166 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700167 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700168 "Z",
169 "B",
170 "C",
171 "D",
172 "F",
173 "I",
174 "J",
175 "S",
176 "V",
177 "[Z",
178 "[B",
179 "[C",
180 "[D",
181 "[F",
182 "[I",
183 "[J",
184 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700185 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700186};
187
Elliott Hughes5f791332011-09-15 17:45:30 -0700188class ObjectLock {
189 public:
190 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
191 CHECK(object != NULL);
192 obj_->MonitorEnter(self_);
193 }
194
195 ~ObjectLock() {
196 obj_->MonitorExit(self_);
197 }
198
199 void Wait() {
200 return Monitor::Wait(self_, obj_, 0, 0, false);
201 }
202
203 void Notify() {
204 obj_->Notify();
205 }
206
207 void NotifyAll() {
208 obj_->NotifyAll();
209 }
210
211 private:
212 Thread* self_;
213 Object* obj_;
214 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
215};
216
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800217ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700218 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800219 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700220 class_linker->Init(boot_class_path);
221 return class_linker.release();
222}
223
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800224ClassLinker* ClassLinker::Create(InternTable* intern_table) {
225 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700226 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700227 return class_linker.release();
228}
229
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800230ClassLinker::ClassLinker(InternTable* intern_table)
231 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700232 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700233 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700234 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700235 init_done_(false),
236 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700237 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700238}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700239
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700240void CreateClassPath(const std::string& class_path,
241 std::vector<const DexFile*>& class_path_vector) {
242 std::vector<std::string> parsed;
243 Split(class_path, ':', parsed);
244 for (size_t i = 0; i < parsed.size(); ++i) {
245 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700246 if (dex_file == NULL) {
247 LOG(WARNING) << "Failed to open dex file " << parsed[i];
248 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700249 class_path_vector.push_back(dex_file);
250 }
251 }
252}
253
254void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800255 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700256
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700257 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700258
Elliott Hughes30646832011-10-13 16:59:46 -0700259 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700260 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
261 CHECK(java_lang_Class.get() != NULL);
262 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700264 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700265
Elliott Hughes418d20f2011-09-22 14:00:39 -0700266 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700267 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
268 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700269
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700270 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700271 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
272 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700273 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700274 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700276
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700277 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700278 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
279 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700280
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700281 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700283
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700284 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700285 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
286 char_array_class->SetComponentType(char_class.get());
287 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700288
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700290 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
291 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 java_lang_String->SetObjectSize(sizeof(String));
293 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400294
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295 // Create storage for root classes, save away our work so far (requires
296 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700297 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700298 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700299 SetClassRoot(kJavaLangClass, java_lang_Class.get());
300 SetClassRoot(kJavaLangObject, java_lang_Object.get());
301 SetClassRoot(kClassArrayClass, class_array_class.get());
302 SetClassRoot(kObjectArrayClass, object_array_class.get());
303 SetClassRoot(kCharArrayClass, char_array_class.get());
304 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305
306 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700307 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
308 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
309 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
310 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
311 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
312 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
313 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
314 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700316 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700317 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700318
319 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700320 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700321 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700322 IntArray::SetArrayClass(int_array_class.get());
323 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700324
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700325 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700326
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700327 // setup boot_class_path_ and register class_path now that we can
328 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700329 std::vector<const DexFile*> boot_class_path_vector;
330 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700331 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700332 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
333 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700334 CHECK(dex_file != NULL);
335 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700336 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337
Elliott Hughes80609252011-09-23 17:24:51 -0700338 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700339 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700340 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700341 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700342 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700343 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
344
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700345 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
346 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700347 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700349 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700352 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700353 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700355 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700357 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700358
359 // now we can use FindSystemClass
360
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700361 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700362 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700363 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700364
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700365 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366 java_lang_Object->SetStatus(Class::kStatusNotReady);
367 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700368 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700369 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
370 java_lang_String->SetStatus(Class::kStatusNotReady);
371 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700372 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700373 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
374
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700375 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700376 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
377 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
378
379 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
380 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
381
382 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700383 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384
385 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
386 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
387
388 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700389 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700390
391 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
392 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
393
394 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
395 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
396
397 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
398 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
399
Elliott Hughes418d20f2011-09-22 14:00:39 -0700400 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700401 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700402
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700404 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700405
406 // Setup the single, global copies of "interfaces" and "iftable"
407 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
408 CHECK(java_lang_Cloneable != NULL);
409 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
410 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411 // We assume that Cloneable/Serializable don't have superinterfaces --
412 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700413 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800414 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
415 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416
Elliott Hughes418d20f2011-09-22 14:00:39 -0700417 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800418 ClassHelper kh(class_array_class.get(), this);
419 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
420 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
421 kh.ChangeClass(object_array_class.get());
422 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
423 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700424 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700425 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700426 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700427 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700428
Elliott Hughes80609252011-09-23 17:24:51 -0700429 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
430 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700431 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700432
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700433 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700434 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700435 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436
437 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700438 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700439 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700440
Ian Rogers466bb252011-10-14 03:29:56 -0700441 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
442
443 // Create java.lang.reflect.Proxy root
444 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
445 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
446
Brian Carlstrom1f870082011-08-23 16:02:11 -0700447 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700448 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
449 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700450 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700451 java_lang_ref_FinalizerReference->SetAccessFlags(
452 java_lang_ref_FinalizerReference->GetAccessFlags() |
453 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700454 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455 java_lang_ref_PhantomReference->SetAccessFlags(
456 java_lang_ref_PhantomReference->GetAccessFlags() |
457 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700458 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459 java_lang_ref_SoftReference->SetAccessFlags(
460 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700461 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700462 java_lang_ref_WeakReference->SetAccessFlags(
463 java_lang_ref_WeakReference->GetAccessFlags() |
464 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700465
Brian Carlstromaded5f72011-10-07 17:15:04 -0700466 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700468 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700469 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
470
471 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
472 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
473 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
474
475 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
476 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
477 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
478 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
479
480 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700481 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
482 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700483 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700484
Brian Carlstroma663ea52011-08-19 23:33:41 -0700485 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700486
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800487 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700488}
489
490void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800491 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700492
493 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700494 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700495 // as the types of the field can't be resolved prior to the runtime being
496 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700497 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700498 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700499 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
500
Elliott Hughesadb460d2011-10-05 17:02:34 -0700501 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
502
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800503 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
504
Brian Carlstrom16192862011-09-12 17:50:06 -0700505 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800506 FieldHelper fh(pendingNext, this);
507 CHECK_STREQ(fh.GetName(), "pendingNext");
508 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
509 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700510
511 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800512 fh.ChangeField(queue);
513 CHECK_STREQ(fh.GetName(), "queue");
514 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
515 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700516
517 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800518 fh.ChangeField(queueNext);
519 CHECK_STREQ(fh.GetName(), "queueNext");
520 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
521 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700522
523 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800524 fh.ChangeField(referent);
525 CHECK_STREQ(fh.GetName(), "referent");
526 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
527 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700528
529 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800530 fh.ChangeField(zombie);
531 CHECK_STREQ(fh.GetName(), "zombie");
532 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
533 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700534
535 Heap::SetReferenceOffsets(referent->GetOffset(),
536 queue->GetOffset(),
537 queueNext->GetOffset(),
538 pendingNext->GetOffset(),
539 zombie->GetOffset());
540
Brian Carlstroma663ea52011-08-19 23:33:41 -0700541 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700542 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700543 ClassRoot class_root = static_cast<ClassRoot>(i);
544 Class* klass = GetClassRoot(class_root);
545 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700546 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700547 // note SetClassRoot does additional validation.
548 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700549 }
550
Elliott Hughes92f14b22011-10-06 12:29:54 -0700551 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700552
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700553 // disable the slow paths in FindClass and CreatePrimitiveClass now
554 // that Object, Class, and Object[] are setup
555 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700556
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800557 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700558}
559
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700560void ClassLinker::RunRootClinits() {
561 Thread* self = Thread::Current();
562 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
563 Class* c = GetClassRoot(ClassRoot(i));
564 if (!c->IsArrayClass() && !c->IsPrimitive()) {
565 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700566 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700567 }
568 }
569}
570
Brian Carlstromd601af82012-01-06 10:15:19 -0800571bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
572 int oat_fd,
573 const std::string& oat_cache_filename) {
jeffhao262bf462011-10-20 18:36:32 -0700574
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800575 std::string dex2oat_string("/system/bin/dex2oat");
576#ifndef NDEBUG
577 dex2oat_string += 'd';
578#endif
579 const char* dex2oat = dex2oat_string.c_str();
580
581 const char* class_path = Runtime::Current()->GetClassPath().c_str();
582
583 std::string boot_image_option_string("--boot-image=");
584 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
585 const char* boot_image_option = boot_image_option_string.c_str();
586
587 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800588 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800589 const char* dex_file_option = dex_file_option_string.c_str();
590
Brian Carlstromd601af82012-01-06 10:15:19 -0800591 std::string oat_fd_option_string("--oat-fd=");
592 oat_fd_option_string += oat_fd;
593 const char* oat_fd_option = oat_fd_option_string.c_str();
594
595 std::string oat_name_option_string("--oat-name=");
596 oat_name_option_string += oat_cache_filename;
597 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800598
jeffhao262bf462011-10-20 18:36:32 -0700599 // fork and exec dex2oat
600 pid_t pid = fork();
601 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800602 // no allocation allowed between fork and exec
603 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700604 "--runtime-arg", "-Xms64m",
605 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500606 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800607 "--runtime-arg", class_path,
608 boot_image_option,
609 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800610 oat_fd_option,
611 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700612 NULL);
613
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800614 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800615 return false;
jeffhao262bf462011-10-20 18:36:32 -0700616 } else {
617 // wait for dex2oat to finish
618 int status;
619 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
620 if (got_pid != pid) {
621 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800622 return false;
jeffhao262bf462011-10-20 18:36:32 -0700623 }
624 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800625 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
626 return false;
jeffhao262bf462011-10-20 18:36:32 -0700627 }
628 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800629 return true;
jeffhao262bf462011-10-20 18:36:32 -0700630}
631
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700632OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700633 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700634 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800635 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700636 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800637 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
638 // check the down cast
639 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700640 std::string oat_filename;
641 oat_filename += runtime->GetHostPrefix();
642 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700643 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700644 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700645 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700646 return NULL;
647 }
648 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
649 uint32_t image_oat_checksum = image_header.GetOatChecksum();
650 if (oat_checksum != image_oat_checksum) {
651 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
652 << " to expected oat checksum " << std::hex << oat_checksum
653 << " in image";
654 return NULL;
655 }
656 oat_files_.push_back(oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800657 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700658 return oat_file;
659}
660
Brian Carlstromae826982011-11-09 01:33:42 -0800661const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
662 for (size_t i = 0; i < oat_files_.size(); i++) {
663 const OatFile* oat_file = oat_files_[i];
664 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800665 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800666 return oat_file;
667 }
668 }
669 return NULL;
670}
671
Brian Carlstromd601af82012-01-06 10:15:19 -0800672class LockedFd {
673 public:
674 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
675 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
676 if (fd == -1) {
677 PLOG(ERROR) << "Failed to open file '" << name << "'";
678 return NULL;
679 }
680 fchmod(fd, mode);
681
682 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
683 // try to lock non-blocking so we can log if we need may need to block
684 int result = flock(fd, LOCK_EX | LOCK_NB);
685 if (result == -1) {
686 LOG(WARNING) << "sleeping while locking file " << name;
687 // retry blocking
688 result = flock(fd, LOCK_EX);
689 }
690 if (result == -1) {
691 PLOG(ERROR) << "Failed to lock file '" << name << "'";
692 close(fd);
693 return NULL;
694 }
695 return new LockedFd(fd);
696 }
697
698 int GetFd() const {
699 return fd_;
700 }
701
702 ~LockedFd() {
703 if (fd_ != -1) {
704 int result = flock(fd_, LOCK_UN);
705 if (result == -1) {
706 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
707 }
708 close(fd_);
709 }
710 }
711
712 private:
713 explicit LockedFd(int fd) : fd_(fd) {}
714
715 int fd_;
716};
717
Brian Carlstromae826982011-11-09 01:33:42 -0800718const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700719 MutexLock mu(dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800720 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
721 if (oat_file != NULL) {
722 return oat_file;
723 }
724
Brian Carlstromd601af82012-01-06 10:15:19 -0800725 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
726 while (true) {
727 oat_file = FindOatFileFromOatLocation(oat_filename);
728 if (oat_file != NULL) {
729 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
730 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
731 oat_files_.push_back(oat_file);
732 return oat_file;
733 }
734 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
735 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
736 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
737 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
738 }
739 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700740 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800741 // Try to generate oat file if it wasn't found or was obsolete.
742 // Note we can be racing with another runtime to do this.
743 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
744 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
745 if (locked_fd.get() == NULL) {
746 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
747 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700748 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800749 // Check to see if the fd we opened and locked matches the file in
750 // the filesystem. If they don't, then somebody else unlinked ours
751 // and created a new file, and we need to use that one instead. (If
752 // we caught them between the unlink and the create, we'll get an
753 // ENOENT from the file stat.)
754 struct stat fd_stat;
755 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
756 if (fd_stat_result != 0) {
757 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
758 return NULL;
759 }
760 struct stat file_stat;
761 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
762 if (file_stat_result != 0
763 || fd_stat.st_dev != file_stat.st_dev
764 || fd_stat.st_ino != file_stat.st_ino) {
765 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
766 usleep(250 * 1000); // if something is hosed, don't peg machine
767 continue;
768 }
769
770 // We have the correct file open and locked. If the file size is
771 // zero, then it was just created by us and we can generate its
772 // contents. If not, someone else created it. Either way, we'll
773 // loop to retry opening the file.
774 if (fd_stat.st_size == 0) {
775 bool success = GenerateOatFile(dex_file.GetLocation(),
776 locked_fd->GetFd(),
777 oat_cache_filename);
778 if (!success) {
779 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
780 return NULL;
781 }
782 }
jeffhao262bf462011-10-20 18:36:32 -0700783 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800784 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700785}
786
Brian Carlstromae826982011-11-09 01:33:42 -0800787const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700788 for (size_t i = 0; i < oat_files_.size(); i++) {
789 const OatFile* oat_file = oat_files_[i];
790 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800791 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700792 return oat_file;
793 }
794 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700795 return NULL;
796}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700797
Brian Carlstromae826982011-11-09 01:33:42 -0800798const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
799 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700800 if (oat_file != NULL) {
801 return oat_file;
802 }
803
Brian Carlstromae826982011-11-09 01:33:42 -0800804 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700805 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800806 if (oat_location.empty() || oat_location[0] != '/') {
807 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700808 return NULL;
809 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700810
Brian Carlstroma9f19782011-10-13 00:14:47 -0700811 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800812 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800813 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700814 if (oat_file != NULL) {
815 return oat_file;
816 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700817 oat_file = OatFile::Open(cache_location, "", NULL);
818 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800819 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700820 return NULL;
821 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700822 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700823
Brian Carlstromae826982011-11-09 01:33:42 -0800824 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromfad71432011-10-16 20:25:10 -0700825 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700826 return oat_file;
827}
828
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700829void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800830 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700831 CHECK(!init_done_);
832
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700833 const std::vector<Space*>& spaces = Heap::GetSpaces();
834 for (size_t i = 0; i < spaces.size(); i++) {
835 Space* space = spaces[i] ;
836 if (space->IsImageSpace()) {
837 OatFile* oat_file = OpenOat(space);
838 CHECK(oat_file != NULL) << "Failed to open oat file for image";
839 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
840 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
841
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800842 if (i == 0) {
843 // Special case of setting up the String class early so that we can test arbitrary objects
844 // as being Strings or not
845 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
846 ->AsObjectArray<Class>()->Get(kJavaLangString);
847 String::SetClass(java_lang_String);
848 }
849
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700850 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
851 static_cast<uint32_t>(dex_caches->GetLength()));
852 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700853 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800854 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800855 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
856 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700857 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800858 LOG(FATAL) << "Failed to open dex file " << dex_file_location
859 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700860 }
861
Brian Carlstromaded5f72011-10-07 17:15:04 -0700862 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700863
Brian Carlstromdf143242011-10-10 18:05:34 -0700864 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700865 }
866 }
867 }
868
Brian Carlstroma663ea52011-08-19 23:33:41 -0700869 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
870 DCHECK(heap_bitmap != NULL);
871
Brian Carlstroma663ea52011-08-19 23:33:41 -0700872 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700873 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700874
875 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700876 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
877 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700878
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800879 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700880 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
881 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800882 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700883 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700884 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700885 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
886 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
887 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
888 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
889 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
890 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
891 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
892 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700893 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700894 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700895
896 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700897
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800898 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700899}
900
Brian Carlstrom78128a62011-09-15 17:21:19 -0700901void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700902 DCHECK(obj != NULL);
903 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700904 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700905
Elliott Hughesdbb40792011-11-18 17:05:22 -0800906 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700907 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700908 return;
909 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700910 if (obj->IsClass()) {
911 // restore class to ClassLinker::classes_ table
912 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800913 ClassHelper kh(klass, class_linker);
914 bool success = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
Ian Rogers5d76c432011-10-31 21:42:49 -0700915 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700916 return;
917 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700918}
919
920// Keep in sync with InitCallback. Anything we visit, we need to
921// reinit references to when reinitializing a ClassLinker from a
922// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700923void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
924 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700925
926 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700927 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700928 }
929
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700930 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700931 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700932 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700933 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700934 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700935 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700936 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700937 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700938
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700939 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700940}
941
Elliott Hughesa2155262011-11-16 16:26:58 -0800942void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
943 MutexLock mu(classes_lock_);
944 typedef Table::const_iterator It; // TODO: C++0x auto
945 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
946 if (!visitor(it->second, arg)) {
947 return;
948 }
949 }
950 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
951 if (!visitor(it->second, arg)) {
952 return;
953 }
954 }
955}
956
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700957ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700958 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700959 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700960 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700961 BooleanArray::ResetArrayClass();
962 ByteArray::ResetArrayClass();
963 CharArray::ResetArrayClass();
964 DoubleArray::ResetArrayClass();
965 FloatArray::ResetArrayClass();
966 IntArray::ResetArrayClass();
967 LongArray::ResetArrayClass();
968 ShortArray::ResetArrayClass();
969 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700970 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700971 STLDeleteElements(&boot_class_path_);
972 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700973}
974
975DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700976 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
977 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700978 return NULL;
979 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700980 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
981 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700982 return NULL;
983 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700984 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
985 if (strings.get() == NULL) {
986 return NULL;
987 }
988 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
989 if (types.get() == NULL) {
990 return NULL;
991 }
992 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
993 if (methods.get() == NULL) {
994 return NULL;
995 }
996 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
997 if (fields.get() == NULL) {
998 return NULL;
999 }
1000 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1001 if (code_and_direct_methods.get() == NULL) {
1002 return NULL;
1003 }
1004 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1005 if (initialized_static_storage.get() == NULL) {
1006 return NULL;
1007 }
1008
1009 dex_cache->Init(location.get(),
1010 strings.get(),
1011 types.get(),
1012 methods.get(),
1013 fields.get(),
1014 code_and_direct_methods.get(),
1015 initialized_static_storage.get());
1016 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001017}
1018
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001019CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1020 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001021}
1022
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001023InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1024 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001025 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1026 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001027 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001028 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001029}
1030
Brian Carlstrom4873d462011-08-21 15:23:39 -07001031Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1032 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001033 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001034 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001035 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001036 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001037}
1038
Brian Carlstrom4873d462011-08-21 15:23:39 -07001039Class* ClassLinker::AllocClass(size_t class_size) {
1040 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001041}
1042
Jesse Wilson35baaab2011-08-10 16:18:03 -04001043Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001044 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001045}
1046
1047Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001048 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001049}
1050
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001051ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1052 return ObjectArray<StackTraceElement>::Alloc(
1053 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1054 length);
1055}
1056
Brian Carlstromaded5f72011-10-07 17:15:04 -07001057Class* EnsureResolved(Class* klass) {
1058 DCHECK(klass != NULL);
1059 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001060 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001061 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001062 ObjectLock lock(klass);
1063 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001064 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001065 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001066 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001067 return NULL;
1068 }
1069 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001070 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001071 lock.Wait();
1072 }
1073 }
1074 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001075 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001076 return NULL;
1077 }
1078 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001079 CHECK(klass->IsResolved()) << PrettyClass(klass);
1080 CHECK(!self->IsExceptionPending())
1081 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1082 return klass;
1083}
1084
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001085Class* ClassLinker::FindSystemClass(const char* descriptor) {
1086 return FindClass(descriptor, NULL);
1087}
1088
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001089Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
1090 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001091 Thread* self = Thread::Current();
1092 DCHECK(self != NULL);
1093 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001094 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001095 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1096 // for primitive classes that aren't backed by dex files.
1097 return FindPrimitiveClass(descriptor[0]);
1098 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001099 // Find the class in the loaded classes table.
1100 Class* klass = LookupClass(descriptor, class_loader);
1101 if (klass != NULL) {
1102 return EnsureResolved(klass);
1103 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001104 // Class is not yet loaded.
1105 if (descriptor[0] == '[') {
1106 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001107
Jesse Wilson47daf872011-11-23 11:42:45 -05001108 } else if (class_loader == NULL) {
1109 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1110 if (pair.second != NULL) {
1111 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1112 }
1113
1114 } else if (ClassLoader::UseCompileTimeClassPath()) {
1115 // first try the boot class path
1116 Class* system_class = FindSystemClass(descriptor);
1117 if (system_class != NULL) {
1118 return system_class;
1119 }
1120 CHECK(self->IsExceptionPending());
1121 self->ClearException();
1122
1123 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001124 const std::vector<const DexFile*>& class_path
1125 = ClassLoader::GetCompileTimeClassPath(class_loader);
1126 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001127 if (pair.second != NULL) {
1128 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001129 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001130
1131 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001132 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001133 ScopedThreadStateChange(self, Thread::kNative);
1134 JNIEnv* env = self->GetJniEnv();
1135 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1136 CHECK(c.get() != NULL);
1137 // TODO: cache method?
1138 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1139 CHECK(mid != NULL);
1140 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1141 if (class_name_object.get() == NULL) {
1142 return NULL;
1143 }
1144 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1145 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
Ian Rogers6b0870d2011-12-15 19:38:12 -08001146 if (!env->ExceptionOccurred()) {
1147 return Decode<Class*>(env, result.get());
1148 } else {
1149 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1150 // TODO: initialize the cause of the NCDFE to this exception
1151 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001152 }
1153
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001154 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001155 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001156}
1157
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001158Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001159 const ClassLoader* class_loader,
1160 const DexFile& dex_file,
1161 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001162 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001163 // Load the class from the dex file.
1164 if (!init_done_) {
1165 // finish up init of hand crafted class_roots_
1166 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001167 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001168 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001169 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001170 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001171 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001172 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001173 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001174 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001175 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001176 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001177 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001178 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001179 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001180 }
1181 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001182 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001183 }
1184 klass->SetDexCache(FindDexCache(dex_file));
1185 LoadClass(dex_file, dex_class_def, klass, class_loader);
1186 // Check for a pending exception during load
1187 Thread* self = Thread::Current();
1188 if (self->IsExceptionPending()) {
1189 return NULL;
1190 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 klass->SetClinitThreadId(self->GetTid());
1193 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001194 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001195 if (!success) {
1196 // We may fail to insert if we raced with another thread.
1197 klass->SetClinitThreadId(0);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001198 klass.reset(LookupClass(descriptor.data(), class_loader));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001199 CHECK(klass.get() != NULL);
1200 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001201 }
1202 // Finish loading (if necessary) by finding parents
1203 CHECK(!klass->IsLoaded());
1204 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1205 // Loading failed.
1206 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001207 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001208 lock.NotifyAll();
1209 return NULL;
1210 }
1211 CHECK(klass->IsLoaded());
1212 // Link the class (if necessary)
1213 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001214 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001215 // Linking failed.
1216 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001217 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001218 lock.NotifyAll();
1219 return NULL;
1220 }
1221 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001222
1223 /*
1224 * We send CLASS_PREPARE events to the debugger from here. The
1225 * definition of "preparation" is creating the static fields for a
1226 * class and initializing them to the standard default values, but not
1227 * executing any code (that comes later, during "initialization").
1228 *
1229 * We did the static preparation in LinkClass.
1230 *
1231 * The class has been prepared and resolved but possibly not yet verified
1232 * at this point.
1233 */
1234 Dbg::PostClassPrepare(klass.get());
1235
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001236 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001237}
1238
Brian Carlstrom4873d462011-08-21 15:23:39 -07001239// Precomputes size that will be needed for Class, matching LinkStaticFields
1240size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1241 const DexFile::ClassDef& dex_class_def) {
1242 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001243 size_t num_ref = 0;
1244 size_t num_32 = 0;
1245 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001246 if (class_data != NULL) {
1247 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1248 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001249 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001250 char c = descriptor[0];
1251 if (c == 'L' || c == '[') {
1252 num_ref++;
1253 } else if (c == 'J' || c == 'D') {
1254 num_64++;
1255 } else {
1256 num_32++;
1257 }
1258 }
1259 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001260 // start with generic class data
1261 size_t size = sizeof(Class);
1262 // follow with reference fields which must be contiguous at start
1263 size += (num_ref * sizeof(uint32_t));
1264 // if there are 64-bit fields to add, make sure they are aligned
1265 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1266 if (num_32 != 0) {
1267 // use an available 32-bit field for padding
1268 num_32--;
1269 }
1270 size += sizeof(uint32_t); // either way, we are adding a word
1271 DCHECK_EQ(size, RoundUp(size, 8));
1272 }
1273 // tack on any 64-bit fields now that alignment is assured
1274 size += (num_64 * sizeof(uint64_t));
1275 // tack on any remaining 32-bit fields
1276 size += (num_32 * sizeof(uint32_t));
1277 return size;
1278}
1279
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001280void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001281 // Every kind of method should at least get an invoke stub from the oat_method.
1282 // non-abstract methods also get their code pointers.
1283 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001284 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001285
1286 if (method->IsAbstract()) {
1287 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1288 return;
1289 }
1290 if (method->IsNative()) {
1291 // unregistering restores the dlsym lookup stub
1292 method->UnregisterNative();
1293 return;
1294 }
1295}
1296
Brian Carlstromf615a612011-07-23 12:50:34 -07001297void ClassLinker::LoadClass(const DexFile& dex_file,
1298 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001299 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001300 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001301 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001302 CHECK(klass->GetDexCache() != NULL);
1303 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001304 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001305 CHECK(descriptor != NULL);
1306
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001307 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001308 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001309 // Make sure that none of our runtime-only flags are set.
1310 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001311 klass->SetAccessFlags(access_flags);
1312 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001313 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001314 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001315
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001316 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001317
Ian Rogers0571d352011-11-03 19:51:38 -07001318 // Load fields fields.
1319 const byte* class_data = dex_file.GetClassData(dex_class_def);
1320 if (class_data == NULL) {
1321 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001322 }
Ian Rogers0571d352011-11-03 19:51:38 -07001323 ClassDataItemIterator it(dex_file, class_data);
1324 if (it.NumStaticFields() != 0) {
1325 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1326 }
1327 if (it.NumInstanceFields() != 0) {
1328 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1329 }
1330 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1331 SirtRef<Field> sfield(AllocField());
1332 klass->SetStaticField(i, sfield.get());
1333 LoadField(dex_file, it, klass, sfield);
1334 }
1335 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1336 SirtRef<Field> ifield(AllocField());
1337 klass->SetInstanceField(i, ifield.get());
1338 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001339 }
1340
Brian Carlstromaded5f72011-10-07 17:15:04 -07001341 UniquePtr<const OatFile::OatClass> oat_class;
1342 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001343 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001344 if (oat_file != NULL) {
1345 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1346 if (oat_dex_file != NULL) {
1347 uint32_t class_def_index;
1348 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1349 CHECK(found) << descriptor;
1350 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001351 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001352 }
1353 }
1354 }
Ian Rogers0571d352011-11-03 19:51:38 -07001355 // Load methods.
1356 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001357 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001358 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001359 }
Ian Rogers0571d352011-11-03 19:51:38 -07001360 if (it.NumVirtualMethods() != 0) {
1361 // TODO: append direct methods to class object
1362 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001363 }
Ian Rogers0571d352011-11-03 19:51:38 -07001364 size_t method_index = 0;
1365 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1366 SirtRef<Method> method(AllocMethod());
1367 klass->SetDirectMethod(i, method.get());
1368 LoadMethod(dex_file, it, klass, method);
1369 if (oat_class.get() != NULL) {
1370 LinkCode(method, oat_class.get(), method_index);
1371 }
1372 method_index++;
1373 }
1374 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1375 SirtRef<Method> method(AllocMethod());
1376 klass->SetVirtualMethod(i, method.get());
1377 LoadMethod(dex_file, it, klass, method);
1378 if (oat_class.get() != NULL) {
1379 LinkCode(method, oat_class.get(), method_index);
1380 }
1381 method_index++;
1382 }
1383 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001384}
1385
Ian Rogers0571d352011-11-03 19:51:38 -07001386void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1387 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001388 uint32_t field_idx = it.GetMemberIndex();
1389 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001390 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001391 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001392}
1393
Ian Rogers0571d352011-11-03 19:51:38 -07001394void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1395 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001396 uint32_t method_idx = it.GetMemberIndex();
1397 dst->SetDexMethodIndex(method_idx);
1398 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001399 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001400
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001401
1402 StringPiece method_name(dex_file.GetMethodName(method_id));
1403 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001404 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1405 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001406
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001407 if (method_name == "finalize") {
1408 // Create the prototype for a signature of "()V"
1409 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1410 if (void_string_id != NULL) {
1411 const DexFile::TypeId* void_type_id =
1412 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1413 if (void_type_id != NULL) {
1414 std::vector<uint16_t> no_args;
1415 const DexFile::ProtoId* finalizer_proto =
1416 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1417 if (finalizer_proto != NULL) {
1418 // We have the prototype in the dex file
1419 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1420 klass->SetFinalizable();
1421 } else {
1422 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1423 // The Enum class declares a "final" finalize() method to prevent subclasses from
1424 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1425 // subclasses, so we exclude it here.
1426 // We also want to avoid setting the flag on Object, where we know that finalize() is
1427 // empty.
1428 if (klass_descriptor != "Ljava/lang/Object;" &&
1429 klass_descriptor != "Ljava/lang/Enum;") {
1430 klass->SetFinalizable();
1431 }
1432 }
1433 }
1434 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001435 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001436 }
Ian Rogers0571d352011-11-03 19:51:38 -07001437 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001438 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001439
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001440 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1441 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1442 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1443 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1444 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1445 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001446
Brian Carlstrom934486c2011-07-12 23:42:50 -07001447 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001448}
1449
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001450void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001451 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1452 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001453}
1454
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001455void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1456 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001457 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001458 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001459}
1460
Brian Carlstromaded5f72011-10-07 17:15:04 -07001461bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001462 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001463 for (size_t i = 0; i != dex_files_.size(); ++i) {
1464 if (dex_files_[i] == &dex_file) {
1465 return true;
1466 }
1467 }
1468 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001469}
1470
Brian Carlstromaded5f72011-10-07 17:15:04 -07001471bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001472 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001473 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001474}
1475
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001476void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001477 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001478 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001479 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001480 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001481 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001482}
1483
Brian Carlstromaded5f72011-10-07 17:15:04 -07001484void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001485 {
1486 MutexLock mu(dex_lock_);
1487 if (IsDexFileRegisteredLocked(dex_file)) {
1488 return;
1489 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001490 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001491 // Don't alloc while holding the lock, since allocation may need to
1492 // suspend all threads and another thread may need the dex_lock_ to
1493 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001494 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001495 {
1496 MutexLock mu(dex_lock_);
1497 if (IsDexFileRegisteredLocked(dex_file)) {
1498 return;
1499 }
1500 RegisterDexFileLocked(dex_file, dex_cache);
1501 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001502}
1503
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001504void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001505 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001506 RegisterDexFileLocked(dex_file, dex_cache);
1507}
1508
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001509const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001510 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001511 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001512 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1513 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001514 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001515 }
1516 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001517 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001518 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001519}
1520
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001521DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001522 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001523 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001524 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001525 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001526 }
1527 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001528 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001529 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001530}
1531
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001532Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1533 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001534 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001535 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001536 CHECK(primitive_class != NULL);
1537 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001538 primitive_class->SetPrimitiveType(type);
1539 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001540 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001541 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1542 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001543}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001544
Brian Carlstrombe977852011-07-19 14:54:54 -07001545// Create an array class (i.e. the class object for the array, not the
1546// array itself). "descriptor" looks like "[C" or "[[[[B" or
1547// "[Ljava/lang/String;".
1548//
1549// If "descriptor" refers to an array of primitives, look up the
1550// primitive type's internally-generated class object.
1551//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001552// "class_loader" is the class loader of the class that's referring to
1553// us. It's used to ensure that we're looking for the element type in
1554// the right context. It does NOT become the class loader for the
1555// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001556//
1557// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001558Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001559 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001560
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001561 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001562 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001563 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001564 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001565 return NULL;
1566 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001567
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001568 // See if the component type is already loaded. Array classes are
1569 // always associated with the class loader of their underlying
1570 // element type -- an array of Strings goes with the loader for
1571 // java/lang/String -- so we need to look for it there. (The
1572 // caller should have checked for the existence of the class
1573 // before calling here, but they did so with *their* class loader,
1574 // not the component type's loader.)
1575 //
1576 // If we find it, the caller adds "loader" to the class' initiating
1577 // loader list, which should prevent us from going through this again.
1578 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001579 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001580 // are the same, because our caller (FindClass) just did the
1581 // lookup. (Even if we get this wrong we still have correct behavior,
1582 // because we effectively do this lookup again when we add the new
1583 // class to the hash table --- necessary because of possible races with
1584 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001585 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001586 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001587 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001588 return new_class;
1589 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001590 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001591
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001592 // Fill out the fields in the Class.
1593 //
1594 // It is possible to execute some methods against arrays, because
1595 // all arrays are subclasses of java_lang_Object_, so we need to set
1596 // up a vtable. We can just point at the one in java_lang_Object_.
1597 //
1598 // Array classes are simple enough that we don't need to do a full
1599 // link step.
1600
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001601 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001602 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001603 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001604 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001605 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001606 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001607 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001608 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001609 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001610 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001611 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001612 }
1613 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001614 if (new_class.get() == NULL) {
1615 new_class.reset(AllocClass(sizeof(Class)));
1616 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001617 return NULL;
1618 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001619 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001620 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001621 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001622 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001623 new_class->SetSuperClass(java_lang_Object);
1624 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001625 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001626 new_class->SetClassLoader(component_type->GetClassLoader());
1627 new_class->SetStatus(Class::kStatusInitialized);
1628 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001629 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001630
1631
1632 // All arrays have java/lang/Cloneable and java/io/Serializable as
1633 // interfaces. We need to set that up here, so that stuff like
1634 // "instanceof" works right.
1635 //
1636 // Note: The GC could run during the call to FindSystemClass,
1637 // so we need to make sure the class object is GC-valid while we're in
1638 // there. Do this by clearing the interface list so the GC will just
1639 // think that the entries are null.
1640
1641
1642 // Use the single, global copies of "interfaces" and "iftable"
1643 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001644 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001645 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001646
1647 // Inherit access flags from the component type. Arrays can't be
1648 // used as a superclass or interface, so we want to add "final"
1649 // and remove "interface".
1650 //
1651 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001652 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001653 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001654 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1655 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001656
Ian Rogers5d76c432011-10-31 21:42:49 -07001657 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001658 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001659 }
1660 // Another thread must have loaded the class after we
1661 // started but before we finished. Abandon what we've
1662 // done.
1663 //
1664 // (Yes, this happens.)
1665
1666 // Grab the winning class.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001667 Class* other_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001668 DCHECK(other_class != NULL);
1669 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001670}
1671
1672Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001673 switch (Primitive::GetType(type)) {
1674 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001675 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001676 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001677 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001678 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001679 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001680 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001681 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001682 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001683 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001684 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001685 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001686 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001687 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001688 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001689 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001690 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001691 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001692 case Primitive::kPrimNot:
1693 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001694 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001695 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001696 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001697 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001698}
1699
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001700bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001701 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001702 DexCache* dex_cache = klass->GetDexCache();
1703 std::string source;
1704 if (dex_cache != NULL) {
1705 source += " from ";
1706 source += dex_cache->GetLocation()->ToModifiedUtf8();
1707 }
1708 LOG(INFO) << "Loaded class " << descriptor << source;
1709 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001710 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001711 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001712 Table::iterator it;
1713 if (image_class) {
1714 // TODO: sanity check there's no match in classes_
1715 it = image_classes_.insert(std::make_pair(hash, klass));
1716 } else {
1717 // TODO: sanity check there's no match in image_classes_
1718 it = classes_.insert(std::make_pair(hash, klass));
1719 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001720 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001721}
1722
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001723bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1724 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001725 MutexLock mu(classes_lock_);
1726 typedef Table::const_iterator It; // TODO: C++0x auto
1727 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001728 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001729 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1730 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001731 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001732 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001733 classes_.erase(it);
1734 return true;
1735 }
1736 }
1737 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1738 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001739 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001740 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001741 image_classes_.erase(it);
1742 return true;
1743 }
1744 }
1745 return false;
1746}
1747
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001748Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1749 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001750 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001751 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001752 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001753 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001754 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001755 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001756 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001757 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001758 return klass;
1759 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001760 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001761 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1762 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001763 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001764 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001765 return klass;
1766 }
1767 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001768 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769}
1770
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001771void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001772 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001773 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001774 MutexLock mu(classes_lock_);
1775 typedef Table::const_iterator It; // TODO: C++0x auto
1776 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001777 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001778 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001779 Class* klass = it->second;
1780 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001781 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001782 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001783 }
1784 }
1785 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001786 Class* klass = it->second;
1787 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001788 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001789 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001790 }
1791 }
1792}
1793
jeffhao98eacac2011-09-14 16:11:53 -07001794void ClassLinker::VerifyClass(Class* klass) {
1795 if (klass->IsVerified()) {
1796 return;
1797 }
1798
1799 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001800 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001801
Ian Rogersd81871c2011-10-03 13:57:23 -07001802 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001803 klass->SetStatus(Class::kStatusVerified);
1804 } else {
1805 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001806 Thread* self = Thread::Current();
1807 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1808 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001809 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001810 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001811 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001812 }
jeffhao98eacac2011-09-14 16:11:53 -07001813}
1814
Ian Rogersc2b44472011-12-14 21:17:17 -08001815static void CheckProxyConstructor(Method* constructor);
1816static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1817
Jesse Wilson95caa792011-10-12 18:14:17 -04001818Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001819 ClassLoader* loader, ObjectArray<Method>* methods,
1820 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001821 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001822 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001823 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001824 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001825 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001826 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001827 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001828 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001829 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001830 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001831
1832 klass->SetStatus(Class::kStatusIdx);
1833
1834 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1835
1836 // Create static field that holds throws, instance fields are inherited
1837 klass->SetSFields(AllocObjectArray<Field>(1));
1838 SirtRef<Field> sfield(AllocField());
1839 klass->SetStaticField(0, sfield.get());
1840 sfield->SetDexFieldIndex(-1);
1841 sfield->SetDeclaringClass(klass.get());
1842 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001843
Ian Rogers466bb252011-10-14 03:29:56 -07001844 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001845 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001846 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001847
Ian Rogers466bb252011-10-14 03:29:56 -07001848 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001849 size_t num_virtual_methods = methods->GetLength();
1850 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1851 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001852 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001853 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001854 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001855
1856 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1857 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1858 DCHECK(!Thread::Current()->IsExceptionPending());
1859
1860 // Link the fields and virtual methods, creating vtable and iftables
1861 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001862 DCHECK(Thread::Current()->IsExceptionPending());
1863 return NULL;
1864 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001865 sfield->SetObject(NULL, throws); // initialize throws field
1866 klass->SetStatus(Class::kStatusInitialized);
1867
1868 // sanity checks
1869#ifndef NDEBUG
1870 bool debug = true;
1871#else
1872 bool debug = false;
1873#endif
1874 if (debug) {
1875 CHECK(klass->GetIFields() == NULL);
1876 CheckProxyConstructor(klass->GetDirectMethod(0));
1877 for (size_t i = 0; i < num_virtual_methods; ++i) {
1878 SirtRef<Method> prototype(methods->Get(i));
1879 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1880 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001881 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08001882 throws_field_name += name->ToModifiedUtf8();
1883 throws_field_name += ".throws";
1884 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1885
1886 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1887 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1888 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001889 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001890}
1891
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001892std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1893 DCHECK(proxy_class->IsProxyClass());
1894 String* name = proxy_class->GetName();
1895 DCHECK(name != NULL);
1896 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1897}
1898
1899
1900Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001901 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001902 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001903 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001904 Method* proxy_constructor = proxy_direct_methods->Get(2);
1905 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1906 // code_ too)
1907 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1908 // Make this constructor public and fix the class to be our Proxy version
1909 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001910 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001911 return constructor;
1912}
1913
1914static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001915 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001916 MethodHelper mh(constructor);
1917 CHECK_STREQ(mh.GetName(), "<init>");
1918 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001919 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001920}
1921
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001922Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1923 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1924 // prototype method
1925 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1926 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001927 // as necessary
1928 Method* method = down_cast<Method*>(prototype->Clone());
1929
1930 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1931 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001932 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001933 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001934
Ian Rogers466bb252011-10-14 03:29:56 -07001935 // At runtime the method looks like a reference and argument saving method, clone the code
1936 // related parameters from this method.
1937 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1938 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1939 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1940 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1941 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001942 return method;
1943}
Jesse Wilson95caa792011-10-12 18:14:17 -04001944
Ian Rogersc2b44472011-12-14 21:17:17 -08001945static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001946 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001947 CHECK(!prototype->IsFinal());
1948 CHECK(method->IsFinal());
1949 CHECK(!method->IsAbstract());
1950 MethodHelper mh(method);
1951 const char* method_name = mh.GetName();
1952 const char* method_shorty = mh.GetShorty();
1953 Class* method_return = mh.GetReturnType();
1954
1955 mh.ChangeMethod(prototype.get());
1956
1957 CHECK_STREQ(mh.GetName(), method_name);
1958 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001959
1960 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001961 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001962}
1963
Brian Carlstrom25c33252011-09-18 15:58:35 -07001964bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001965 CHECK(klass->IsResolved() || klass->IsErroneous())
1966 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967
Carl Shapirob5573532011-07-12 18:22:59 -07001968 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001969
Brian Carlstrom25c33252011-09-18 15:58:35 -07001970 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001971 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001972 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001973 ObjectLock lock(klass);
1974
Brian Carlstromd1422f82011-09-28 11:37:09 -07001975 if (klass->GetStatus() == Class::kStatusInitialized) {
1976 return true;
1977 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001978
Brian Carlstromd1422f82011-09-28 11:37:09 -07001979 if (klass->IsErroneous()) {
1980 ThrowEarlierClassFailure(klass);
1981 return false;
1982 }
1983
1984 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001985 VerifyClass(klass);
1986 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001987 return false;
1988 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001989 }
1990
Brian Carlstrom25c33252011-09-18 15:58:35 -07001991 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1992 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001993 // if the class has a <clinit> but we can't run it during compilation,
1994 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001995 return false;
1996 }
1997
Brian Carlstromd1422f82011-09-28 11:37:09 -07001998 // If the class is kStatusInitializing, either this thread is
1999 // initializing higher up the stack or another thread has beat us
2000 // to initializing and we need to wait. Either way, this
2001 // invocation of InitializeClass will not be responsible for
2002 // running <clinit> and will return.
2003 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002004 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002005 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002006 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002007 return true;
2008 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002009 // No. That's fine. Wait for another thread to finish initializing.
2010 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002011 }
2012
2013 if (!ValidateSuperClassDescriptors(klass)) {
2014 klass->SetStatus(Class::kStatusError);
2015 return false;
2016 }
2017
Brian Carlstromd1422f82011-09-28 11:37:09 -07002018 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002019
Elliott Hughesdcc24742011-09-07 14:02:44 -07002020 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002021 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002022 }
2023
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002024 uint64_t t0 = NanoTime();
2025
Brian Carlstrom25c33252011-09-18 15:58:35 -07002026 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002027 return false;
2028 }
2029
2030 InitializeStaticFields(klass);
2031
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002032 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002033 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002034 }
2035
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002036 uint64_t t1 = NanoTime();
2037
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002038 {
2039 ObjectLock lock(klass);
2040
2041 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002042 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002043 klass->SetStatus(Class::kStatusError);
2044 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002045 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2046 RuntimeStats* thread_stats = self->GetStats();
2047 ++global_stats->class_init_count;
2048 ++thread_stats->class_init_count;
2049 global_stats->class_init_time_ns += (t1 - t0);
2050 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002051 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002052 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002053 ClassHelper kh(klass);
2054 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002055 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002056 }
2057 lock.NotifyAll();
2058 }
2059
2060 return true;
2061}
2062
Brian Carlstromd1422f82011-09-28 11:37:09 -07002063bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2064 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002065 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002066 lock.Wait();
2067
2068 // When we wake up, repeat the test for init-in-progress. If
2069 // there's an exception pending (only possible if
2070 // "interruptShouldThrow" was set), bail out.
2071 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002072 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002073 klass->SetStatus(Class::kStatusError);
2074 return false;
2075 }
2076 // Spurious wakeup? Go back to waiting.
2077 if (klass->GetStatus() == Class::kStatusInitializing) {
2078 continue;
2079 }
2080 if (klass->IsErroneous()) {
2081 // The caller wants an exception, but it was thrown in a
2082 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002083 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002084 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002085 return false;
2086 }
2087 if (klass->IsInitialized()) {
2088 return true;
2089 }
2090 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2091 }
2092 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2093}
2094
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002095bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2096 if (klass->IsInterface()) {
2097 return true;
2098 }
2099 // begin with the methods local to the superclass
2100 if (klass->HasSuperClass() &&
2101 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2102 const Class* super = klass->GetSuperClass();
2103 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002104 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002105 if (method != super->GetVirtualMethod(i) &&
2106 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002107 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2108
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002109 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2110 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2111 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002112 return false;
2113 }
2114 }
2115 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002116 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2117 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2118 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002119 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2120 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002121 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002122 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002123 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002124 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2125
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002126 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2127 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2128 PrettyMethod(method).c_str(),
2129 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002130 return false;
2131 }
2132 }
2133 }
2134 }
2135 return true;
2136}
2137
2138bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002139 const Class* klass1,
2140 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002141 if (klass1 == klass2) {
2142 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002143 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002144 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002145 const DexFile::ProtoId& proto_id =
2146 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002147 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2148 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002149 if (descriptor == NULL) {
2150 break;
2151 }
2152 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2153 // Found a non-primitive type.
2154 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2155 return false;
2156 }
2157 }
2158 }
2159 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002160 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002161 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002162 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002163 return false;
2164 }
2165 }
2166 return true;
2167}
2168
2169// Returns true if classes referenced by the descriptor are the
2170// same classes in klass1 as they are in klass2.
2171bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002172 const Class* klass1,
2173 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002174 CHECK(descriptor != NULL);
2175 CHECK(klass1 != NULL);
2176 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002177 if (klass1 == klass2) {
2178 return true;
2179 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002180 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002181 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002182 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002183 // TODO: found2 == NULL
2184 // TODO: lookup found1 in initiating loader list
2185 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002186 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002187 return found1 == found2;
2188 } else {
2189 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002190 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002191}
2192
Brian Carlstrom25c33252011-09-18 15:58:35 -07002193bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002195 if (!klass->IsInterface() && klass->HasSuperClass()) {
2196 Class* super_class = klass->GetSuperClass();
2197 if (super_class->GetStatus() != Class::kStatusInitialized) {
2198 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002199 Thread* self = Thread::Current();
2200 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002201 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002202 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002203 // TODO: check for a pending exception
2204 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002205 if (!can_run_clinit) {
2206 // Don't set status to error when we can't run <clinit>.
2207 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2208 klass->SetStatus(Class::kStatusVerified);
2209 return false;
2210 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002211 klass->SetStatus(Class::kStatusError);
2212 klass->NotifyAll();
2213 return false;
2214 }
2215 }
2216 }
2217 return true;
2218}
2219
Brian Carlstrom25c33252011-09-18 15:58:35 -07002220bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002221 CHECK(c != NULL);
2222 if (c->IsInitialized()) {
2223 return true;
2224 }
2225
Elliott Hughes5f791332011-09-15 17:45:30 -07002226 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002227 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002228 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002229 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002230}
2231
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002232void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002233 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002234 const ClassLoader* cl = c->GetClassLoader();
2235 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002236 ClassDataItemIterator it(dex_file, class_data);
2237 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2238 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002239 }
2240}
2241
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002242void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002243 size_t num_static_fields = klass->NumStaticFields();
2244 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002245 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002246 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002247 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002248 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002249 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002250 return;
2251 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002252 ClassHelper kh(klass);
2253 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002254 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002255 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002256 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002257
Ian Rogers0571d352011-11-03 19:51:38 -07002258 if (it.HasNext()) {
2259 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2260 std::map<uint32_t, Field*> field_map;
2261 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2262 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2263 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002264 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265 }
2266}
2267
Ian Rogersc2b44472011-12-14 21:17:17 -08002268bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002269 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002270 if (!LinkSuperClass(klass)) {
2271 return false;
2272 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002273 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002274 return false;
2275 }
2276 if (!LinkInstanceFields(klass)) {
2277 return false;
2278 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002279 if (!LinkStaticFields(klass)) {
2280 return false;
2281 }
2282 CreateReferenceInstanceOffsets(klass);
2283 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002284 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2285 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002286 return true;
2287}
2288
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002289bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002290 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002291 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2292 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2293 if (class_def == NULL) {
2294 return false;
2295 }
2296 uint16_t super_class_idx = class_def->superclass_idx_;
2297 if (super_class_idx != DexFile::kDexNoIndex16) {
2298 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002300 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002301 return false;
2302 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002303 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002304 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002305 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2306 if (interfaces != NULL) {
2307 for (size_t i = 0; i < interfaces->Size(); i++) {
2308 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2309 Class* interface = ResolveType(dex_file, idx, klass.get());
2310 if (interface == NULL) {
2311 DCHECK(Thread::Current()->IsExceptionPending());
2312 return false;
2313 }
2314 // Verify
2315 if (!klass->CanAccess(interface)) {
2316 // TODO: the RI seemed to ignore this in my testing.
2317 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2318 "Interface %s implemented by class %s is inaccessible",
2319 PrettyDescriptor(interface).c_str(),
2320 PrettyDescriptor(klass.get()).c_str());
2321 return false;
2322 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002323 }
2324 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002325 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002326 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002327 return true;
2328}
2329
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002330bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002331 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002332 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002333 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002334 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002335 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002336 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002337 return false;
2338 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002339 return true;
2340 }
2341 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002342 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002343 return false;
2344 }
2345 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002346 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002347 Thread* thread = Thread::Current();
2348 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002349 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002350 PrettyDescriptor(super).c_str(),
2351 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002352 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002353 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002354 return false;
2355 }
2356 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002357 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002358 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002359 PrettyDescriptor(super).c_str(),
2360 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002361 return false;
2362 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002363
2364 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2365 if (super->IsFinalizable()) {
2366 klass->SetFinalizable();
2367 }
2368
Elliott Hughes2da50362011-10-10 16:57:08 -07002369 // Inherit reference flags (if any) from the superclass.
2370 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2371 if (reference_flags != 0) {
2372 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2373 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002374 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002375 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002376 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002377 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002378 return false;
2379 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002380
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002381#ifndef NDEBUG
2382 // Ensure super classes are fully resolved prior to resolving fields..
2383 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002384 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002385 super = super->GetSuperClass();
2386 }
2387#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002388 return true;
2389}
2390
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002391// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002392bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002393 if (klass->IsInterface()) {
2394 // No vtable.
2395 size_t count = klass->NumVirtualMethods();
2396 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002397 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002398 return false;
2399 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002400 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002401 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002402 }
jeffhaobdb76512011-09-07 11:43:16 -07002403 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002404 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002405 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002406 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002407 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002408 }
2409 return true;
2410}
2411
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002412bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002413 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002414 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2415 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002416 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002417 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002418 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002419 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002420 MethodHelper local_mh(NULL, this);
2421 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002422 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002423 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002424 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002425 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002426 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002427 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002428 super_mh.ChangeMethod(super_method);
2429 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 // Verify
2431 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002432 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002433 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002434 PrettyDescriptor(klass.get()).c_str(),
2435 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002436 return false;
2437 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002438 vtable->Set(j, local_method);
2439 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002440 break;
2441 }
2442 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002443 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002444 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002445 vtable->Set(actual_count, local_method);
2446 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002447 actual_count += 1;
2448 }
2449 }
2450 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002451 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002452 return false;
2453 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002454 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002455 CHECK_LE(actual_count, max_count);
2456 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002457 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002458 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002459 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002460 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002461 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002462 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002463 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002464 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002465 return false;
2466 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002467 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002468 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002469 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2470 vtable->Set(i, virtual_method);
2471 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002472 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002473 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002474 }
2475 return true;
2476}
2477
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002478bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002479 size_t super_ifcount;
2480 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002481 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002482 } else {
2483 super_ifcount = 0;
2484 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002485 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002486 ClassHelper kh(klass.get(), this);
2487 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2488 ifcount += num_interfaces;
2489 for (size_t i = 0; i < num_interfaces; i++) {
2490 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2491 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002492 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002493 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002494 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002495 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002496 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002497 return true;
2498 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002499 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002500 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002501 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2502 for (size_t i = 0; i < super_ifcount; i++) {
2503 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2504 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002505 }
2506 // Flatten the interface inheritance hierarchy.
2507 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002508 for (size_t i = 0; i < num_interfaces; i++) {
2509 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002510 DCHECK(interface != NULL);
2511 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002512 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002513 Thread* thread = Thread::Current();
2514 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002515 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002516 PrettyDescriptor(klass.get()).c_str(),
2517 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002518 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519 return false;
2520 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002521 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002522 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002523 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002524 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2525 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002526 }
2527 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002528 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002529 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002530
2531 // If we're an interface, we don't need the vtable pointers, so we're done.
2532 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002533 return true;
2534 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002535 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002536 MethodHelper vtable_mh(NULL, this);
2537 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002538 for (size_t i = 0; i < ifcount; ++i) {
2539 InterfaceEntry* interface_entry = iftable->Get(i);
2540 Class* interface = interface_entry->GetInterface();
2541 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2542 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002543 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002544 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2545 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002546 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002547 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002548 // For each method listed in the interface's method list, find the
2549 // matching method in our class's method list. We want to favor the
2550 // subclass over the superclass, which just requires walking
2551 // back from the end of the vtable. (This only matters if the
2552 // superclass defines a private method and this class redefines
2553 // it -- otherwise it would use the same vtable slot. In .dex files
2554 // those don't end up in the virtual method table, so it shouldn't
2555 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002556 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2557 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002558 vtable_mh.ChangeMethod(vtable_method);
2559 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002560 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002561 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002562 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002563 return false;
2564 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002565 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002566 break;
2567 }
2568 }
2569 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002570 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002571 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002572 Method* mir_method = miranda_list[mir];
2573 vtable_mh.ChangeMethod(mir_method);
2574 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002575 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002576 break;
2577 }
2578 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002579 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002580 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002581 miranda_method.reset(AllocMethod());
2582 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2583 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002585 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002586 }
2587 }
2588 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002589 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002590 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002591 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002592 klass->SetVirtualMethods((old_method_count == 0)
2593 ? AllocObjectArray<Method>(new_method_count)
2594 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002596 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2597 CHECK(vtable != NULL);
2598 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002599 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002600 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002601 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002602 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002603 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002604 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2605 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2606 klass->SetVirtualMethod(old_method_count + i, method);
2607 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002608 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002609 // TODO: do not assign to the vtable field until it is fully constructed.
2610 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002611 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002612
2613 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2614 for (int i = 0; i < vtable->GetLength(); ++i) {
2615 CHECK(vtable->Get(i) != NULL);
2616 }
2617
2618// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2619
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002620 return true;
2621}
2622
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002623bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2624 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002625 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002626}
2627
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002628bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2629 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002630 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002631 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002632 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002633 return success;
2634}
2635
Brian Carlstromdbc05252011-09-09 01:59:59 -07002636struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002637 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002638 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002639 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002640 fh_->ChangeField(field1);
2641 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2642 fh_->ChangeField(field2);
2643 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002644 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2645 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2646 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2647 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002648 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2649 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2650 if (order1 != order2) {
2651 return order1 < order2;
2652 }
2653
2654 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002655 fh_->ChangeField(field1);
2656 StringPiece name1(fh_->GetName());
2657 fh_->ChangeField(field2);
2658 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002659 return name1 < name2;
2660 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002661
2662 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002663};
2664
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002665bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002666 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002667 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002668
2669 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002670 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002671
2672 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002673 size_t size;
2674 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002675 if (is_static) {
2676 size = klass->GetClassSize();
2677 field_offset = Class::FieldsOffset();
2678 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002679 Class* super_class = klass->GetSuperClass();
2680 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002681 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002682 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002683 }
2684 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002685 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002686
Brian Carlstromdbc05252011-09-09 01:59:59 -07002687 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002688
Brian Carlstromdbc05252011-09-09 01:59:59 -07002689 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002690 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002691 std::deque<Field*> grouped_and_sorted_fields;
2692 for (size_t i = 0; i < num_fields; i++) {
2693 grouped_and_sorted_fields.push_back(fields->Get(i));
2694 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002695 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002696 std::sort(grouped_and_sorted_fields.begin(),
2697 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002698 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002699
2700 // References should be at the front.
2701 size_t current_field = 0;
2702 size_t num_reference_fields = 0;
2703 for (; current_field < num_fields; current_field++) {
2704 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002705 fh.ChangeField(field);
2706 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002707 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002708 if (isPrimitive) {
2709 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002710 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002711 grouped_and_sorted_fields.pop_front();
2712 num_reference_fields++;
2713 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002714 field->SetOffset(field_offset);
2715 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002716 }
2717
2718 // Now we want to pack all of the double-wide fields together. If
2719 // we're not aligned, though, we want to shuffle one 32-bit field
2720 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002721 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002722 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2723 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002724 fh.ChangeField(field);
2725 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002726 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2727 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002728 continue;
2729 }
2730 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002731 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002732 // drop the consumed field
2733 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2734 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002735 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002736 // whether we found a 32-bit field for padding or not, we advance
2737 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002738 }
2739
2740 // Alignment is good, shuffle any double-wide fields forward, and
2741 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002742 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002743 while (!grouped_and_sorted_fields.empty()) {
2744 Field* field = grouped_and_sorted_fields.front();
2745 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002746 fh.ChangeField(field);
2747 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002748 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002749 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002750 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002751 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002752 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002753 ? sizeof(uint64_t)
2754 : sizeof(uint32_t)));
2755 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002756 }
2757
Elliott Hughesadb460d2011-10-05 17:02:34 -07002758 // 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 -08002759 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2760 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002761 // We know there are no non-reference fields in the Reference classes, and we know
2762 // that 'referent' is alphabetically last, so this is easy...
2763 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002764 fh.ChangeField(fields->Get(num_fields - 1));
2765 StringPiece name(fh.GetName());
2766 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002767 --num_reference_fields;
2768 }
2769
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002770#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002771 // Make sure that all reference fields appear before
2772 // non-reference fields, and all double-wide fields are aligned.
2773 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002774 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002775 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002776 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002777 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002778 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002779 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002780 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2781 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002782 fh.ChangeField(field);
2783 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002784 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002785 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002786 is_primitive = true; // We lied above, so we have to expect a lie here.
2787 }
2788 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002789 if (!seen_non_ref) {
2790 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002791 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002792 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002793 } else {
2794 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002795 }
2796 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002797 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002798 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002799 }
2800#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002801 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002802 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002803 if (is_static) {
2804 klass->SetNumReferenceStaticFields(num_reference_fields);
2805 klass->SetClassSize(size);
2806 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002807 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002808 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002809 klass->SetObjectSize(size);
2810 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002811 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002812 return true;
2813}
2814
2815// Set the bitmap of reference offsets, refOffsets, from the ifields
2816// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002817void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002818 uint32_t reference_offsets = 0;
2819 Class* super_class = klass->GetSuperClass();
2820 if (super_class != NULL) {
2821 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002822 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002823 if (reference_offsets == CLASS_WALK_SUPER) {
2824 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002825 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002826 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002827 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002828 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002829}
2830
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002831void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002832 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002833}
2834
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002835void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002836 uint32_t reference_offsets) {
2837 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002838 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2839 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002840 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002841 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002842 // All of the fields that contain object references are guaranteed
2843 // to be at the beginning of the fields list.
2844 for (size_t i = 0; i < num_reference_fields; ++i) {
2845 // Note that byte_offset is the offset from the beginning of
2846 // object, not the offset into instance data
2847 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002848 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002849 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2850 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2851 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002852 CHECK_NE(new_bit, 0U);
2853 reference_offsets |= new_bit;
2854 } else {
2855 reference_offsets = CLASS_WALK_SUPER;
2856 break;
2857 }
2858 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002859 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002860 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002861 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002862 } else {
2863 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002864 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002865}
2866
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002867String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002868 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002869 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002870 if (resolved != NULL) {
2871 return resolved;
2872 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002873 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2874 int32_t utf16_length = dex_file.GetStringLength(string_id);
2875 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002876 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002877 dex_cache->SetResolvedString(string_idx, string);
2878 return string;
2879}
2880
2881Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002882 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002883 DexCache* dex_cache,
2884 const ClassLoader* class_loader) {
2885 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002886 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002887 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002888 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002889 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002890 // TODO: we used to throw here if resolved's class loader was not the
2891 // boot class loader. This was to permit different classes with the
2892 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002893 dex_cache->SetResolvedType(type_idx, resolved);
2894 } else {
2895 DCHECK(Thread::Current()->IsExceptionPending());
2896 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002897 }
2898 return resolved;
2899}
2900
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002901Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2902 uint32_t method_idx,
2903 DexCache* dex_cache,
2904 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002905 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002906 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2907 if (resolved != NULL) {
2908 return resolved;
2909 }
2910 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2911 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2912 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002913 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002914 return NULL;
2915 }
2916
Ian Rogers0571d352011-11-03 19:51:38 -07002917 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2918 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002919 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002920 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002921 } else if (klass->IsInterface()) {
2922 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002923 } else {
2924 resolved = klass->FindVirtualMethod(name, signature);
2925 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002926 if (resolved != NULL) {
2927 dex_cache->SetResolvedMethod(method_idx, resolved);
2928 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002929 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002930 }
2931 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002932}
2933
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002934Field* ClassLinker::ResolveField(const DexFile& dex_file,
2935 uint32_t field_idx,
2936 DexCache* dex_cache,
2937 const ClassLoader* class_loader,
2938 bool is_static) {
2939 Field* resolved = dex_cache->GetResolvedField(field_idx);
2940 if (resolved != NULL) {
2941 return resolved;
2942 }
2943 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2944 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2945 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002946 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002947 return NULL;
2948 }
2949
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002950 const char* name = dex_file.GetFieldName(field_id);
2951 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002952 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002953 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002954 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002955 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002956 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002957 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002958 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002959 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002960 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2961 }
2962 return resolved;
2963}
2964
2965Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2966 uint32_t field_idx,
2967 DexCache* dex_cache,
2968 const ClassLoader* class_loader) {
2969 Field* resolved = dex_cache->GetResolvedField(field_idx);
2970 if (resolved != NULL) {
2971 return resolved;
2972 }
2973 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2974 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2975 if (klass == NULL) {
2976 DCHECK(Thread::Current()->IsExceptionPending());
2977 return NULL;
2978 }
2979
2980 const char* name = dex_file.GetFieldName(field_id);
2981 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
2982 resolved = klass->FindField(name, type);
2983 if (resolved != NULL) {
2984 dex_cache->SetResolvedField(field_idx, resolved);
2985 } else {
2986 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002987 }
2988 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002989}
2990
Ian Rogersad25ac52011-10-04 19:13:33 -07002991const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2992 Class* declaring_class = referrer->GetDeclaringClass();
2993 DexCache* dex_cache = declaring_class->GetDexCache();
2994 const DexFile& dex_file = FindDexFile(dex_cache);
2995 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2996 return dex_file.GetShorty(method_id.proto_idx_);
2997}
2998
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002999void ClassLinker::DumpAllClasses(int flags) const {
3000 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3001 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3002 std::vector<Class*> all_classes;
3003 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003004 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003005 typedef Table::const_iterator It; // TODO: C++0x auto
3006 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3007 all_classes.push_back(it->second);
3008 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003009 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3010 all_classes.push_back(it->second);
3011 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003012 }
3013
3014 for (size_t i = 0; i < all_classes.size(); ++i) {
3015 all_classes[i]->DumpClass(std::cerr, flags);
3016 }
3017}
3018
Elliott Hughescac6cc72011-11-03 20:31:21 -07003019void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3020 MutexLock mu(classes_lock_);
3021 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3022 << classes_.size() << " allocated classes\n";
3023}
3024
Elliott Hughese27955c2011-08-26 15:21:24 -07003025size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003026 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003027 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003028}
3029
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003030pid_t ClassLinker::GetClassesLockOwner() {
3031 return classes_lock_.GetOwner();
3032}
3033
3034pid_t ClassLinker::GetDexLockOwner() {
3035 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003036}
3037
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003038void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3039 DCHECK(!init_done_);
3040
3041 DCHECK(klass != NULL);
3042 DCHECK(klass->GetClassLoader() == NULL);
3043
3044 DCHECK(class_roots_ != NULL);
3045 DCHECK(class_roots_->Get(class_root) == NULL);
3046 class_roots_->Set(class_root, klass);
3047}
3048
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003049} // namespace art