blob: 1355cbf382efad21ac09ff808dde88f60c92b21c [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=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800592 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800593 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 Carlstrom866c8622012-01-06 16:35:13 -0800632void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
633 MutexLock mu(dex_lock_);
634 RegisterOatFileLocked(oat_file);
635}
636
637void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
638 dex_lock_.AssertHeld();
639 oat_files_.push_back(&oat_file);
640}
641
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700642OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700643 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700644 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800645 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700646 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800647 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
648 // check the down cast
649 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700650 std::string oat_filename;
651 oat_filename += runtime->GetHostPrefix();
652 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700653 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700655 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700656 return NULL;
657 }
658 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
659 uint32_t image_oat_checksum = image_header.GetOatChecksum();
660 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800661 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700662 << " to expected oat checksum " << std::hex << oat_checksum
663 << " in image";
664 return NULL;
665 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800666 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800667 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700668 return oat_file;
669}
670
Brian Carlstromae826982011-11-09 01:33:42 -0800671const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
672 for (size_t i = 0; i < oat_files_.size(); i++) {
673 const OatFile* oat_file = oat_files_[i];
674 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800675 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800676 return oat_file;
677 }
678 }
679 return NULL;
680}
681
Brian Carlstromd601af82012-01-06 10:15:19 -0800682class LockedFd {
683 public:
684 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
685 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
686 if (fd == -1) {
687 PLOG(ERROR) << "Failed to open file '" << name << "'";
688 return NULL;
689 }
690 fchmod(fd, mode);
691
692 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
693 // try to lock non-blocking so we can log if we need may need to block
694 int result = flock(fd, LOCK_EX | LOCK_NB);
695 if (result == -1) {
696 LOG(WARNING) << "sleeping while locking file " << name;
697 // retry blocking
698 result = flock(fd, LOCK_EX);
699 }
700 if (result == -1) {
701 PLOG(ERROR) << "Failed to lock file '" << name << "'";
702 close(fd);
703 return NULL;
704 }
705 return new LockedFd(fd);
706 }
707
708 int GetFd() const {
709 return fd_;
710 }
711
712 ~LockedFd() {
713 if (fd_ != -1) {
714 int result = flock(fd_, LOCK_UN);
715 if (result == -1) {
716 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
717 }
718 close(fd_);
719 }
720 }
721
722 private:
723 explicit LockedFd(int fd) : fd_(fd) {}
724
725 int fd_;
726};
727
Brian Carlstromae826982011-11-09 01:33:42 -0800728const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700729 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800730 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
731 if (open_oat_file != NULL) {
732 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800733 }
734
Brian Carlstromd601af82012-01-06 10:15:19 -0800735 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800736 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
737 if (open_oat_file != NULL) {
738 return open_oat_file;
739 }
740
Brian Carlstromd601af82012-01-06 10:15:19 -0800741 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800742 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
743 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800744 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
745 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800746 RegisterOatFileLocked(*oat_file.get());
747 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800748 }
749 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
750 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
751 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
752 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
753 }
754 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700755 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800756 // Try to generate oat file if it wasn't found or was obsolete.
757 // Note we can be racing with another runtime to do this.
758 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
759 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
760 if (locked_fd.get() == NULL) {
761 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
762 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700763 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800764 // Check to see if the fd we opened and locked matches the file in
765 // the filesystem. If they don't, then somebody else unlinked ours
766 // and created a new file, and we need to use that one instead. (If
767 // we caught them between the unlink and the create, we'll get an
768 // ENOENT from the file stat.)
769 struct stat fd_stat;
770 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
771 if (fd_stat_result != 0) {
772 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
773 return NULL;
774 }
775 struct stat file_stat;
776 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
777 if (file_stat_result != 0
778 || fd_stat.st_dev != file_stat.st_dev
779 || fd_stat.st_ino != file_stat.st_ino) {
780 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
781 usleep(250 * 1000); // if something is hosed, don't peg machine
782 continue;
783 }
784
785 // We have the correct file open and locked. If the file size is
786 // zero, then it was just created by us and we can generate its
787 // contents. If not, someone else created it. Either way, we'll
788 // loop to retry opening the file.
789 if (fd_stat.st_size == 0) {
790 bool success = GenerateOatFile(dex_file.GetLocation(),
791 locked_fd->GetFd(),
792 oat_cache_filename);
793 if (!success) {
794 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
795 return NULL;
796 }
797 }
jeffhao262bf462011-10-20 18:36:32 -0700798 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800799 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700800}
801
Brian Carlstromae826982011-11-09 01:33:42 -0800802const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700803 for (size_t i = 0; i < oat_files_.size(); i++) {
804 const OatFile* oat_file = oat_files_[i];
805 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800806 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700807 return oat_file;
808 }
809 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700810 return NULL;
811}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700812
Brian Carlstromae826982011-11-09 01:33:42 -0800813const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800814 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700815 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800816 if (oat_location.empty() || oat_location[0] != '/') {
817 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700818 return NULL;
819 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700820
Brian Carlstroma9f19782011-10-13 00:14:47 -0700821 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800822 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800823 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700824 if (oat_file != NULL) {
825 return oat_file;
826 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700827 oat_file = OatFile::Open(cache_location, "", NULL);
828 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800829 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700830 return NULL;
831 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700832 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700833
Brian Carlstromae826982011-11-09 01:33:42 -0800834 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700835 return oat_file;
836}
837
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700838void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800839 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700840 CHECK(!init_done_);
841
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700842 const std::vector<Space*>& spaces = Heap::GetSpaces();
843 for (size_t i = 0; i < spaces.size(); i++) {
844 Space* space = spaces[i] ;
845 if (space->IsImageSpace()) {
846 OatFile* oat_file = OpenOat(space);
847 CHECK(oat_file != NULL) << "Failed to open oat file for image";
848 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
849 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
850
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800851 if (i == 0) {
852 // Special case of setting up the String class early so that we can test arbitrary objects
853 // as being Strings or not
854 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
855 ->AsObjectArray<Class>()->Get(kJavaLangString);
856 String::SetClass(java_lang_String);
857 }
858
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700859 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
860 static_cast<uint32_t>(dex_caches->GetLength()));
861 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700862 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800863 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800864 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
865 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700866 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800867 LOG(FATAL) << "Failed to open dex file " << dex_file_location
868 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700869 }
870
Brian Carlstromaded5f72011-10-07 17:15:04 -0700871 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700872
Brian Carlstromdf143242011-10-10 18:05:34 -0700873 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700874 }
875 }
876 }
877
Brian Carlstroma663ea52011-08-19 23:33:41 -0700878 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
879 DCHECK(heap_bitmap != NULL);
880
Brian Carlstroma663ea52011-08-19 23:33:41 -0700881 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700882 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700883
884 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700885 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
886 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700887
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800888 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700889 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
890 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800891 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700892 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700893 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700894 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
895 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
896 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
897 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
898 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
899 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
900 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
901 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700902 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700903 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700904
905 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700906
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800907 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700908}
909
Brian Carlstrom78128a62011-09-15 17:21:19 -0700910void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700911 DCHECK(obj != NULL);
912 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700913 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700914
Elliott Hughesdbb40792011-11-18 17:05:22 -0800915 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700916 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700917 return;
918 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700919 if (obj->IsClass()) {
920 // restore class to ClassLinker::classes_ table
921 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800922 ClassHelper kh(klass, class_linker);
923 bool success = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
Ian Rogers5d76c432011-10-31 21:42:49 -0700924 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700925 return;
926 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700927}
928
929// Keep in sync with InitCallback. Anything we visit, we need to
930// reinit references to when reinitializing a ClassLinker from a
931// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700932void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
933 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700934
935 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700936 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700937 }
938
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700939 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700940 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700941 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700942 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700943 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700944 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700945 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700946 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700947
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700948 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700949}
950
Elliott Hughesa2155262011-11-16 16:26:58 -0800951void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
952 MutexLock mu(classes_lock_);
953 typedef Table::const_iterator It; // TODO: C++0x auto
954 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
955 if (!visitor(it->second, arg)) {
956 return;
957 }
958 }
959 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
960 if (!visitor(it->second, arg)) {
961 return;
962 }
963 }
964}
965
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700966ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700967 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700968 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700969 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700970 BooleanArray::ResetArrayClass();
971 ByteArray::ResetArrayClass();
972 CharArray::ResetArrayClass();
973 DoubleArray::ResetArrayClass();
974 FloatArray::ResetArrayClass();
975 IntArray::ResetArrayClass();
976 LongArray::ResetArrayClass();
977 ShortArray::ResetArrayClass();
978 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700979 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700980 STLDeleteElements(&boot_class_path_);
981 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700982}
983
984DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700985 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
986 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700987 return NULL;
988 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700989 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
990 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700991 return NULL;
992 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700993 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
994 if (strings.get() == NULL) {
995 return NULL;
996 }
997 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
998 if (types.get() == NULL) {
999 return NULL;
1000 }
1001 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1002 if (methods.get() == NULL) {
1003 return NULL;
1004 }
1005 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1006 if (fields.get() == NULL) {
1007 return NULL;
1008 }
1009 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1010 if (code_and_direct_methods.get() == NULL) {
1011 return NULL;
1012 }
1013 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1014 if (initialized_static_storage.get() == NULL) {
1015 return NULL;
1016 }
1017
1018 dex_cache->Init(location.get(),
1019 strings.get(),
1020 types.get(),
1021 methods.get(),
1022 fields.get(),
1023 code_and_direct_methods.get(),
1024 initialized_static_storage.get());
1025 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001026}
1027
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001028CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1029 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001030}
1031
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001032InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1033 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001034 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1035 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001036 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001037 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001038}
1039
Brian Carlstrom4873d462011-08-21 15:23:39 -07001040Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1041 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001042 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001043 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001044 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001045 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001046}
1047
Brian Carlstrom4873d462011-08-21 15:23:39 -07001048Class* ClassLinker::AllocClass(size_t class_size) {
1049 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001050}
1051
Jesse Wilson35baaab2011-08-10 16:18:03 -04001052Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001053 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001054}
1055
1056Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001057 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001058}
1059
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001060ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1061 return ObjectArray<StackTraceElement>::Alloc(
1062 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1063 length);
1064}
1065
Brian Carlstromaded5f72011-10-07 17:15:04 -07001066Class* EnsureResolved(Class* klass) {
1067 DCHECK(klass != NULL);
1068 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001069 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001070 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001071 ObjectLock lock(klass);
1072 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001073 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001074 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001075 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001076 return NULL;
1077 }
1078 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001079 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001080 lock.Wait();
1081 }
1082 }
1083 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001084 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001085 return NULL;
1086 }
1087 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001088 CHECK(klass->IsResolved()) << PrettyClass(klass);
1089 CHECK(!self->IsExceptionPending())
1090 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1091 return klass;
1092}
1093
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001094Class* ClassLinker::FindSystemClass(const char* descriptor) {
1095 return FindClass(descriptor, NULL);
1096}
1097
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001098Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
1099 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001100 Thread* self = Thread::Current();
1101 DCHECK(self != NULL);
1102 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001103 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001104 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1105 // for primitive classes that aren't backed by dex files.
1106 return FindPrimitiveClass(descriptor[0]);
1107 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001108 // Find the class in the loaded classes table.
1109 Class* klass = LookupClass(descriptor, class_loader);
1110 if (klass != NULL) {
1111 return EnsureResolved(klass);
1112 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001113 // Class is not yet loaded.
1114 if (descriptor[0] == '[') {
1115 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001116
Jesse Wilson47daf872011-11-23 11:42:45 -05001117 } else if (class_loader == NULL) {
1118 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1119 if (pair.second != NULL) {
1120 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1121 }
1122
1123 } else if (ClassLoader::UseCompileTimeClassPath()) {
1124 // first try the boot class path
1125 Class* system_class = FindSystemClass(descriptor);
1126 if (system_class != NULL) {
1127 return system_class;
1128 }
1129 CHECK(self->IsExceptionPending());
1130 self->ClearException();
1131
1132 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001133 const std::vector<const DexFile*>& class_path
1134 = ClassLoader::GetCompileTimeClassPath(class_loader);
1135 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001136 if (pair.second != NULL) {
1137 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001138 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001139
1140 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001141 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001142 ScopedThreadStateChange(self, Thread::kNative);
1143 JNIEnv* env = self->GetJniEnv();
1144 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1145 CHECK(c.get() != NULL);
1146 // TODO: cache method?
1147 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1148 CHECK(mid != NULL);
1149 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1150 if (class_name_object.get() == NULL) {
1151 return NULL;
1152 }
1153 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1154 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
Ian Rogers6b0870d2011-12-15 19:38:12 -08001155 if (!env->ExceptionOccurred()) {
1156 return Decode<Class*>(env, result.get());
1157 } else {
1158 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1159 // TODO: initialize the cause of the NCDFE to this exception
1160 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001161 }
1162
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001163 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001164 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001165}
1166
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001167Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001168 const ClassLoader* class_loader,
1169 const DexFile& dex_file,
1170 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001171 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001172 // Load the class from the dex file.
1173 if (!init_done_) {
1174 // finish up init of hand crafted class_roots_
1175 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001176 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001177 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001178 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001179 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001180 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001181 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001182 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001183 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001184 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001185 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001186 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001188 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001189 }
1190 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 }
1193 klass->SetDexCache(FindDexCache(dex_file));
1194 LoadClass(dex_file, dex_class_def, klass, class_loader);
1195 // Check for a pending exception during load
1196 Thread* self = Thread::Current();
1197 if (self->IsExceptionPending()) {
1198 return NULL;
1199 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001200 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001201 klass->SetClinitThreadId(self->GetTid());
1202 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001203 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001204 if (!success) {
1205 // We may fail to insert if we raced with another thread.
1206 klass->SetClinitThreadId(0);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001207 klass.reset(LookupClass(descriptor.data(), class_loader));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001208 CHECK(klass.get() != NULL);
1209 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001210 }
1211 // Finish loading (if necessary) by finding parents
1212 CHECK(!klass->IsLoaded());
1213 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1214 // Loading failed.
1215 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001216 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001217 lock.NotifyAll();
1218 return NULL;
1219 }
1220 CHECK(klass->IsLoaded());
1221 // Link the class (if necessary)
1222 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001223 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001224 // Linking failed.
1225 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001226 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001227 lock.NotifyAll();
1228 return NULL;
1229 }
1230 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001231
1232 /*
1233 * We send CLASS_PREPARE events to the debugger from here. The
1234 * definition of "preparation" is creating the static fields for a
1235 * class and initializing them to the standard default values, but not
1236 * executing any code (that comes later, during "initialization").
1237 *
1238 * We did the static preparation in LinkClass.
1239 *
1240 * The class has been prepared and resolved but possibly not yet verified
1241 * at this point.
1242 */
1243 Dbg::PostClassPrepare(klass.get());
1244
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001245 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001246}
1247
Brian Carlstrom4873d462011-08-21 15:23:39 -07001248// Precomputes size that will be needed for Class, matching LinkStaticFields
1249size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1250 const DexFile::ClassDef& dex_class_def) {
1251 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001252 size_t num_ref = 0;
1253 size_t num_32 = 0;
1254 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001255 if (class_data != NULL) {
1256 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1257 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001258 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001259 char c = descriptor[0];
1260 if (c == 'L' || c == '[') {
1261 num_ref++;
1262 } else if (c == 'J' || c == 'D') {
1263 num_64++;
1264 } else {
1265 num_32++;
1266 }
1267 }
1268 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001269 // start with generic class data
1270 size_t size = sizeof(Class);
1271 // follow with reference fields which must be contiguous at start
1272 size += (num_ref * sizeof(uint32_t));
1273 // if there are 64-bit fields to add, make sure they are aligned
1274 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1275 if (num_32 != 0) {
1276 // use an available 32-bit field for padding
1277 num_32--;
1278 }
1279 size += sizeof(uint32_t); // either way, we are adding a word
1280 DCHECK_EQ(size, RoundUp(size, 8));
1281 }
1282 // tack on any 64-bit fields now that alignment is assured
1283 size += (num_64 * sizeof(uint64_t));
1284 // tack on any remaining 32-bit fields
1285 size += (num_32 * sizeof(uint32_t));
1286 return size;
1287}
1288
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001289void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001290 // Every kind of method should at least get an invoke stub from the oat_method.
1291 // non-abstract methods also get their code pointers.
1292 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001293 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001294
1295 if (method->IsAbstract()) {
1296 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1297 return;
1298 }
1299 if (method->IsNative()) {
1300 // unregistering restores the dlsym lookup stub
1301 method->UnregisterNative();
1302 return;
1303 }
1304}
1305
Brian Carlstromf615a612011-07-23 12:50:34 -07001306void ClassLinker::LoadClass(const DexFile& dex_file,
1307 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001308 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001309 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001310 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001311 CHECK(klass->GetDexCache() != NULL);
1312 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001313 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001314 CHECK(descriptor != NULL);
1315
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001316 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001317 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001318 // Make sure that none of our runtime-only flags are set.
1319 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001320 klass->SetAccessFlags(access_flags);
1321 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001322 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001323 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001324
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001325 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001326
Ian Rogers0571d352011-11-03 19:51:38 -07001327 // Load fields fields.
1328 const byte* class_data = dex_file.GetClassData(dex_class_def);
1329 if (class_data == NULL) {
1330 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001331 }
Ian Rogers0571d352011-11-03 19:51:38 -07001332 ClassDataItemIterator it(dex_file, class_data);
1333 if (it.NumStaticFields() != 0) {
1334 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1335 }
1336 if (it.NumInstanceFields() != 0) {
1337 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1338 }
1339 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1340 SirtRef<Field> sfield(AllocField());
1341 klass->SetStaticField(i, sfield.get());
1342 LoadField(dex_file, it, klass, sfield);
1343 }
1344 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1345 SirtRef<Field> ifield(AllocField());
1346 klass->SetInstanceField(i, ifield.get());
1347 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001348 }
1349
Brian Carlstromaded5f72011-10-07 17:15:04 -07001350 UniquePtr<const OatFile::OatClass> oat_class;
1351 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001352 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001353 if (oat_file != NULL) {
1354 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1355 if (oat_dex_file != NULL) {
1356 uint32_t class_def_index;
1357 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1358 CHECK(found) << descriptor;
1359 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001360 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001361 }
1362 }
1363 }
Ian Rogers0571d352011-11-03 19:51:38 -07001364 // Load methods.
1365 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001366 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001367 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001368 }
Ian Rogers0571d352011-11-03 19:51:38 -07001369 if (it.NumVirtualMethods() != 0) {
1370 // TODO: append direct methods to class object
1371 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001372 }
Ian Rogers0571d352011-11-03 19:51:38 -07001373 size_t method_index = 0;
1374 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1375 SirtRef<Method> method(AllocMethod());
1376 klass->SetDirectMethod(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 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1384 SirtRef<Method> method(AllocMethod());
1385 klass->SetVirtualMethod(i, method.get());
1386 LoadMethod(dex_file, it, klass, method);
1387 if (oat_class.get() != NULL) {
1388 LinkCode(method, oat_class.get(), method_index);
1389 }
1390 method_index++;
1391 }
1392 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001393}
1394
Ian Rogers0571d352011-11-03 19:51:38 -07001395void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1396 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001397 uint32_t field_idx = it.GetMemberIndex();
1398 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001399 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001400 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001401}
1402
Ian Rogers0571d352011-11-03 19:51:38 -07001403void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1404 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001405 uint32_t method_idx = it.GetMemberIndex();
1406 dst->SetDexMethodIndex(method_idx);
1407 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001408 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001409
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001410
1411 StringPiece method_name(dex_file.GetMethodName(method_id));
1412 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001413 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1414 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001415
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001416 if (method_name == "finalize") {
1417 // Create the prototype for a signature of "()V"
1418 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1419 if (void_string_id != NULL) {
1420 const DexFile::TypeId* void_type_id =
1421 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1422 if (void_type_id != NULL) {
1423 std::vector<uint16_t> no_args;
1424 const DexFile::ProtoId* finalizer_proto =
1425 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1426 if (finalizer_proto != NULL) {
1427 // We have the prototype in the dex file
1428 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1429 klass->SetFinalizable();
1430 } else {
1431 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1432 // The Enum class declares a "final" finalize() method to prevent subclasses from
1433 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1434 // subclasses, so we exclude it here.
1435 // We also want to avoid setting the flag on Object, where we know that finalize() is
1436 // empty.
1437 if (klass_descriptor != "Ljava/lang/Object;" &&
1438 klass_descriptor != "Ljava/lang/Enum;") {
1439 klass->SetFinalizable();
1440 }
1441 }
1442 }
1443 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001444 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001445 }
Ian Rogers0571d352011-11-03 19:51:38 -07001446 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001447 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001448
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001449 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1450 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1451 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1452 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1453 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1454 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001455
Brian Carlstrom934486c2011-07-12 23:42:50 -07001456 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001457}
1458
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001459void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001460 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1461 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001462}
1463
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001464void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1465 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001466 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001467 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001468}
1469
Brian Carlstromaded5f72011-10-07 17:15:04 -07001470bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001471 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001472 for (size_t i = 0; i != dex_files_.size(); ++i) {
1473 if (dex_files_[i] == &dex_file) {
1474 return true;
1475 }
1476 }
1477 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001478}
1479
Brian Carlstromaded5f72011-10-07 17:15:04 -07001480bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001481 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001482 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001483}
1484
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001485void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001486 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001487 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001488 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001489 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001490 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001491}
1492
Brian Carlstromaded5f72011-10-07 17:15:04 -07001493void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001494 {
1495 MutexLock mu(dex_lock_);
1496 if (IsDexFileRegisteredLocked(dex_file)) {
1497 return;
1498 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001499 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001500 // Don't alloc while holding the lock, since allocation may need to
1501 // suspend all threads and another thread may need the dex_lock_ to
1502 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001503 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001504 {
1505 MutexLock mu(dex_lock_);
1506 if (IsDexFileRegisteredLocked(dex_file)) {
1507 return;
1508 }
1509 RegisterDexFileLocked(dex_file, dex_cache);
1510 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001511}
1512
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001513void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001514 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001515 RegisterDexFileLocked(dex_file, dex_cache);
1516}
1517
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001518const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001519 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001520 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001521 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1522 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001523 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001524 }
1525 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001526 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001527 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001528}
1529
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001530DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001531 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001532 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001533 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001534 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001535 }
1536 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001537 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001538 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001539}
1540
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001541Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1542 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001543 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001544 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001545 CHECK(primitive_class != NULL);
1546 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001547 primitive_class->SetPrimitiveType(type);
1548 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001549 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001550 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1551 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001552}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001553
Brian Carlstrombe977852011-07-19 14:54:54 -07001554// Create an array class (i.e. the class object for the array, not the
1555// array itself). "descriptor" looks like "[C" or "[[[[B" or
1556// "[Ljava/lang/String;".
1557//
1558// If "descriptor" refers to an array of primitives, look up the
1559// primitive type's internally-generated class object.
1560//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001561// "class_loader" is the class loader of the class that's referring to
1562// us. It's used to ensure that we're looking for the element type in
1563// the right context. It does NOT become the class loader for the
1564// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001565//
1566// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001567Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001568 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001569
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001570 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001571 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001572 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001573 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001574 return NULL;
1575 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001576
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001577 // See if the component type is already loaded. Array classes are
1578 // always associated with the class loader of their underlying
1579 // element type -- an array of Strings goes with the loader for
1580 // java/lang/String -- so we need to look for it there. (The
1581 // caller should have checked for the existence of the class
1582 // before calling here, but they did so with *their* class loader,
1583 // not the component type's loader.)
1584 //
1585 // If we find it, the caller adds "loader" to the class' initiating
1586 // loader list, which should prevent us from going through this again.
1587 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001588 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001589 // are the same, because our caller (FindClass) just did the
1590 // lookup. (Even if we get this wrong we still have correct behavior,
1591 // because we effectively do this lookup again when we add the new
1592 // class to the hash table --- necessary because of possible races with
1593 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001594 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001595 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001596 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001597 return new_class;
1598 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001599 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001600
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001601 // Fill out the fields in the Class.
1602 //
1603 // It is possible to execute some methods against arrays, because
1604 // all arrays are subclasses of java_lang_Object_, so we need to set
1605 // up a vtable. We can just point at the one in java_lang_Object_.
1606 //
1607 // Array classes are simple enough that we don't need to do a full
1608 // link step.
1609
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001610 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001611 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001612 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001613 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001614 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001615 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001616 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001617 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001618 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001619 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001620 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001621 }
1622 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001623 if (new_class.get() == NULL) {
1624 new_class.reset(AllocClass(sizeof(Class)));
1625 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001626 return NULL;
1627 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001628 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001629 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001630 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001631 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001632 new_class->SetSuperClass(java_lang_Object);
1633 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001634 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001635 new_class->SetClassLoader(component_type->GetClassLoader());
1636 new_class->SetStatus(Class::kStatusInitialized);
1637 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001638 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001639
1640
1641 // All arrays have java/lang/Cloneable and java/io/Serializable as
1642 // interfaces. We need to set that up here, so that stuff like
1643 // "instanceof" works right.
1644 //
1645 // Note: The GC could run during the call to FindSystemClass,
1646 // so we need to make sure the class object is GC-valid while we're in
1647 // there. Do this by clearing the interface list so the GC will just
1648 // think that the entries are null.
1649
1650
1651 // Use the single, global copies of "interfaces" and "iftable"
1652 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001653 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001654 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001655
1656 // Inherit access flags from the component type. Arrays can't be
1657 // used as a superclass or interface, so we want to add "final"
1658 // and remove "interface".
1659 //
1660 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001661 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001662 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001663 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1664 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001665
Ian Rogers5d76c432011-10-31 21:42:49 -07001666 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001667 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001668 }
1669 // Another thread must have loaded the class after we
1670 // started but before we finished. Abandon what we've
1671 // done.
1672 //
1673 // (Yes, this happens.)
1674
1675 // Grab the winning class.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001676 Class* other_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001677 DCHECK(other_class != NULL);
1678 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001679}
1680
1681Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001682 switch (Primitive::GetType(type)) {
1683 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001684 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001685 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001686 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001687 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001688 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001689 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001690 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001691 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001692 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001693 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001694 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001695 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001696 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001697 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001698 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001699 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001700 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001701 case Primitive::kPrimNot:
1702 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001703 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001704 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001705 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001706 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001707}
1708
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001709bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001710 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001711 DexCache* dex_cache = klass->GetDexCache();
1712 std::string source;
1713 if (dex_cache != NULL) {
1714 source += " from ";
1715 source += dex_cache->GetLocation()->ToModifiedUtf8();
1716 }
1717 LOG(INFO) << "Loaded class " << descriptor << source;
1718 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001719 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001720 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001721 Table::iterator it;
1722 if (image_class) {
1723 // TODO: sanity check there's no match in classes_
1724 it = image_classes_.insert(std::make_pair(hash, klass));
1725 } else {
1726 // TODO: sanity check there's no match in image_classes_
1727 it = classes_.insert(std::make_pair(hash, klass));
1728 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001729 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001730}
1731
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001732bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1733 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001734 MutexLock mu(classes_lock_);
1735 typedef Table::const_iterator It; // TODO: C++0x auto
1736 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001737 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001738 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1739 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001740 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001741 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001742 classes_.erase(it);
1743 return true;
1744 }
1745 }
1746 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1747 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001748 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001749 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001750 image_classes_.erase(it);
1751 return true;
1752 }
1753 }
1754 return false;
1755}
1756
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001757Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1758 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001759 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001760 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001761 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001762 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001763 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001764 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001765 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001766 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001767 return klass;
1768 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001770 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1771 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001772 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001773 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001774 return klass;
1775 }
1776 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001777 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001778}
1779
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001780void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001781 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001782 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001783 MutexLock mu(classes_lock_);
1784 typedef Table::const_iterator It; // TODO: C++0x auto
1785 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001786 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001787 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001788 Class* klass = it->second;
1789 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001790 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001791 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001792 }
1793 }
1794 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001795 Class* klass = it->second;
1796 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001797 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001798 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001799 }
1800 }
1801}
1802
jeffhao98eacac2011-09-14 16:11:53 -07001803void ClassLinker::VerifyClass(Class* klass) {
1804 if (klass->IsVerified()) {
1805 return;
1806 }
1807
1808 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001809 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001810
Ian Rogersd81871c2011-10-03 13:57:23 -07001811 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001812 klass->SetStatus(Class::kStatusVerified);
1813 } else {
1814 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001815 Thread* self = Thread::Current();
1816 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1817 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001818 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001819 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001820 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001821 }
jeffhao98eacac2011-09-14 16:11:53 -07001822}
1823
Ian Rogersc2b44472011-12-14 21:17:17 -08001824static void CheckProxyConstructor(Method* constructor);
1825static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1826
Jesse Wilson95caa792011-10-12 18:14:17 -04001827Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001828 ClassLoader* loader, ObjectArray<Method>* methods,
1829 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001830 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001831 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001832 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001833 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001834 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001835 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001836 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001837 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001838 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001839 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001840
1841 klass->SetStatus(Class::kStatusIdx);
1842
1843 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1844
1845 // Create static field that holds throws, instance fields are inherited
1846 klass->SetSFields(AllocObjectArray<Field>(1));
1847 SirtRef<Field> sfield(AllocField());
1848 klass->SetStaticField(0, sfield.get());
1849 sfield->SetDexFieldIndex(-1);
1850 sfield->SetDeclaringClass(klass.get());
1851 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001852
Ian Rogers466bb252011-10-14 03:29:56 -07001853 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001854 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001855 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001856
Ian Rogers466bb252011-10-14 03:29:56 -07001857 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001858 size_t num_virtual_methods = methods->GetLength();
1859 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1860 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001861 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001862 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001863 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001864
1865 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1866 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1867 DCHECK(!Thread::Current()->IsExceptionPending());
1868
1869 // Link the fields and virtual methods, creating vtable and iftables
1870 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001871 DCHECK(Thread::Current()->IsExceptionPending());
1872 return NULL;
1873 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001874 sfield->SetObject(NULL, throws); // initialize throws field
1875 klass->SetStatus(Class::kStatusInitialized);
1876
1877 // sanity checks
1878#ifndef NDEBUG
1879 bool debug = true;
1880#else
1881 bool debug = false;
1882#endif
1883 if (debug) {
1884 CHECK(klass->GetIFields() == NULL);
1885 CheckProxyConstructor(klass->GetDirectMethod(0));
1886 for (size_t i = 0; i < num_virtual_methods; ++i) {
1887 SirtRef<Method> prototype(methods->Get(i));
1888 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1889 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001890 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08001891 throws_field_name += name->ToModifiedUtf8();
1892 throws_field_name += ".throws";
1893 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1894
1895 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1896 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1897 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001898 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001899}
1900
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001901std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1902 DCHECK(proxy_class->IsProxyClass());
1903 String* name = proxy_class->GetName();
1904 DCHECK(name != NULL);
1905 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1906}
1907
1908
1909Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001910 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001911 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001912 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001913 Method* proxy_constructor = proxy_direct_methods->Get(2);
1914 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1915 // code_ too)
1916 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1917 // Make this constructor public and fix the class to be our Proxy version
1918 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001919 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001920 return constructor;
1921}
1922
1923static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001924 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001925 MethodHelper mh(constructor);
1926 CHECK_STREQ(mh.GetName(), "<init>");
1927 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001928 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001929}
1930
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001931Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1932 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1933 // prototype method
1934 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1935 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001936 // as necessary
1937 Method* method = down_cast<Method*>(prototype->Clone());
1938
1939 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1940 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001941 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001942 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001943
Ian Rogers466bb252011-10-14 03:29:56 -07001944 // At runtime the method looks like a reference and argument saving method, clone the code
1945 // related parameters from this method.
1946 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1947 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1948 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1949 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1950 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001951 return method;
1952}
Jesse Wilson95caa792011-10-12 18:14:17 -04001953
Ian Rogersc2b44472011-12-14 21:17:17 -08001954static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001955 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001956 CHECK(!prototype->IsFinal());
1957 CHECK(method->IsFinal());
1958 CHECK(!method->IsAbstract());
1959 MethodHelper mh(method);
1960 const char* method_name = mh.GetName();
1961 const char* method_shorty = mh.GetShorty();
1962 Class* method_return = mh.GetReturnType();
1963
1964 mh.ChangeMethod(prototype.get());
1965
1966 CHECK_STREQ(mh.GetName(), method_name);
1967 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001968
1969 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001970 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001971}
1972
Brian Carlstrom25c33252011-09-18 15:58:35 -07001973bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001974 CHECK(klass->IsResolved() || klass->IsErroneous())
1975 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001976
Carl Shapirob5573532011-07-12 18:22:59 -07001977 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001978
Brian Carlstrom25c33252011-09-18 15:58:35 -07001979 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001980 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001981 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001982 ObjectLock lock(klass);
1983
Brian Carlstromd1422f82011-09-28 11:37:09 -07001984 if (klass->GetStatus() == Class::kStatusInitialized) {
1985 return true;
1986 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001987
Brian Carlstromd1422f82011-09-28 11:37:09 -07001988 if (klass->IsErroneous()) {
1989 ThrowEarlierClassFailure(klass);
1990 return false;
1991 }
1992
1993 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001994 VerifyClass(klass);
1995 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001996 return false;
1997 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001998 }
1999
Brian Carlstrom25c33252011-09-18 15:58:35 -07002000 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2001 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002002 // if the class has a <clinit> but we can't run it during compilation,
2003 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07002004 return false;
2005 }
2006
Brian Carlstromd1422f82011-09-28 11:37:09 -07002007 // If the class is kStatusInitializing, either this thread is
2008 // initializing higher up the stack or another thread has beat us
2009 // to initializing and we need to wait. Either way, this
2010 // invocation of InitializeClass will not be responsible for
2011 // running <clinit> and will return.
2012 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002013 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002014 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002015 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002016 return true;
2017 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002018 // No. That's fine. Wait for another thread to finish initializing.
2019 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002020 }
2021
2022 if (!ValidateSuperClassDescriptors(klass)) {
2023 klass->SetStatus(Class::kStatusError);
2024 return false;
2025 }
2026
Brian Carlstromd1422f82011-09-28 11:37:09 -07002027 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002028
Elliott Hughesdcc24742011-09-07 14:02:44 -07002029 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002030 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002031 }
2032
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002033 uint64_t t0 = NanoTime();
2034
Brian Carlstrom25c33252011-09-18 15:58:35 -07002035 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002036 return false;
2037 }
2038
2039 InitializeStaticFields(klass);
2040
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002042 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002043 }
2044
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002045 uint64_t t1 = NanoTime();
2046
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002047 {
2048 ObjectLock lock(klass);
2049
2050 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002051 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002052 klass->SetStatus(Class::kStatusError);
2053 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002054 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2055 RuntimeStats* thread_stats = self->GetStats();
2056 ++global_stats->class_init_count;
2057 ++thread_stats->class_init_count;
2058 global_stats->class_init_time_ns += (t1 - t0);
2059 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002060 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002061 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002062 ClassHelper kh(klass);
2063 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002064 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002065 }
2066 lock.NotifyAll();
2067 }
2068
2069 return true;
2070}
2071
Brian Carlstromd1422f82011-09-28 11:37:09 -07002072bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2073 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002074 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002075 lock.Wait();
2076
2077 // When we wake up, repeat the test for init-in-progress. If
2078 // there's an exception pending (only possible if
2079 // "interruptShouldThrow" was set), bail out.
2080 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002081 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002082 klass->SetStatus(Class::kStatusError);
2083 return false;
2084 }
2085 // Spurious wakeup? Go back to waiting.
2086 if (klass->GetStatus() == Class::kStatusInitializing) {
2087 continue;
2088 }
2089 if (klass->IsErroneous()) {
2090 // The caller wants an exception, but it was thrown in a
2091 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002092 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002093 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002094 return false;
2095 }
2096 if (klass->IsInitialized()) {
2097 return true;
2098 }
2099 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2100 }
2101 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2102}
2103
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002104bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2105 if (klass->IsInterface()) {
2106 return true;
2107 }
2108 // begin with the methods local to the superclass
2109 if (klass->HasSuperClass() &&
2110 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2111 const Class* super = klass->GetSuperClass();
2112 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002113 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002114 if (method != super->GetVirtualMethod(i) &&
2115 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002116 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2117
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002118 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2119 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2120 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002121 return false;
2122 }
2123 }
2124 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002125 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2126 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2127 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002128 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2129 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002130 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002131 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002132 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002133 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2134
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002135 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2136 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2137 PrettyMethod(method).c_str(),
2138 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002139 return false;
2140 }
2141 }
2142 }
2143 }
2144 return true;
2145}
2146
2147bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002148 const Class* klass1,
2149 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002150 if (klass1 == klass2) {
2151 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002152 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002153 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002154 const DexFile::ProtoId& proto_id =
2155 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002156 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2157 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002158 if (descriptor == NULL) {
2159 break;
2160 }
2161 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2162 // Found a non-primitive type.
2163 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2164 return false;
2165 }
2166 }
2167 }
2168 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002169 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002170 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002171 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002172 return false;
2173 }
2174 }
2175 return true;
2176}
2177
2178// Returns true if classes referenced by the descriptor are the
2179// same classes in klass1 as they are in klass2.
2180bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002181 const Class* klass1,
2182 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002183 CHECK(descriptor != NULL);
2184 CHECK(klass1 != NULL);
2185 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002186 if (klass1 == klass2) {
2187 return true;
2188 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002189 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002190 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002191 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002192 // TODO: found2 == NULL
2193 // TODO: lookup found1 in initiating loader list
2194 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002195 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002196 return found1 == found2;
2197 } else {
2198 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002199 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002200}
2201
Brian Carlstrom25c33252011-09-18 15:58:35 -07002202bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002203 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002204 if (!klass->IsInterface() && klass->HasSuperClass()) {
2205 Class* super_class = klass->GetSuperClass();
2206 if (super_class->GetStatus() != Class::kStatusInitialized) {
2207 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002208 Thread* self = Thread::Current();
2209 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002210 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002211 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002212 // TODO: check for a pending exception
2213 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002214 if (!can_run_clinit) {
2215 // Don't set status to error when we can't run <clinit>.
2216 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2217 klass->SetStatus(Class::kStatusVerified);
2218 return false;
2219 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002220 klass->SetStatus(Class::kStatusError);
2221 klass->NotifyAll();
2222 return false;
2223 }
2224 }
2225 }
2226 return true;
2227}
2228
Brian Carlstrom25c33252011-09-18 15:58:35 -07002229bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002230 CHECK(c != NULL);
2231 if (c->IsInitialized()) {
2232 return true;
2233 }
2234
Elliott Hughes5f791332011-09-15 17:45:30 -07002235 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002236 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002237 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002238 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002239}
2240
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002241void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002242 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002243 const ClassLoader* cl = c->GetClassLoader();
2244 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002245 ClassDataItemIterator it(dex_file, class_data);
2246 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2247 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002248 }
2249}
2250
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002251void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002252 size_t num_static_fields = klass->NumStaticFields();
2253 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002254 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002255 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002256 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002257 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002258 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002259 return;
2260 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002261 ClassHelper kh(klass);
2262 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002263 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002264 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002265 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002266
Ian Rogers0571d352011-11-03 19:51:38 -07002267 if (it.HasNext()) {
2268 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2269 std::map<uint32_t, Field*> field_map;
2270 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2271 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2272 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002273 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002274 }
2275}
2276
Ian Rogersc2b44472011-12-14 21:17:17 -08002277bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002278 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002279 if (!LinkSuperClass(klass)) {
2280 return false;
2281 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002282 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002283 return false;
2284 }
2285 if (!LinkInstanceFields(klass)) {
2286 return false;
2287 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002288 if (!LinkStaticFields(klass)) {
2289 return false;
2290 }
2291 CreateReferenceInstanceOffsets(klass);
2292 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002293 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2294 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002295 return true;
2296}
2297
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002298bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002299 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002300 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2301 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2302 if (class_def == NULL) {
2303 return false;
2304 }
2305 uint16_t super_class_idx = class_def->superclass_idx_;
2306 if (super_class_idx != DexFile::kDexNoIndex16) {
2307 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002308 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002309 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002310 return false;
2311 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002312 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002313 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002314 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2315 if (interfaces != NULL) {
2316 for (size_t i = 0; i < interfaces->Size(); i++) {
2317 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2318 Class* interface = ResolveType(dex_file, idx, klass.get());
2319 if (interface == NULL) {
2320 DCHECK(Thread::Current()->IsExceptionPending());
2321 return false;
2322 }
2323 // Verify
2324 if (!klass->CanAccess(interface)) {
2325 // TODO: the RI seemed to ignore this in my testing.
2326 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2327 "Interface %s implemented by class %s is inaccessible",
2328 PrettyDescriptor(interface).c_str(),
2329 PrettyDescriptor(klass.get()).c_str());
2330 return false;
2331 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002332 }
2333 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002334 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002335 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002336 return true;
2337}
2338
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002339bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002340 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002341 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002342 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002343 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002344 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002345 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002346 return false;
2347 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002348 return true;
2349 }
2350 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002351 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002352 return false;
2353 }
2354 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002355 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002356 Thread* thread = Thread::Current();
2357 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002358 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002359 PrettyDescriptor(super).c_str(),
2360 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002361 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002362 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002363 return false;
2364 }
2365 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002366 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002367 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002368 PrettyDescriptor(super).c_str(),
2369 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002370 return false;
2371 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002372
2373 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2374 if (super->IsFinalizable()) {
2375 klass->SetFinalizable();
2376 }
2377
Elliott Hughes2da50362011-10-10 16:57:08 -07002378 // Inherit reference flags (if any) from the superclass.
2379 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2380 if (reference_flags != 0) {
2381 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2382 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002383 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002384 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002385 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002386 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002387 return false;
2388 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002389
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002390#ifndef NDEBUG
2391 // Ensure super classes are fully resolved prior to resolving fields..
2392 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002393 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002394 super = super->GetSuperClass();
2395 }
2396#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002397 return true;
2398}
2399
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002400// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002401bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002402 if (klass->IsInterface()) {
2403 // No vtable.
2404 size_t count = klass->NumVirtualMethods();
2405 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002406 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002407 return false;
2408 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002409 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002410 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002411 }
jeffhaobdb76512011-09-07 11:43:16 -07002412 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002413 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002414 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002415 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002416 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002417 }
2418 return true;
2419}
2420
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002421bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002422 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002423 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2424 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002425 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002426 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002427 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002428 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002429 MethodHelper local_mh(NULL, this);
2430 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002431 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002432 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002433 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002434 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002435 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002436 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002437 super_mh.ChangeMethod(super_method);
2438 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002439 // Verify
2440 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002441 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002442 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002443 PrettyDescriptor(klass.get()).c_str(),
2444 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002445 return false;
2446 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002447 vtable->Set(j, local_method);
2448 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002449 break;
2450 }
2451 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002452 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002453 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002454 vtable->Set(actual_count, local_method);
2455 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002456 actual_count += 1;
2457 }
2458 }
2459 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002460 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002461 return false;
2462 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002463 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002464 CHECK_LE(actual_count, max_count);
2465 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002466 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002467 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002468 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002469 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002470 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002471 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002472 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002473 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002474 return false;
2475 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002476 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002477 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002478 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2479 vtable->Set(i, virtual_method);
2480 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002481 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002482 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002483 }
2484 return true;
2485}
2486
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002487bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002488 size_t super_ifcount;
2489 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002490 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002491 } else {
2492 super_ifcount = 0;
2493 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002494 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002495 ClassHelper kh(klass.get(), this);
2496 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2497 ifcount += num_interfaces;
2498 for (size_t i = 0; i < num_interfaces; i++) {
2499 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2500 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002501 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002502 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002503 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002504 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002505 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002506 return true;
2507 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002508 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002509 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002510 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2511 for (size_t i = 0; i < super_ifcount; i++) {
2512 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2513 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002514 }
2515 // Flatten the interface inheritance hierarchy.
2516 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002517 for (size_t i = 0; i < num_interfaces; i++) {
2518 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002519 DCHECK(interface != NULL);
2520 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002521 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002522 Thread* thread = Thread::Current();
2523 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002524 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002525 PrettyDescriptor(klass.get()).c_str(),
2526 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002527 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002528 return false;
2529 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002530 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002531 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002532 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002533 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2534 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002535 }
2536 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002537 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002538 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002539
2540 // If we're an interface, we don't need the vtable pointers, so we're done.
2541 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002542 return true;
2543 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002544 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002545 MethodHelper vtable_mh(NULL, this);
2546 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002547 for (size_t i = 0; i < ifcount; ++i) {
2548 InterfaceEntry* interface_entry = iftable->Get(i);
2549 Class* interface = interface_entry->GetInterface();
2550 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2551 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002552 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002553 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2554 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002555 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002556 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002557 // For each method listed in the interface's method list, find the
2558 // matching method in our class's method list. We want to favor the
2559 // subclass over the superclass, which just requires walking
2560 // back from the end of the vtable. (This only matters if the
2561 // superclass defines a private method and this class redefines
2562 // it -- otherwise it would use the same vtable slot. In .dex files
2563 // those don't end up in the virtual method table, so it shouldn't
2564 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002565 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2566 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002567 vtable_mh.ChangeMethod(vtable_method);
2568 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002569 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002570 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002571 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002572 return false;
2573 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002574 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002575 break;
2576 }
2577 }
2578 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002579 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002580 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002581 Method* mir_method = miranda_list[mir];
2582 vtable_mh.ChangeMethod(mir_method);
2583 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002584 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002585 break;
2586 }
2587 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002588 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002589 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002590 miranda_method.reset(AllocMethod());
2591 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2592 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002593 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002594 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595 }
2596 }
2597 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002598 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002599 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002600 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002601 klass->SetVirtualMethods((old_method_count == 0)
2602 ? AllocObjectArray<Method>(new_method_count)
2603 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002604
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002605 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2606 CHECK(vtable != NULL);
2607 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002608 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002609 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002610 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002611 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002612 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002613 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2614 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2615 klass->SetVirtualMethod(old_method_count + i, method);
2616 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002617 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002618 // TODO: do not assign to the vtable field until it is fully constructed.
2619 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002620 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002621
2622 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2623 for (int i = 0; i < vtable->GetLength(); ++i) {
2624 CHECK(vtable->Get(i) != NULL);
2625 }
2626
2627// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2628
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002629 return true;
2630}
2631
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002632bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2633 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002634 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002635}
2636
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002637bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2638 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002639 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002640 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002641 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002642 return success;
2643}
2644
Brian Carlstromdbc05252011-09-09 01:59:59 -07002645struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002646 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002647 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002648 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002649 fh_->ChangeField(field1);
2650 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2651 fh_->ChangeField(field2);
2652 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002653 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2654 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2655 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2656 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002657 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2658 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2659 if (order1 != order2) {
2660 return order1 < order2;
2661 }
2662
2663 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002664 fh_->ChangeField(field1);
2665 StringPiece name1(fh_->GetName());
2666 fh_->ChangeField(field2);
2667 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002668 return name1 < name2;
2669 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002670
2671 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002672};
2673
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002674bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002675 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002676 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002677
2678 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002679 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002680
2681 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002682 size_t size;
2683 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002684 if (is_static) {
2685 size = klass->GetClassSize();
2686 field_offset = Class::FieldsOffset();
2687 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002688 Class* super_class = klass->GetSuperClass();
2689 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002690 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002691 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002692 }
2693 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002694 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002695
Brian Carlstromdbc05252011-09-09 01:59:59 -07002696 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002697
Brian Carlstromdbc05252011-09-09 01:59:59 -07002698 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002699 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002700 std::deque<Field*> grouped_and_sorted_fields;
2701 for (size_t i = 0; i < num_fields; i++) {
2702 grouped_and_sorted_fields.push_back(fields->Get(i));
2703 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002704 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002705 std::sort(grouped_and_sorted_fields.begin(),
2706 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002707 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002708
2709 // References should be at the front.
2710 size_t current_field = 0;
2711 size_t num_reference_fields = 0;
2712 for (; current_field < num_fields; current_field++) {
2713 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002714 fh.ChangeField(field);
2715 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002716 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002717 if (isPrimitive) {
2718 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002719 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002720 grouped_and_sorted_fields.pop_front();
2721 num_reference_fields++;
2722 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002723 field->SetOffset(field_offset);
2724 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002725 }
2726
2727 // Now we want to pack all of the double-wide fields together. If
2728 // we're not aligned, though, we want to shuffle one 32-bit field
2729 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002730 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002731 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2732 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002733 fh.ChangeField(field);
2734 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002735 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2736 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002737 continue;
2738 }
2739 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002740 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002741 // drop the consumed field
2742 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2743 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002744 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002745 // whether we found a 32-bit field for padding or not, we advance
2746 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002747 }
2748
2749 // Alignment is good, shuffle any double-wide fields forward, and
2750 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002751 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002752 while (!grouped_and_sorted_fields.empty()) {
2753 Field* field = grouped_and_sorted_fields.front();
2754 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002755 fh.ChangeField(field);
2756 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002757 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002758 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002759 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002760 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002761 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002762 ? sizeof(uint64_t)
2763 : sizeof(uint32_t)));
2764 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002765 }
2766
Elliott Hughesadb460d2011-10-05 17:02:34 -07002767 // 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 -08002768 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2769 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002770 // We know there are no non-reference fields in the Reference classes, and we know
2771 // that 'referent' is alphabetically last, so this is easy...
2772 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002773 fh.ChangeField(fields->Get(num_fields - 1));
2774 StringPiece name(fh.GetName());
2775 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002776 --num_reference_fields;
2777 }
2778
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002779#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002780 // Make sure that all reference fields appear before
2781 // non-reference fields, and all double-wide fields are aligned.
2782 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002783 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002784 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002785 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002786 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002787 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002788 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002789 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2790 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002791 fh.ChangeField(field);
2792 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002793 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002794 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002795 is_primitive = true; // We lied above, so we have to expect a lie here.
2796 }
2797 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002798 if (!seen_non_ref) {
2799 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002800 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002801 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002802 } else {
2803 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002804 }
2805 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002806 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002807 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002808 }
2809#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002810 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002811 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002812 if (is_static) {
2813 klass->SetNumReferenceStaticFields(num_reference_fields);
2814 klass->SetClassSize(size);
2815 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002816 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002817 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002818 klass->SetObjectSize(size);
2819 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002820 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002821 return true;
2822}
2823
2824// Set the bitmap of reference offsets, refOffsets, from the ifields
2825// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002826void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002827 uint32_t reference_offsets = 0;
2828 Class* super_class = klass->GetSuperClass();
2829 if (super_class != NULL) {
2830 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002831 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002832 if (reference_offsets == CLASS_WALK_SUPER) {
2833 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002834 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002835 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002836 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002837 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002838}
2839
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002840void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002841 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002842}
2843
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002844void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002845 uint32_t reference_offsets) {
2846 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002847 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2848 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002849 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002850 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002851 // All of the fields that contain object references are guaranteed
2852 // to be at the beginning of the fields list.
2853 for (size_t i = 0; i < num_reference_fields; ++i) {
2854 // Note that byte_offset is the offset from the beginning of
2855 // object, not the offset into instance data
2856 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002857 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002858 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2859 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2860 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002861 CHECK_NE(new_bit, 0U);
2862 reference_offsets |= new_bit;
2863 } else {
2864 reference_offsets = CLASS_WALK_SUPER;
2865 break;
2866 }
2867 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002868 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002869 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002870 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002871 } else {
2872 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002873 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002874}
2875
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002876String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002877 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002878 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002879 if (resolved != NULL) {
2880 return resolved;
2881 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002882 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2883 int32_t utf16_length = dex_file.GetStringLength(string_id);
2884 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002885 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002886 dex_cache->SetResolvedString(string_idx, string);
2887 return string;
2888}
2889
2890Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002891 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002892 DexCache* dex_cache,
2893 const ClassLoader* class_loader) {
2894 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002895 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002896 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002897 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002898 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002899 // TODO: we used to throw here if resolved's class loader was not the
2900 // boot class loader. This was to permit different classes with the
2901 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002902 dex_cache->SetResolvedType(type_idx, resolved);
2903 } else {
2904 DCHECK(Thread::Current()->IsExceptionPending());
2905 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002906 }
2907 return resolved;
2908}
2909
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002910Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2911 uint32_t method_idx,
2912 DexCache* dex_cache,
2913 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002914 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002915 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2916 if (resolved != NULL) {
2917 return resolved;
2918 }
2919 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2920 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2921 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002922 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002923 return NULL;
2924 }
2925
Ian Rogers0571d352011-11-03 19:51:38 -07002926 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2927 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002928 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002929 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002930 } else if (klass->IsInterface()) {
2931 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002932 } else {
2933 resolved = klass->FindVirtualMethod(name, signature);
2934 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002935 if (resolved != NULL) {
2936 dex_cache->SetResolvedMethod(method_idx, resolved);
2937 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002938 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002939 }
2940 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002941}
2942
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002943Field* ClassLinker::ResolveField(const DexFile& dex_file,
2944 uint32_t field_idx,
2945 DexCache* dex_cache,
2946 const ClassLoader* class_loader,
2947 bool is_static) {
2948 Field* resolved = dex_cache->GetResolvedField(field_idx);
2949 if (resolved != NULL) {
2950 return resolved;
2951 }
2952 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2953 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2954 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002955 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002956 return NULL;
2957 }
2958
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002959 const char* name = dex_file.GetFieldName(field_id);
2960 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002961 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002962 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002963 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002964 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002965 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002966 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002967 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002968 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002969 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2970 }
2971 return resolved;
2972}
2973
2974Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2975 uint32_t field_idx,
2976 DexCache* dex_cache,
2977 const ClassLoader* class_loader) {
2978 Field* resolved = dex_cache->GetResolvedField(field_idx);
2979 if (resolved != NULL) {
2980 return resolved;
2981 }
2982 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2983 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2984 if (klass == NULL) {
2985 DCHECK(Thread::Current()->IsExceptionPending());
2986 return NULL;
2987 }
2988
2989 const char* name = dex_file.GetFieldName(field_id);
2990 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
2991 resolved = klass->FindField(name, type);
2992 if (resolved != NULL) {
2993 dex_cache->SetResolvedField(field_idx, resolved);
2994 } else {
2995 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002996 }
2997 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002998}
2999
Ian Rogersad25ac52011-10-04 19:13:33 -07003000const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3001 Class* declaring_class = referrer->GetDeclaringClass();
3002 DexCache* dex_cache = declaring_class->GetDexCache();
3003 const DexFile& dex_file = FindDexFile(dex_cache);
3004 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3005 return dex_file.GetShorty(method_id.proto_idx_);
3006}
3007
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003008void ClassLinker::DumpAllClasses(int flags) const {
3009 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3010 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3011 std::vector<Class*> all_classes;
3012 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003013 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003014 typedef Table::const_iterator It; // TODO: C++0x auto
3015 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3016 all_classes.push_back(it->second);
3017 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003018 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3019 all_classes.push_back(it->second);
3020 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003021 }
3022
3023 for (size_t i = 0; i < all_classes.size(); ++i) {
3024 all_classes[i]->DumpClass(std::cerr, flags);
3025 }
3026}
3027
Elliott Hughescac6cc72011-11-03 20:31:21 -07003028void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3029 MutexLock mu(classes_lock_);
3030 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3031 << classes_.size() << " allocated classes\n";
3032}
3033
Elliott Hughese27955c2011-08-26 15:21:24 -07003034size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003035 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003036 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003037}
3038
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003039pid_t ClassLinker::GetClassesLockOwner() {
3040 return classes_lock_.GetOwner();
3041}
3042
3043pid_t ClassLinker::GetDexLockOwner() {
3044 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003045}
3046
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003047void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3048 DCHECK(!init_done_);
3049
3050 DCHECK(klass != NULL);
3051 DCHECK(klass->GetClassLoader() == NULL);
3052
3053 DCHECK(class_roots_ != NULL);
3054 DCHECK(class_roots_->Get(class_root) == NULL);
3055 class_roots_->Set(class_root, klass);
3056}
3057
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003058} // namespace art