blob: 1a9618c61703569b9bd719a9e02f5db0a438e1c1 [file] [log] [blame]
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001// Copyright 2011 Google Inc. All Rights Reserved.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07003#include "class_linker.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07004
Brian Carlstromd601af82012-01-06 10:15:19 -08005#include <fcntl.h>
6#include <sys/file.h>
7#include <sys/stat.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -08008#include <sys/types.h>
9#include <sys/wait.h>
10
Brian Carlstromdbc05252011-09-09 01:59:59 -070011#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070012#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070013#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070014#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070015
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070016#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070017#include "class_loader.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080018#include "debugger.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070019#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070020#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070021#include "dex_verifier.h"
22#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070023#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070024#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070026#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070027#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070028#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080029#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070030#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070031#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070032#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070033#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070034#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070035#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070036#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070037#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070038#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070039
40namespace art {
41
Elliott Hughes4a2b4172011-09-20 17:08:25 -070042namespace {
43
Elliott Hughes362f9bc2011-10-17 18:56:41 -070044void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070045void ThrowNoClassDefFoundError(const char* fmt, ...) {
46 va_list args;
47 va_start(args, fmt);
48 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
49 va_end(args);
50}
51
Elliott Hughes362f9bc2011-10-17 18:56:41 -070052void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070053void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070054 va_list args;
55 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070056 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070057 va_end(args);
58}
59
Elliott Hughes362f9bc2011-10-17 18:56:41 -070060void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070061void ThrowLinkageError(const char* fmt, ...) {
62 va_list args;
63 va_start(args, fmt);
64 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
65 va_end(args);
66}
67
Ian Rogers9f1ab122011-12-12 08:52:43 -080068void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
69 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080070 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070071 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080072 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
73 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080074 std::string location(kh.GetLocation());
75 if (!location.empty()) {
76 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070077 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070078 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070079}
80
Ian Rogersb067ac22011-12-13 18:05:09 -080081void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080082 const StringPiece& name) {
83 ClassHelper kh(c);
84 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080085 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080086 << " in class " << kh.GetDescriptor() << " or its superclasses";
87 std::string location(kh.GetLocation());
88 if (!location.empty()) {
89 msg << " (defined in " << location << ")";
90 }
91 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
92}
93
Ian Rogerscab01012012-01-10 17:35:46 -080094void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
95void ThrowNullPointerException(const char* fmt, ...) {
96 va_list args;
97 va_start(args, fmt);
98 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
99 va_end(args);
100}
101
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700102void ThrowEarlierClassFailure(Class* c) {
103 /*
104 * The class failed to initialize on a previous attempt, so we want to throw
105 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
106 * failed in verification, in which case v2 5.4.1 says we need to re-throw
107 * the previous error.
108 */
109 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
110
111 if (c->GetVerifyErrorClass() != NULL) {
112 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800113 ClassHelper ve_ch(c->GetVerifyErrorClass());
114 std::string error_descriptor(ve_ch.GetDescriptor());
115 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700116 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800117 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700118 }
119}
120
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700121void WrapExceptionInInitializer() {
122 JNIEnv* env = Thread::Current()->GetJniEnv();
123
124 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
125 CHECK(cause.get() != NULL);
126
127 env->ExceptionClear();
128
129 // TODO: add java.lang.Error to JniConstants?
130 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
131 CHECK(error_class.get() != NULL);
132 if (env->IsInstanceOf(cause.get(), error_class.get())) {
133 // We only wrap non-Error exceptions; an Error can just be used as-is.
134 env->Throw(cause.get());
135 return;
136 }
137
138 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
139 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
140 CHECK(eiie_class.get() != NULL);
141
142 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
143 CHECK(mid != NULL);
144
145 ScopedLocalRef<jthrowable> eiie(env,
146 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
147 env->Throw(eiie.get());
148}
149
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800150static size_t Hash(const char* s) {
151 // This is the java.lang.String hashcode for convenience, not interoperability.
152 size_t hash = 0;
153 for (; *s != '\0'; ++s) {
154 hash = hash * 31 + *s;
155 }
156 return hash;
157}
158
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700159} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700160
Elliott Hughes418d20f2011-09-22 14:00:39 -0700161const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700162 "Ljava/lang/Class;",
163 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700164 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700165 "[Ljava/lang/Object;",
166 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700167 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700168 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700169 "Ljava/lang/reflect/Field;",
170 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700171 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700172 "Ljava/lang/ClassLoader;",
173 "Ldalvik/system/BaseDexClassLoader;",
174 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700175 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700176 "Z",
177 "B",
178 "C",
179 "D",
180 "F",
181 "I",
182 "J",
183 "S",
184 "V",
185 "[Z",
186 "[B",
187 "[C",
188 "[D",
189 "[F",
190 "[I",
191 "[J",
192 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700193 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700194};
195
Elliott Hughes5f791332011-09-15 17:45:30 -0700196class ObjectLock {
197 public:
198 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
199 CHECK(object != NULL);
200 obj_->MonitorEnter(self_);
201 }
202
203 ~ObjectLock() {
204 obj_->MonitorExit(self_);
205 }
206
207 void Wait() {
208 return Monitor::Wait(self_, obj_, 0, 0, false);
209 }
210
211 void Notify() {
212 obj_->Notify();
213 }
214
215 void NotifyAll() {
216 obj_->NotifyAll();
217 }
218
219 private:
220 Thread* self_;
221 Object* obj_;
222 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
223};
224
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800225ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700226 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800227 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700228 class_linker->Init(boot_class_path);
229 return class_linker.release();
230}
231
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800232ClassLinker* ClassLinker::Create(InternTable* intern_table) {
233 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700234 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700235 return class_linker.release();
236}
237
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800238ClassLinker::ClassLinker(InternTable* intern_table)
239 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700240 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700241 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700242 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700243 init_done_(false),
244 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700245 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700246}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700247
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700248void CreateClassPath(const std::string& class_path,
249 std::vector<const DexFile*>& class_path_vector) {
250 std::vector<std::string> parsed;
251 Split(class_path, ':', parsed);
252 for (size_t i = 0; i < parsed.size(); ++i) {
253 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700254 if (dex_file == NULL) {
255 LOG(WARNING) << "Failed to open dex file " << parsed[i];
256 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700257 class_path_vector.push_back(dex_file);
258 }
259 }
260}
261
262void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800263 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700264
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700265 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700266
Elliott Hughes30646832011-10-13 16:59:46 -0700267 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700268 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
269 CHECK(java_lang_Class.get() != NULL);
270 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700271 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700272 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700273
Elliott Hughes418d20f2011-09-22 14:00:39 -0700274 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700275 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
276 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700277
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700278 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700279 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
280 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700281 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700284
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700286 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
287 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700288
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700289 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700290 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700291
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700293 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
294 char_array_class->SetComponentType(char_class.get());
295 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700296
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700298 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
299 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700300 java_lang_String->SetObjectSize(sizeof(String));
301 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400302
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303 // Create storage for root classes, save away our work so far (requires
304 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700305 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700306 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700307 SetClassRoot(kJavaLangClass, java_lang_Class.get());
308 SetClassRoot(kJavaLangObject, java_lang_Object.get());
309 SetClassRoot(kClassArrayClass, class_array_class.get());
310 SetClassRoot(kObjectArrayClass, object_array_class.get());
311 SetClassRoot(kCharArrayClass, char_array_class.get());
312 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313
314 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700315 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
316 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
317 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
318 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
319 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
320 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
321 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
322 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700323
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700324 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700325 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700326
327 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700328 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700329 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 IntArray::SetArrayClass(int_array_class.get());
331 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700333 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700334
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700335 // setup boot_class_path_ and register class_path now that we can
336 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700337 std::vector<const DexFile*> boot_class_path_vector;
338 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700339 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700340 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
341 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700342 CHECK(dex_file != NULL);
343 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700344 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345
Elliott Hughes80609252011-09-23 17:24:51 -0700346 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700348 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700349 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700351 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
352
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700353 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
354 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700356 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700358 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700359
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700360 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700361 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700363 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700365 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366
367 // now we can use FindSystemClass
368
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700369 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700370 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700371 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700372
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700373 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374 java_lang_Object->SetStatus(Class::kStatusNotReady);
375 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700376 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
378 java_lang_String->SetStatus(Class::kStatusNotReady);
379 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700380 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
382
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700383 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700384 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
385 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
386
387 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
388 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
389
390 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700391 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392
393 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
394 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
395
396 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700397 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700398
399 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
400 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
401
402 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
403 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
404
405 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
406 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
407
Elliott Hughes418d20f2011-09-22 14:00:39 -0700408 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700409 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700410
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700412 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
414 // Setup the single, global copies of "interfaces" and "iftable"
415 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
416 CHECK(java_lang_Cloneable != NULL);
417 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
418 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419 // We assume that Cloneable/Serializable don't have superinterfaces --
420 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700421 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800422 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
423 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700424
Elliott Hughes418d20f2011-09-22 14:00:39 -0700425 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800426 ClassHelper kh(class_array_class.get(), this);
427 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
428 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
429 kh.ChangeClass(object_array_class.get());
430 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
431 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700432 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700433 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700434 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700435 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700436
Elliott Hughes80609252011-09-23 17:24:51 -0700437 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
438 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700439 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700440
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700442 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700443 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444
445 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700446 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700447 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700448
Ian Rogers466bb252011-10-14 03:29:56 -0700449 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
450
451 // Create java.lang.reflect.Proxy root
452 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
453 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
454
Brian Carlstrom1f870082011-08-23 16:02:11 -0700455 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700456 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
457 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700458 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459 java_lang_ref_FinalizerReference->SetAccessFlags(
460 java_lang_ref_FinalizerReference->GetAccessFlags() |
461 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700462 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700463 java_lang_ref_PhantomReference->SetAccessFlags(
464 java_lang_ref_PhantomReference->GetAccessFlags() |
465 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700466 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700467 java_lang_ref_SoftReference->SetAccessFlags(
468 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700469 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700470 java_lang_ref_WeakReference->SetAccessFlags(
471 java_lang_ref_WeakReference->GetAccessFlags() |
472 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700473
Brian Carlstromaded5f72011-10-07 17:15:04 -0700474 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700476 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700477 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
478
479 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
480 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
481 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
482
483 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
484 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
485 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
486 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
487
488 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700489 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
490 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700491 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700492
Brian Carlstroma663ea52011-08-19 23:33:41 -0700493 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700494
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800495 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700496}
497
498void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800499 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700500
501 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700502 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700503 // as the types of the field can't be resolved prior to the runtime being
504 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700505 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700506 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700507 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
508
Elliott Hughesadb460d2011-10-05 17:02:34 -0700509 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
510
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800511 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
512
Brian Carlstrom16192862011-09-12 17:50:06 -0700513 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800514 FieldHelper fh(pendingNext, this);
515 CHECK_STREQ(fh.GetName(), "pendingNext");
516 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
517 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700518
519 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800520 fh.ChangeField(queue);
521 CHECK_STREQ(fh.GetName(), "queue");
522 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
523 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700524
525 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800526 fh.ChangeField(queueNext);
527 CHECK_STREQ(fh.GetName(), "queueNext");
528 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
529 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700530
531 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800532 fh.ChangeField(referent);
533 CHECK_STREQ(fh.GetName(), "referent");
534 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
535 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700536
537 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800538 fh.ChangeField(zombie);
539 CHECK_STREQ(fh.GetName(), "zombie");
540 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
541 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700542
543 Heap::SetReferenceOffsets(referent->GetOffset(),
544 queue->GetOffset(),
545 queueNext->GetOffset(),
546 pendingNext->GetOffset(),
547 zombie->GetOffset());
548
Brian Carlstroma663ea52011-08-19 23:33:41 -0700549 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700551 ClassRoot class_root = static_cast<ClassRoot>(i);
552 Class* klass = GetClassRoot(class_root);
553 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700554 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700555 // note SetClassRoot does additional validation.
556 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700557 }
558
Elliott Hughes92f14b22011-10-06 12:29:54 -0700559 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700560
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700561 // disable the slow paths in FindClass and CreatePrimitiveClass now
562 // that Object, Class, and Object[] are setup
563 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700564
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800565 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700566}
567
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700568void ClassLinker::RunRootClinits() {
569 Thread* self = Thread::Current();
570 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
571 Class* c = GetClassRoot(ClassRoot(i));
572 if (!c->IsArrayClass() && !c->IsPrimitive()) {
573 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700574 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700575 }
576 }
577}
578
Brian Carlstromd601af82012-01-06 10:15:19 -0800579bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
580 int oat_fd,
581 const std::string& oat_cache_filename) {
jeffhao262bf462011-10-20 18:36:32 -0700582
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800583 std::string dex2oat_string("/system/bin/dex2oat");
584#ifndef NDEBUG
585 dex2oat_string += 'd';
586#endif
587 const char* dex2oat = dex2oat_string.c_str();
588
589 const char* class_path = Runtime::Current()->GetClassPath().c_str();
590
591 std::string boot_image_option_string("--boot-image=");
592 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
593 const char* boot_image_option = boot_image_option_string.c_str();
594
595 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800596 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800597 const char* dex_file_option = dex_file_option_string.c_str();
598
Brian Carlstromd601af82012-01-06 10:15:19 -0800599 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800600 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800601 const char* oat_fd_option = oat_fd_option_string.c_str();
602
603 std::string oat_name_option_string("--oat-name=");
604 oat_name_option_string += oat_cache_filename;
605 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800606
jeffhao262bf462011-10-20 18:36:32 -0700607 // fork and exec dex2oat
608 pid_t pid = fork();
609 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800610 // no allocation allowed between fork and exec
611 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700612 "--runtime-arg", "-Xms64m",
613 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500614 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800615 "--runtime-arg", class_path,
616 boot_image_option,
617 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800618 oat_fd_option,
619 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700620 NULL);
621
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800622 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800623 return false;
jeffhao262bf462011-10-20 18:36:32 -0700624 } else {
625 // wait for dex2oat to finish
626 int status;
627 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
628 if (got_pid != pid) {
629 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800630 return false;
jeffhao262bf462011-10-20 18:36:32 -0700631 }
632 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800633 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
634 return false;
jeffhao262bf462011-10-20 18:36:32 -0700635 }
636 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800637 return true;
jeffhao262bf462011-10-20 18:36:32 -0700638}
639
Brian Carlstrom866c8622012-01-06 16:35:13 -0800640void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
641 MutexLock mu(dex_lock_);
642 RegisterOatFileLocked(oat_file);
643}
644
645void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
646 dex_lock_.AssertHeld();
647 oat_files_.push_back(&oat_file);
648}
649
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700650OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700651 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700652 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800653 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700654 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800655 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
656 // check the down cast
657 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700658 std::string oat_filename;
659 oat_filename += runtime->GetHostPrefix();
660 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700661 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700662 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700663 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700664 return NULL;
665 }
666 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
667 uint32_t image_oat_checksum = image_header.GetOatChecksum();
668 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800669 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700670 << " to expected oat checksum " << std::hex << oat_checksum
671 << " in image";
672 return NULL;
673 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800674 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800675 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700676 return oat_file;
677}
678
Brian Carlstromae826982011-11-09 01:33:42 -0800679const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
680 for (size_t i = 0; i < oat_files_.size(); i++) {
681 const OatFile* oat_file = oat_files_[i];
682 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800683 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800684 return oat_file;
685 }
686 }
687 return NULL;
688}
689
Brian Carlstromd601af82012-01-06 10:15:19 -0800690class LockedFd {
691 public:
692 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
693 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
694 if (fd == -1) {
695 PLOG(ERROR) << "Failed to open file '" << name << "'";
696 return NULL;
697 }
698 fchmod(fd, mode);
699
700 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
701 // try to lock non-blocking so we can log if we need may need to block
702 int result = flock(fd, LOCK_EX | LOCK_NB);
703 if (result == -1) {
704 LOG(WARNING) << "sleeping while locking file " << name;
705 // retry blocking
706 result = flock(fd, LOCK_EX);
707 }
708 if (result == -1) {
709 PLOG(ERROR) << "Failed to lock file '" << name << "'";
710 close(fd);
711 return NULL;
712 }
713 return new LockedFd(fd);
714 }
715
716 int GetFd() const {
717 return fd_;
718 }
719
720 ~LockedFd() {
721 if (fd_ != -1) {
722 int result = flock(fd_, LOCK_UN);
723 if (result == -1) {
724 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
725 }
726 close(fd_);
727 }
728 }
729
730 private:
731 explicit LockedFd(int fd) : fd_(fd) {}
732
733 int fd_;
734};
735
Brian Carlstromae826982011-11-09 01:33:42 -0800736const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700737 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800738 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
739 if (open_oat_file != NULL) {
740 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800741 }
742
Brian Carlstromd601af82012-01-06 10:15:19 -0800743 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800744 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
745 if (open_oat_file != NULL) {
746 return open_oat_file;
747 }
748
Brian Carlstromd601af82012-01-06 10:15:19 -0800749 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800750 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
751 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800752 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
753 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800754 RegisterOatFileLocked(*oat_file.get());
755 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800756 }
757 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
758 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
759 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
760 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
761 }
762 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700763 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800764 // Try to generate oat file if it wasn't found or was obsolete.
765 // Note we can be racing with another runtime to do this.
766 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
767 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
768 if (locked_fd.get() == NULL) {
769 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
770 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700771 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800772 // Check to see if the fd we opened and locked matches the file in
773 // the filesystem. If they don't, then somebody else unlinked ours
774 // and created a new file, and we need to use that one instead. (If
775 // we caught them between the unlink and the create, we'll get an
776 // ENOENT from the file stat.)
777 struct stat fd_stat;
778 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
779 if (fd_stat_result != 0) {
780 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
781 return NULL;
782 }
783 struct stat file_stat;
784 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
785 if (file_stat_result != 0
786 || fd_stat.st_dev != file_stat.st_dev
787 || fd_stat.st_ino != file_stat.st_ino) {
788 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
789 usleep(250 * 1000); // if something is hosed, don't peg machine
790 continue;
791 }
792
793 // We have the correct file open and locked. If the file size is
794 // zero, then it was just created by us and we can generate its
795 // contents. If not, someone else created it. Either way, we'll
796 // loop to retry opening the file.
797 if (fd_stat.st_size == 0) {
798 bool success = GenerateOatFile(dex_file.GetLocation(),
799 locked_fd->GetFd(),
800 oat_cache_filename);
801 if (!success) {
802 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
803 return NULL;
804 }
805 }
jeffhao262bf462011-10-20 18:36:32 -0700806 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800807 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700808}
809
Brian Carlstromae826982011-11-09 01:33:42 -0800810const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700811 for (size_t i = 0; i < oat_files_.size(); i++) {
812 const OatFile* oat_file = oat_files_[i];
813 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800814 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700815 return oat_file;
816 }
817 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700818 return NULL;
819}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700820
Brian Carlstromae826982011-11-09 01:33:42 -0800821const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800822 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700823 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800824 if (oat_location.empty() || oat_location[0] != '/') {
825 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700826 return NULL;
827 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700828
Brian Carlstroma9f19782011-10-13 00:14:47 -0700829 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800830 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800831 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700832 if (oat_file != NULL) {
833 return oat_file;
834 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700835 oat_file = OatFile::Open(cache_location, "", NULL);
836 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800837 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700838 return NULL;
839 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700840 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700841
Brian Carlstromae826982011-11-09 01:33:42 -0800842 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700843 return oat_file;
844}
845
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700846void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800847 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700848 CHECK(!init_done_);
849
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700850 const std::vector<Space*>& spaces = Heap::GetSpaces();
851 for (size_t i = 0; i < spaces.size(); i++) {
852 Space* space = spaces[i] ;
853 if (space->IsImageSpace()) {
854 OatFile* oat_file = OpenOat(space);
855 CHECK(oat_file != NULL) << "Failed to open oat file for image";
856 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
857 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
858
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800859 if (i == 0) {
860 // Special case of setting up the String class early so that we can test arbitrary objects
861 // as being Strings or not
862 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
863 ->AsObjectArray<Class>()->Get(kJavaLangString);
864 String::SetClass(java_lang_String);
865 }
866
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700867 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
868 static_cast<uint32_t>(dex_caches->GetLength()));
869 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700870 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800871 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800872 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
873 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700874 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800875 LOG(FATAL) << "Failed to open dex file " << dex_file_location
876 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700877 }
878
Brian Carlstromaded5f72011-10-07 17:15:04 -0700879 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700880
Brian Carlstromdf143242011-10-10 18:05:34 -0700881 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700882 }
883 }
884 }
885
Brian Carlstroma663ea52011-08-19 23:33:41 -0700886 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
887 DCHECK(heap_bitmap != NULL);
888
Brian Carlstroma663ea52011-08-19 23:33:41 -0700889 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700890 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700891
892 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700893 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
894 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700895
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800896 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700897 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
898 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800899 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700900 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700901 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700902 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
903 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
904 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
905 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
906 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
907 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
908 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
909 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700910 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700911 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700912
913 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700914
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800915 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700916}
917
Brian Carlstrom78128a62011-09-15 17:21:19 -0700918void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700919 DCHECK(obj != NULL);
920 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700921 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700922
Elliott Hughesdbb40792011-11-18 17:05:22 -0800923 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700924 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700925 return;
926 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700927 if (obj->IsClass()) {
928 // restore class to ClassLinker::classes_ table
929 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800930 ClassHelper kh(klass, class_linker);
931 bool success = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
Ian Rogers5d76c432011-10-31 21:42:49 -0700932 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700933 return;
934 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700935}
936
937// Keep in sync with InitCallback. Anything we visit, we need to
938// reinit references to when reinitializing a ClassLinker from a
939// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700940void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
941 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700942
943 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700944 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700945 }
946
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700947 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700948 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700949 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700950 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700951 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700952 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700953 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700954 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700955
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700956 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700957}
958
Elliott Hughesa2155262011-11-16 16:26:58 -0800959void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
960 MutexLock mu(classes_lock_);
961 typedef Table::const_iterator It; // TODO: C++0x auto
962 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
963 if (!visitor(it->second, arg)) {
964 return;
965 }
966 }
967 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
968 if (!visitor(it->second, arg)) {
969 return;
970 }
971 }
972}
973
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700974ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700975 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700976 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700977 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700978 BooleanArray::ResetArrayClass();
979 ByteArray::ResetArrayClass();
980 CharArray::ResetArrayClass();
981 DoubleArray::ResetArrayClass();
982 FloatArray::ResetArrayClass();
983 IntArray::ResetArrayClass();
984 LongArray::ResetArrayClass();
985 ShortArray::ResetArrayClass();
986 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700987 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700988 STLDeleteElements(&boot_class_path_);
989 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700990}
991
992DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700993 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
994 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700995 return NULL;
996 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700997 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
998 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700999 return NULL;
1000 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001001 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
1002 if (strings.get() == NULL) {
1003 return NULL;
1004 }
1005 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
1006 if (types.get() == NULL) {
1007 return NULL;
1008 }
1009 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
1010 if (methods.get() == NULL) {
1011 return NULL;
1012 }
1013 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
1014 if (fields.get() == NULL) {
1015 return NULL;
1016 }
1017 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1018 if (code_and_direct_methods.get() == NULL) {
1019 return NULL;
1020 }
1021 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1022 if (initialized_static_storage.get() == NULL) {
1023 return NULL;
1024 }
1025
1026 dex_cache->Init(location.get(),
1027 strings.get(),
1028 types.get(),
1029 methods.get(),
1030 fields.get(),
1031 code_and_direct_methods.get(),
1032 initialized_static_storage.get());
1033 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001034}
1035
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001036CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1037 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001038}
1039
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001040InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1041 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001042 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1043 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001044 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001045 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001046}
1047
Brian Carlstrom4873d462011-08-21 15:23:39 -07001048Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1049 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001050 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001051 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001052 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001053 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001054}
1055
Brian Carlstrom4873d462011-08-21 15:23:39 -07001056Class* ClassLinker::AllocClass(size_t class_size) {
1057 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001058}
1059
Jesse Wilson35baaab2011-08-10 16:18:03 -04001060Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001061 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001062}
1063
1064Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001065 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001066}
1067
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001068ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1069 return ObjectArray<StackTraceElement>::Alloc(
1070 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1071 length);
1072}
1073
Brian Carlstromaded5f72011-10-07 17:15:04 -07001074Class* EnsureResolved(Class* klass) {
1075 DCHECK(klass != NULL);
1076 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001077 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001078 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001079 ObjectLock lock(klass);
1080 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001081 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001082 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001083 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001084 return NULL;
1085 }
1086 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001087 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001088 lock.Wait();
1089 }
1090 }
1091 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001092 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001093 return NULL;
1094 }
1095 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001096 CHECK(klass->IsResolved()) << PrettyClass(klass);
1097 CHECK(!self->IsExceptionPending())
1098 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1099 return klass;
1100}
1101
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001102Class* ClassLinker::FindSystemClass(const char* descriptor) {
1103 return FindClass(descriptor, NULL);
1104}
1105
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001106Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
1107 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001108 Thread* self = Thread::Current();
1109 DCHECK(self != NULL);
1110 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001111 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001112 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1113 // for primitive classes that aren't backed by dex files.
1114 return FindPrimitiveClass(descriptor[0]);
1115 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001116 // Find the class in the loaded classes table.
1117 Class* klass = LookupClass(descriptor, class_loader);
1118 if (klass != NULL) {
1119 return EnsureResolved(klass);
1120 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 // Class is not yet loaded.
1122 if (descriptor[0] == '[') {
1123 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001124
Jesse Wilson47daf872011-11-23 11:42:45 -05001125 } else if (class_loader == NULL) {
1126 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1127 if (pair.second != NULL) {
1128 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1129 }
1130
1131 } else if (ClassLoader::UseCompileTimeClassPath()) {
1132 // first try the boot class path
1133 Class* system_class = FindSystemClass(descriptor);
1134 if (system_class != NULL) {
1135 return system_class;
1136 }
1137 CHECK(self->IsExceptionPending());
1138 self->ClearException();
1139
1140 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001141 const std::vector<const DexFile*>& class_path
1142 = ClassLoader::GetCompileTimeClassPath(class_loader);
1143 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001144 if (pair.second != NULL) {
1145 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001146 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001147
1148 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001149 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001150 ScopedThreadStateChange(self, Thread::kNative);
1151 JNIEnv* env = self->GetJniEnv();
1152 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1153 CHECK(c.get() != NULL);
1154 // TODO: cache method?
1155 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1156 CHECK(mid != NULL);
1157 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1158 if (class_name_object.get() == NULL) {
1159 return NULL;
1160 }
1161 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001162 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1163 class_name_object.get()));
1164 if (env->ExceptionOccurred()) {
1165 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1166 // TODO: initialize the cause of the NCDFE to this exception
1167 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001168 // broken loader - throw NPE to be compatible with Dalvik
1169 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1170 class_name_string.c_str());
1171 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001172 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001173 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001174 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001175 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001176 }
1177
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001178 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001179 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001180}
1181
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001182Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001183 const ClassLoader* class_loader,
1184 const DexFile& dex_file,
1185 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001186 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 // Load the class from the dex file.
1188 if (!init_done_) {
1189 // finish up init of hand crafted class_roots_
1190 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001193 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001194 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001195 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001196 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001197 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001198 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001199 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001200 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001201 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001202 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001203 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001204 }
1205 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001206 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001207 }
1208 klass->SetDexCache(FindDexCache(dex_file));
1209 LoadClass(dex_file, dex_class_def, klass, class_loader);
1210 // Check for a pending exception during load
1211 Thread* self = Thread::Current();
1212 if (self->IsExceptionPending()) {
1213 return NULL;
1214 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001215 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001216 klass->SetClinitThreadId(self->GetTid());
1217 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001218 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001219 if (!success) {
1220 // We may fail to insert if we raced with another thread.
1221 klass->SetClinitThreadId(0);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001222 klass.reset(LookupClass(descriptor.data(), class_loader));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001223 CHECK(klass.get() != NULL);
1224 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001225 }
1226 // Finish loading (if necessary) by finding parents
1227 CHECK(!klass->IsLoaded());
1228 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1229 // Loading failed.
1230 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001231 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001232 lock.NotifyAll();
1233 return NULL;
1234 }
1235 CHECK(klass->IsLoaded());
1236 // Link the class (if necessary)
1237 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001238 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001239 // Linking failed.
1240 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001241 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001242 lock.NotifyAll();
1243 return NULL;
1244 }
1245 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001246
1247 /*
1248 * We send CLASS_PREPARE events to the debugger from here. The
1249 * definition of "preparation" is creating the static fields for a
1250 * class and initializing them to the standard default values, but not
1251 * executing any code (that comes later, during "initialization").
1252 *
1253 * We did the static preparation in LinkClass.
1254 *
1255 * The class has been prepared and resolved but possibly not yet verified
1256 * at this point.
1257 */
1258 Dbg::PostClassPrepare(klass.get());
1259
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001260 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001261}
1262
Brian Carlstrom4873d462011-08-21 15:23:39 -07001263// Precomputes size that will be needed for Class, matching LinkStaticFields
1264size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1265 const DexFile::ClassDef& dex_class_def) {
1266 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001267 size_t num_ref = 0;
1268 size_t num_32 = 0;
1269 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001270 if (class_data != NULL) {
1271 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1272 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001273 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001274 char c = descriptor[0];
1275 if (c == 'L' || c == '[') {
1276 num_ref++;
1277 } else if (c == 'J' || c == 'D') {
1278 num_64++;
1279 } else {
1280 num_32++;
1281 }
1282 }
1283 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001284 // start with generic class data
1285 size_t size = sizeof(Class);
1286 // follow with reference fields which must be contiguous at start
1287 size += (num_ref * sizeof(uint32_t));
1288 // if there are 64-bit fields to add, make sure they are aligned
1289 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1290 if (num_32 != 0) {
1291 // use an available 32-bit field for padding
1292 num_32--;
1293 }
1294 size += sizeof(uint32_t); // either way, we are adding a word
1295 DCHECK_EQ(size, RoundUp(size, 8));
1296 }
1297 // tack on any 64-bit fields now that alignment is assured
1298 size += (num_64 * sizeof(uint64_t));
1299 // tack on any remaining 32-bit fields
1300 size += (num_32 * sizeof(uint32_t));
1301 return size;
1302}
1303
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001304void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001305 // Every kind of method should at least get an invoke stub from the oat_method.
1306 // non-abstract methods also get their code pointers.
1307 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001308 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001309
1310 if (method->IsAbstract()) {
1311 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1312 return;
1313 }
1314 if (method->IsNative()) {
1315 // unregistering restores the dlsym lookup stub
1316 method->UnregisterNative();
1317 return;
1318 }
1319}
1320
Brian Carlstromf615a612011-07-23 12:50:34 -07001321void ClassLinker::LoadClass(const DexFile& dex_file,
1322 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001323 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001324 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001325 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001326 CHECK(klass->GetDexCache() != NULL);
1327 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001328 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001329 CHECK(descriptor != NULL);
1330
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001331 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001332 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001333 // Make sure that none of our runtime-only flags are set.
1334 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001335 klass->SetAccessFlags(access_flags);
1336 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001337 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001338 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001339
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001340 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001341
Ian Rogers0571d352011-11-03 19:51:38 -07001342 // Load fields fields.
1343 const byte* class_data = dex_file.GetClassData(dex_class_def);
1344 if (class_data == NULL) {
1345 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001346 }
Ian Rogers0571d352011-11-03 19:51:38 -07001347 ClassDataItemIterator it(dex_file, class_data);
1348 if (it.NumStaticFields() != 0) {
1349 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1350 }
1351 if (it.NumInstanceFields() != 0) {
1352 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1353 }
1354 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1355 SirtRef<Field> sfield(AllocField());
1356 klass->SetStaticField(i, sfield.get());
1357 LoadField(dex_file, it, klass, sfield);
1358 }
1359 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1360 SirtRef<Field> ifield(AllocField());
1361 klass->SetInstanceField(i, ifield.get());
1362 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001363 }
1364
Brian Carlstromaded5f72011-10-07 17:15:04 -07001365 UniquePtr<const OatFile::OatClass> oat_class;
1366 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001367 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001368 if (oat_file != NULL) {
1369 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1370 if (oat_dex_file != NULL) {
1371 uint32_t class_def_index;
1372 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1373 CHECK(found) << descriptor;
1374 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001375 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001376 }
1377 }
1378 }
Ian Rogers0571d352011-11-03 19:51:38 -07001379 // Load methods.
1380 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001381 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001382 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001383 }
Ian Rogers0571d352011-11-03 19:51:38 -07001384 if (it.NumVirtualMethods() != 0) {
1385 // TODO: append direct methods to class object
1386 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001387 }
Ian Rogers0571d352011-11-03 19:51:38 -07001388 size_t method_index = 0;
1389 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1390 SirtRef<Method> method(AllocMethod());
1391 klass->SetDirectMethod(i, method.get());
1392 LoadMethod(dex_file, it, klass, method);
1393 if (oat_class.get() != NULL) {
1394 LinkCode(method, oat_class.get(), method_index);
1395 }
1396 method_index++;
1397 }
1398 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1399 SirtRef<Method> method(AllocMethod());
1400 klass->SetVirtualMethod(i, method.get());
1401 LoadMethod(dex_file, it, klass, method);
1402 if (oat_class.get() != NULL) {
1403 LinkCode(method, oat_class.get(), method_index);
1404 }
1405 method_index++;
1406 }
1407 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001408}
1409
Ian Rogers0571d352011-11-03 19:51:38 -07001410void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1411 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001412 uint32_t field_idx = it.GetMemberIndex();
1413 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001414 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001415 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001416}
1417
Ian Rogers0571d352011-11-03 19:51:38 -07001418void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1419 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001420 uint32_t method_idx = it.GetMemberIndex();
1421 dst->SetDexMethodIndex(method_idx);
1422 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001423 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001424
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001425
1426 StringPiece method_name(dex_file.GetMethodName(method_id));
1427 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001428 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1429 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001430
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001431 if (method_name == "finalize") {
1432 // Create the prototype for a signature of "()V"
1433 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1434 if (void_string_id != NULL) {
1435 const DexFile::TypeId* void_type_id =
1436 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1437 if (void_type_id != NULL) {
1438 std::vector<uint16_t> no_args;
1439 const DexFile::ProtoId* finalizer_proto =
1440 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1441 if (finalizer_proto != NULL) {
1442 // We have the prototype in the dex file
1443 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1444 klass->SetFinalizable();
1445 } else {
1446 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1447 // The Enum class declares a "final" finalize() method to prevent subclasses from
1448 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1449 // subclasses, so we exclude it here.
1450 // We also want to avoid setting the flag on Object, where we know that finalize() is
1451 // empty.
1452 if (klass_descriptor != "Ljava/lang/Object;" &&
1453 klass_descriptor != "Ljava/lang/Enum;") {
1454 klass->SetFinalizable();
1455 }
1456 }
1457 }
1458 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001459 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001460 }
Ian Rogers0571d352011-11-03 19:51:38 -07001461 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001462 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001463
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001464 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1465 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1466 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1467 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1468 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1469 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001470
Brian Carlstrom934486c2011-07-12 23:42:50 -07001471 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001472}
1473
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001474void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001475 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1476 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001477}
1478
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001479void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1480 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001481 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001482 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001483}
1484
Brian Carlstromaded5f72011-10-07 17:15:04 -07001485bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001486 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001487 for (size_t i = 0; i != dex_files_.size(); ++i) {
1488 if (dex_files_[i] == &dex_file) {
1489 return true;
1490 }
1491 }
1492 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001493}
1494
Brian Carlstromaded5f72011-10-07 17:15:04 -07001495bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001496 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001497 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001498}
1499
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001500void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001501 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001502 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001503 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001504 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001505 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001506}
1507
Brian Carlstromaded5f72011-10-07 17:15:04 -07001508void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001509 {
1510 MutexLock mu(dex_lock_);
1511 if (IsDexFileRegisteredLocked(dex_file)) {
1512 return;
1513 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001514 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001515 // Don't alloc while holding the lock, since allocation may need to
1516 // suspend all threads and another thread may need the dex_lock_ to
1517 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001518 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001519 {
1520 MutexLock mu(dex_lock_);
1521 if (IsDexFileRegisteredLocked(dex_file)) {
1522 return;
1523 }
1524 RegisterDexFileLocked(dex_file, dex_cache);
1525 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001526}
1527
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001528void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001529 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001530 RegisterDexFileLocked(dex_file, dex_cache);
1531}
1532
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001533const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001534 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001535 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001536 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1537 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001538 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001539 }
1540 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001541 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001542 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001543}
1544
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001545DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001546 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001547 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001548 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001549 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001550 }
1551 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001552 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001553 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001554}
1555
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001556Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1557 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001558 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001559 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001560 CHECK(primitive_class != NULL);
1561 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001562 primitive_class->SetPrimitiveType(type);
1563 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001564 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001565 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1566 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001567}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001568
Brian Carlstrombe977852011-07-19 14:54:54 -07001569// Create an array class (i.e. the class object for the array, not the
1570// array itself). "descriptor" looks like "[C" or "[[[[B" or
1571// "[Ljava/lang/String;".
1572//
1573// If "descriptor" refers to an array of primitives, look up the
1574// primitive type's internally-generated class object.
1575//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001576// "class_loader" is the class loader of the class that's referring to
1577// us. It's used to ensure that we're looking for the element type in
1578// the right context. It does NOT become the class loader for the
1579// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001580//
1581// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001582Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001583 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001584
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001585 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001586 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001587 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001588 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001589 return NULL;
1590 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001591
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001592 // See if the component type is already loaded. Array classes are
1593 // always associated with the class loader of their underlying
1594 // element type -- an array of Strings goes with the loader for
1595 // java/lang/String -- so we need to look for it there. (The
1596 // caller should have checked for the existence of the class
1597 // before calling here, but they did so with *their* class loader,
1598 // not the component type's loader.)
1599 //
1600 // If we find it, the caller adds "loader" to the class' initiating
1601 // loader list, which should prevent us from going through this again.
1602 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001603 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001604 // are the same, because our caller (FindClass) just did the
1605 // lookup. (Even if we get this wrong we still have correct behavior,
1606 // because we effectively do this lookup again when we add the new
1607 // class to the hash table --- necessary because of possible races with
1608 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001609 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001610 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001611 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001612 return new_class;
1613 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001614 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001615
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001616 // Fill out the fields in the Class.
1617 //
1618 // It is possible to execute some methods against arrays, because
1619 // all arrays are subclasses of java_lang_Object_, so we need to set
1620 // up a vtable. We can just point at the one in java_lang_Object_.
1621 //
1622 // Array classes are simple enough that we don't need to do a full
1623 // link step.
1624
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001625 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001626 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001627 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001628 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001629 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001630 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001631 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001632 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001633 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001634 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001635 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001636 }
1637 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001638 if (new_class.get() == NULL) {
1639 new_class.reset(AllocClass(sizeof(Class)));
1640 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001641 return NULL;
1642 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001643 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001644 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001645 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001646 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001647 new_class->SetSuperClass(java_lang_Object);
1648 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001649 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001650 new_class->SetClassLoader(component_type->GetClassLoader());
1651 new_class->SetStatus(Class::kStatusInitialized);
1652 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001653 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001654
1655
1656 // All arrays have java/lang/Cloneable and java/io/Serializable as
1657 // interfaces. We need to set that up here, so that stuff like
1658 // "instanceof" works right.
1659 //
1660 // Note: The GC could run during the call to FindSystemClass,
1661 // so we need to make sure the class object is GC-valid while we're in
1662 // there. Do this by clearing the interface list so the GC will just
1663 // think that the entries are null.
1664
1665
1666 // Use the single, global copies of "interfaces" and "iftable"
1667 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001668 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001669 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001670
1671 // Inherit access flags from the component type. Arrays can't be
1672 // used as a superclass or interface, so we want to add "final"
1673 // and remove "interface".
1674 //
1675 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001676 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001677 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001678 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1679 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001680
Ian Rogers5d76c432011-10-31 21:42:49 -07001681 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001682 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001683 }
1684 // Another thread must have loaded the class after we
1685 // started but before we finished. Abandon what we've
1686 // done.
1687 //
1688 // (Yes, this happens.)
1689
1690 // Grab the winning class.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001691 Class* other_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001692 DCHECK(other_class != NULL);
1693 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001694}
1695
1696Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001697 switch (Primitive::GetType(type)) {
1698 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001699 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001700 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001701 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001702 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001703 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001704 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001705 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001706 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001707 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001708 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001709 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001710 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001711 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001712 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001713 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001714 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001715 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001716 case Primitive::kPrimNot:
1717 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001718 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001719 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001720 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001721 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001722}
1723
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001724bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001725 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001726 DexCache* dex_cache = klass->GetDexCache();
1727 std::string source;
1728 if (dex_cache != NULL) {
1729 source += " from ";
1730 source += dex_cache->GetLocation()->ToModifiedUtf8();
1731 }
1732 LOG(INFO) << "Loaded class " << descriptor << source;
1733 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001734 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001735 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001736 Table::iterator it;
1737 if (image_class) {
1738 // TODO: sanity check there's no match in classes_
1739 it = image_classes_.insert(std::make_pair(hash, klass));
1740 } else {
1741 // TODO: sanity check there's no match in image_classes_
1742 it = classes_.insert(std::make_pair(hash, klass));
1743 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001744 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001745}
1746
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001747bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1748 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001749 MutexLock mu(classes_lock_);
1750 typedef Table::const_iterator It; // TODO: C++0x auto
1751 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001752 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001753 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1754 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001755 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001756 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001757 classes_.erase(it);
1758 return true;
1759 }
1760 }
1761 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1762 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001763 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001764 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001765 image_classes_.erase(it);
1766 return true;
1767 }
1768 }
1769 return false;
1770}
1771
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001772Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1773 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001774 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001775 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001776 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001777 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001778 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001779 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001780 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001781 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001782 return klass;
1783 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001784 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001785 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1786 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001787 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001788 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001789 return klass;
1790 }
1791 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001792 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001793}
1794
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001795void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001796 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001797 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001798 MutexLock mu(classes_lock_);
1799 typedef Table::const_iterator It; // TODO: C++0x auto
1800 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001801 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001802 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001803 Class* klass = it->second;
1804 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001805 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001806 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001807 }
1808 }
1809 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001810 Class* klass = it->second;
1811 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001812 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001813 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001814 }
1815 }
1816}
1817
jeffhao98eacac2011-09-14 16:11:53 -07001818void ClassLinker::VerifyClass(Class* klass) {
1819 if (klass->IsVerified()) {
1820 return;
1821 }
1822
1823 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001824 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001825
Ian Rogersd81871c2011-10-03 13:57:23 -07001826 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001827 klass->SetStatus(Class::kStatusVerified);
1828 } else {
1829 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001830 Thread* self = Thread::Current();
1831 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1832 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001833 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001834 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001835 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001836 }
jeffhao98eacac2011-09-14 16:11:53 -07001837}
1838
Ian Rogersc2b44472011-12-14 21:17:17 -08001839static void CheckProxyConstructor(Method* constructor);
1840static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1841
Jesse Wilson95caa792011-10-12 18:14:17 -04001842Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001843 ClassLoader* loader, ObjectArray<Method>* methods,
1844 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001845 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001846 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001847 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001848 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001849 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001850 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001851 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001852 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001853 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001854 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001855
1856 klass->SetStatus(Class::kStatusIdx);
1857
1858 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1859
1860 // Create static field that holds throws, instance fields are inherited
1861 klass->SetSFields(AllocObjectArray<Field>(1));
1862 SirtRef<Field> sfield(AllocField());
1863 klass->SetStaticField(0, sfield.get());
1864 sfield->SetDexFieldIndex(-1);
1865 sfield->SetDeclaringClass(klass.get());
1866 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001867
Ian Rogers466bb252011-10-14 03:29:56 -07001868 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001869 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001870 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001871
Ian Rogers466bb252011-10-14 03:29:56 -07001872 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001873 size_t num_virtual_methods = methods->GetLength();
1874 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1875 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001876 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001877 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001878 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001879
1880 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1881 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1882 DCHECK(!Thread::Current()->IsExceptionPending());
1883
1884 // Link the fields and virtual methods, creating vtable and iftables
1885 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001886 DCHECK(Thread::Current()->IsExceptionPending());
1887 return NULL;
1888 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001889 sfield->SetObject(NULL, throws); // initialize throws field
1890 klass->SetStatus(Class::kStatusInitialized);
1891
1892 // sanity checks
1893#ifndef NDEBUG
1894 bool debug = true;
1895#else
1896 bool debug = false;
1897#endif
1898 if (debug) {
1899 CHECK(klass->GetIFields() == NULL);
1900 CheckProxyConstructor(klass->GetDirectMethod(0));
1901 for (size_t i = 0; i < num_virtual_methods; ++i) {
1902 SirtRef<Method> prototype(methods->Get(i));
1903 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1904 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001905 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08001906 throws_field_name += name->ToModifiedUtf8();
1907 throws_field_name += ".throws";
1908 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1909
1910 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1911 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1912 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001913 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001914}
1915
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001916std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1917 DCHECK(proxy_class->IsProxyClass());
1918 String* name = proxy_class->GetName();
1919 DCHECK(name != NULL);
1920 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1921}
1922
1923
1924Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001925 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001926 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001927 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001928 Method* proxy_constructor = proxy_direct_methods->Get(2);
1929 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1930 // code_ too)
1931 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1932 // Make this constructor public and fix the class to be our Proxy version
1933 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001934 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001935 return constructor;
1936}
1937
1938static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001939 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001940 MethodHelper mh(constructor);
1941 CHECK_STREQ(mh.GetName(), "<init>");
1942 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001943 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001944}
1945
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001946Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1947 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1948 // prototype method
1949 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1950 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001951 // as necessary
1952 Method* method = down_cast<Method*>(prototype->Clone());
1953
1954 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1955 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001956 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001957 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001958
Ian Rogers466bb252011-10-14 03:29:56 -07001959 // At runtime the method looks like a reference and argument saving method, clone the code
1960 // related parameters from this method.
1961 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1962 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1963 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1964 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1965 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001966 return method;
1967}
Jesse Wilson95caa792011-10-12 18:14:17 -04001968
Ian Rogersc2b44472011-12-14 21:17:17 -08001969static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001970 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001971 CHECK(!prototype->IsFinal());
1972 CHECK(method->IsFinal());
1973 CHECK(!method->IsAbstract());
1974 MethodHelper mh(method);
1975 const char* method_name = mh.GetName();
1976 const char* method_shorty = mh.GetShorty();
1977 Class* method_return = mh.GetReturnType();
1978
1979 mh.ChangeMethod(prototype.get());
1980
1981 CHECK_STREQ(mh.GetName(), method_name);
1982 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001983
1984 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001985 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001986}
1987
Brian Carlstrom25c33252011-09-18 15:58:35 -07001988bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001989 CHECK(klass->IsResolved() || klass->IsErroneous())
1990 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001991
Carl Shapirob5573532011-07-12 18:22:59 -07001992 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001993
Brian Carlstrom25c33252011-09-18 15:58:35 -07001994 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001995 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001996 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001997 ObjectLock lock(klass);
1998
Brian Carlstromd1422f82011-09-28 11:37:09 -07001999 if (klass->GetStatus() == Class::kStatusInitialized) {
2000 return true;
2001 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002002
Brian Carlstromd1422f82011-09-28 11:37:09 -07002003 if (klass->IsErroneous()) {
2004 ThrowEarlierClassFailure(klass);
2005 return false;
2006 }
2007
2008 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002009 VerifyClass(klass);
2010 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002011 return false;
2012 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002013 }
2014
Brian Carlstrom25c33252011-09-18 15:58:35 -07002015 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2016 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002017 // if the class has a <clinit> but we can't run it during compilation,
2018 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07002019 return false;
2020 }
2021
Brian Carlstromd1422f82011-09-28 11:37:09 -07002022 // If the class is kStatusInitializing, either this thread is
2023 // initializing higher up the stack or another thread has beat us
2024 // to initializing and we need to wait. Either way, this
2025 // invocation of InitializeClass will not be responsible for
2026 // running <clinit> and will return.
2027 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002028 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002029 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002030 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002031 return true;
2032 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002033 // No. That's fine. Wait for another thread to finish initializing.
2034 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002035 }
2036
2037 if (!ValidateSuperClassDescriptors(klass)) {
2038 klass->SetStatus(Class::kStatusError);
2039 return false;
2040 }
2041
Brian Carlstromd1422f82011-09-28 11:37:09 -07002042 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002043
Elliott Hughesdcc24742011-09-07 14:02:44 -07002044 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002045 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002046 }
2047
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002048 uint64_t t0 = NanoTime();
2049
Brian Carlstrom25c33252011-09-18 15:58:35 -07002050 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002051 return false;
2052 }
2053
2054 InitializeStaticFields(klass);
2055
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002056 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002057 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002058 }
2059
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002060 uint64_t t1 = NanoTime();
2061
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002062 {
2063 ObjectLock lock(klass);
2064
2065 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002066 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002067 klass->SetStatus(Class::kStatusError);
2068 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002069 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2070 RuntimeStats* thread_stats = self->GetStats();
2071 ++global_stats->class_init_count;
2072 ++thread_stats->class_init_count;
2073 global_stats->class_init_time_ns += (t1 - t0);
2074 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002075 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002076 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002077 ClassHelper kh(klass);
2078 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002079 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002080 }
2081 lock.NotifyAll();
2082 }
2083
2084 return true;
2085}
2086
Brian Carlstromd1422f82011-09-28 11:37:09 -07002087bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2088 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002089 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002090 lock.Wait();
2091
2092 // When we wake up, repeat the test for init-in-progress. If
2093 // there's an exception pending (only possible if
2094 // "interruptShouldThrow" was set), bail out.
2095 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002096 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002097 klass->SetStatus(Class::kStatusError);
2098 return false;
2099 }
2100 // Spurious wakeup? Go back to waiting.
2101 if (klass->GetStatus() == Class::kStatusInitializing) {
2102 continue;
2103 }
2104 if (klass->IsErroneous()) {
2105 // The caller wants an exception, but it was thrown in a
2106 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002107 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002108 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002109 return false;
2110 }
2111 if (klass->IsInitialized()) {
2112 return true;
2113 }
2114 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2115 }
2116 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2117}
2118
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002119bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2120 if (klass->IsInterface()) {
2121 return true;
2122 }
2123 // begin with the methods local to the superclass
2124 if (klass->HasSuperClass() &&
2125 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2126 const Class* super = klass->GetSuperClass();
2127 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002128 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002129 if (method != super->GetVirtualMethod(i) &&
2130 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002131 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2132
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002133 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2134 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2135 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002136 return false;
2137 }
2138 }
2139 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002140 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2141 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2142 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002143 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2144 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002145 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002146 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002147 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002148 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2149
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002150 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2151 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2152 PrettyMethod(method).c_str(),
2153 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002154 return false;
2155 }
2156 }
2157 }
2158 }
2159 return true;
2160}
2161
2162bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002163 const Class* klass1,
2164 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002165 if (klass1 == klass2) {
2166 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002167 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002168 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002169 const DexFile::ProtoId& proto_id =
2170 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002171 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2172 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002173 if (descriptor == NULL) {
2174 break;
2175 }
2176 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2177 // Found a non-primitive type.
2178 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2179 return false;
2180 }
2181 }
2182 }
2183 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002184 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002185 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002186 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002187 return false;
2188 }
2189 }
2190 return true;
2191}
2192
2193// Returns true if classes referenced by the descriptor are the
2194// same classes in klass1 as they are in klass2.
2195bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002196 const Class* klass1,
2197 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002198 CHECK(descriptor != NULL);
2199 CHECK(klass1 != NULL);
2200 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002201 if (klass1 == klass2) {
2202 return true;
2203 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002204 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002205 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002206 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002207 // TODO: found2 == NULL
2208 // TODO: lookup found1 in initiating loader list
2209 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002210 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002211 return found1 == found2;
2212 } else {
2213 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002214 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002215}
2216
Brian Carlstrom25c33252011-09-18 15:58:35 -07002217bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002218 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002219 if (!klass->IsInterface() && klass->HasSuperClass()) {
2220 Class* super_class = klass->GetSuperClass();
2221 if (super_class->GetStatus() != Class::kStatusInitialized) {
2222 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002223 Thread* self = Thread::Current();
2224 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002225 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002226 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002227 // TODO: check for a pending exception
2228 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002229 if (!can_run_clinit) {
2230 // Don't set status to error when we can't run <clinit>.
2231 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2232 klass->SetStatus(Class::kStatusVerified);
2233 return false;
2234 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002235 klass->SetStatus(Class::kStatusError);
2236 klass->NotifyAll();
2237 return false;
2238 }
2239 }
2240 }
2241 return true;
2242}
2243
Brian Carlstrom25c33252011-09-18 15:58:35 -07002244bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002245 CHECK(c != NULL);
2246 if (c->IsInitialized()) {
2247 return true;
2248 }
2249
Elliott Hughes5f791332011-09-15 17:45:30 -07002250 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002251 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002252 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002253 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002254}
2255
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002256void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002257 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002258 const ClassLoader* cl = c->GetClassLoader();
2259 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002260 ClassDataItemIterator it(dex_file, class_data);
2261 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2262 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002263 }
2264}
2265
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002266void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002267 size_t num_static_fields = klass->NumStaticFields();
2268 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002269 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002270 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002271 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002272 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002273 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002274 return;
2275 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002276 ClassHelper kh(klass);
2277 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002278 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002279 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002280 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002281
Ian Rogers0571d352011-11-03 19:51:38 -07002282 if (it.HasNext()) {
2283 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2284 std::map<uint32_t, Field*> field_map;
2285 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2286 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2287 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002288 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002289 }
2290}
2291
Ian Rogersc2b44472011-12-14 21:17:17 -08002292bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002293 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 if (!LinkSuperClass(klass)) {
2295 return false;
2296 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002297 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002298 return false;
2299 }
2300 if (!LinkInstanceFields(klass)) {
2301 return false;
2302 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002303 if (!LinkStaticFields(klass)) {
2304 return false;
2305 }
2306 CreateReferenceInstanceOffsets(klass);
2307 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002308 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2309 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002310 return true;
2311}
2312
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002313bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002314 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002315 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2316 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002317 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002318 uint16_t super_class_idx = class_def->superclass_idx_;
2319 if (super_class_idx != DexFile::kDexNoIndex16) {
2320 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002321 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002322 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002323 return false;
2324 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002325 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002326 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002327 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2328 if (interfaces != NULL) {
2329 for (size_t i = 0; i < interfaces->Size(); i++) {
2330 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2331 Class* interface = ResolveType(dex_file, idx, klass.get());
2332 if (interface == NULL) {
2333 DCHECK(Thread::Current()->IsExceptionPending());
2334 return false;
2335 }
2336 // Verify
2337 if (!klass->CanAccess(interface)) {
2338 // TODO: the RI seemed to ignore this in my testing.
2339 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2340 "Interface %s implemented by class %s is inaccessible",
2341 PrettyDescriptor(interface).c_str(),
2342 PrettyDescriptor(klass.get()).c_str());
2343 return false;
2344 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002345 }
2346 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002347 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002348 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002349 return true;
2350}
2351
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002352bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002353 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002354 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002355 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002356 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002357 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002358 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002359 return false;
2360 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002361 return true;
2362 }
2363 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002364 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002365 return false;
2366 }
2367 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002368 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002369 Thread* thread = Thread::Current();
2370 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002371 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002372 PrettyDescriptor(super).c_str(),
2373 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002374 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002375 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002376 return false;
2377 }
2378 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002379 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002380 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002381 PrettyDescriptor(super).c_str(),
2382 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002383 return false;
2384 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002385
2386 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2387 if (super->IsFinalizable()) {
2388 klass->SetFinalizable();
2389 }
2390
Elliott Hughes2da50362011-10-10 16:57:08 -07002391 // Inherit reference flags (if any) from the superclass.
2392 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2393 if (reference_flags != 0) {
2394 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2395 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002396 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002397 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002398 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002399 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002400 return false;
2401 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002402
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002403#ifndef NDEBUG
2404 // Ensure super classes are fully resolved prior to resolving fields..
2405 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002406 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002407 super = super->GetSuperClass();
2408 }
2409#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002410 return true;
2411}
2412
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002413// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002414bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002415 if (klass->IsInterface()) {
2416 // No vtable.
2417 size_t count = klass->NumVirtualMethods();
2418 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002419 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002420 return false;
2421 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002422 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002423 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002424 }
jeffhaobdb76512011-09-07 11:43:16 -07002425 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002426 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002427 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002428 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002429 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 }
2431 return true;
2432}
2433
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002434bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002435 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002436 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2437 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002438 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002439 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002440 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002441 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002442 MethodHelper local_mh(NULL, this);
2443 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002444 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002445 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002446 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002447 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002448 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002449 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002450 super_mh.ChangeMethod(super_method);
2451 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002452 // Verify
2453 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002454 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002455 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002456 PrettyDescriptor(klass.get()).c_str(),
2457 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002458 return false;
2459 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002460 vtable->Set(j, local_method);
2461 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002462 break;
2463 }
2464 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002465 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002466 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002467 vtable->Set(actual_count, local_method);
2468 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002469 actual_count += 1;
2470 }
2471 }
2472 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002473 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002474 return false;
2475 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002476 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002477 CHECK_LE(actual_count, max_count);
2478 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002479 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002480 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002481 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002482 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002483 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002484 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002485 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002486 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002487 return false;
2488 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002489 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002490 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002491 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2492 vtable->Set(i, virtual_method);
2493 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002494 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002495 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002496 }
2497 return true;
2498}
2499
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002500bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002501 size_t super_ifcount;
2502 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002503 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002504 } else {
2505 super_ifcount = 0;
2506 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002507 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002508 ClassHelper kh(klass.get(), this);
2509 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2510 ifcount += num_interfaces;
2511 for (size_t i = 0; i < num_interfaces; i++) {
2512 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2513 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002514 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002515 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002516 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002517 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002518 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519 return true;
2520 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002521 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002522 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002523 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2524 for (size_t i = 0; i < super_ifcount; i++) {
2525 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2526 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002527 }
2528 // Flatten the interface inheritance hierarchy.
2529 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002530 for (size_t i = 0; i < num_interfaces; i++) {
2531 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002532 DCHECK(interface != NULL);
2533 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002534 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002535 Thread* thread = Thread::Current();
2536 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002537 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002538 PrettyDescriptor(klass.get()).c_str(),
2539 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002540 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002541 return false;
2542 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002543 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002544 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002545 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002546 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2547 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002548 }
2549 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002550 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002551 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002552
2553 // If we're an interface, we don't need the vtable pointers, so we're done.
2554 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002555 return true;
2556 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002557 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002558 MethodHelper vtable_mh(NULL, this);
2559 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002560 for (size_t i = 0; i < ifcount; ++i) {
2561 InterfaceEntry* interface_entry = iftable->Get(i);
2562 Class* interface = interface_entry->GetInterface();
2563 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2564 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002565 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002566 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2567 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002568 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002569 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002570 // For each method listed in the interface's method list, find the
2571 // matching method in our class's method list. We want to favor the
2572 // subclass over the superclass, which just requires walking
2573 // back from the end of the vtable. (This only matters if the
2574 // superclass defines a private method and this class redefines
2575 // it -- otherwise it would use the same vtable slot. In .dex files
2576 // those don't end up in the virtual method table, so it shouldn't
2577 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002578 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2579 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002580 vtable_mh.ChangeMethod(vtable_method);
2581 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002582 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002583 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002584 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002585 return false;
2586 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002587 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002588 break;
2589 }
2590 }
2591 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002592 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002593 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002594 Method* mir_method = miranda_list[mir];
2595 vtable_mh.ChangeMethod(mir_method);
2596 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002597 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002598 break;
2599 }
2600 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002601 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002602 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002603 miranda_method.reset(AllocMethod());
2604 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2605 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002606 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002607 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002608 }
2609 }
2610 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002611 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002612 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002613 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002614 klass->SetVirtualMethods((old_method_count == 0)
2615 ? AllocObjectArray<Method>(new_method_count)
2616 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002617
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002618 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2619 CHECK(vtable != NULL);
2620 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002621 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002622 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002623 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002624 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002625 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002626 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2627 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2628 klass->SetVirtualMethod(old_method_count + i, method);
2629 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002630 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002631 // TODO: do not assign to the vtable field until it is fully constructed.
2632 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002633 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002634
2635 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2636 for (int i = 0; i < vtable->GetLength(); ++i) {
2637 CHECK(vtable->Get(i) != NULL);
2638 }
2639
2640// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2641
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002642 return true;
2643}
2644
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002645bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2646 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002647 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002648}
2649
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002650bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2651 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002652 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002653 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002654 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002655 return success;
2656}
2657
Brian Carlstromdbc05252011-09-09 01:59:59 -07002658struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002659 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002660 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002661 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002662 fh_->ChangeField(field1);
2663 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2664 fh_->ChangeField(field2);
2665 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002666 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2667 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2668 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2669 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002670 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2671 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2672 if (order1 != order2) {
2673 return order1 < order2;
2674 }
2675
2676 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002677 fh_->ChangeField(field1);
2678 StringPiece name1(fh_->GetName());
2679 fh_->ChangeField(field2);
2680 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002681 return name1 < name2;
2682 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002683
2684 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002685};
2686
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002687bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002688 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002689 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002690
2691 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002692 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002693
2694 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002695 size_t size;
2696 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002697 if (is_static) {
2698 size = klass->GetClassSize();
2699 field_offset = Class::FieldsOffset();
2700 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002701 Class* super_class = klass->GetSuperClass();
2702 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002703 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002704 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002705 }
2706 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002707 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002708
Brian Carlstromdbc05252011-09-09 01:59:59 -07002709 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002710
Brian Carlstromdbc05252011-09-09 01:59:59 -07002711 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002712 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002713 std::deque<Field*> grouped_and_sorted_fields;
2714 for (size_t i = 0; i < num_fields; i++) {
2715 grouped_and_sorted_fields.push_back(fields->Get(i));
2716 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002717 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002718 std::sort(grouped_and_sorted_fields.begin(),
2719 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002720 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002721
2722 // References should be at the front.
2723 size_t current_field = 0;
2724 size_t num_reference_fields = 0;
2725 for (; current_field < num_fields; current_field++) {
2726 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002727 fh.ChangeField(field);
2728 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002729 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002730 if (isPrimitive) {
2731 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002732 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002733 grouped_and_sorted_fields.pop_front();
2734 num_reference_fields++;
2735 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002736 field->SetOffset(field_offset);
2737 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002738 }
2739
2740 // Now we want to pack all of the double-wide fields together. If
2741 // we're not aligned, though, we want to shuffle one 32-bit field
2742 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002743 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002744 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2745 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002746 fh.ChangeField(field);
2747 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002748 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2749 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002750 continue;
2751 }
2752 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002753 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002754 // drop the consumed field
2755 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2756 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002757 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002758 // whether we found a 32-bit field for padding or not, we advance
2759 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002760 }
2761
2762 // Alignment is good, shuffle any double-wide fields forward, and
2763 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002764 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002765 while (!grouped_and_sorted_fields.empty()) {
2766 Field* field = grouped_and_sorted_fields.front();
2767 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002768 fh.ChangeField(field);
2769 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002770 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002771 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002772 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002773 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002774 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002775 ? sizeof(uint64_t)
2776 : sizeof(uint32_t)));
2777 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002778 }
2779
Elliott Hughesadb460d2011-10-05 17:02:34 -07002780 // 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 -08002781 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2782 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002783 // We know there are no non-reference fields in the Reference classes, and we know
2784 // that 'referent' is alphabetically last, so this is easy...
2785 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002786 fh.ChangeField(fields->Get(num_fields - 1));
2787 StringPiece name(fh.GetName());
2788 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002789 --num_reference_fields;
2790 }
2791
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002792#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002793 // Make sure that all reference fields appear before
2794 // non-reference fields, and all double-wide fields are aligned.
2795 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002796 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002797 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002798 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002799 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002800 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002801 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002802 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2803 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002804 fh.ChangeField(field);
2805 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002806 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002807 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002808 is_primitive = true; // We lied above, so we have to expect a lie here.
2809 }
2810 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002811 if (!seen_non_ref) {
2812 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002813 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002814 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002815 } else {
2816 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002817 }
2818 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002819 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002820 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002821 }
2822#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002823 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002824 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002825 if (is_static) {
2826 klass->SetNumReferenceStaticFields(num_reference_fields);
2827 klass->SetClassSize(size);
2828 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002829 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002830 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002831 klass->SetObjectSize(size);
2832 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002833 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002834 return true;
2835}
2836
2837// Set the bitmap of reference offsets, refOffsets, from the ifields
2838// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002839void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002840 uint32_t reference_offsets = 0;
2841 Class* super_class = klass->GetSuperClass();
2842 if (super_class != NULL) {
2843 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002844 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002845 if (reference_offsets == CLASS_WALK_SUPER) {
2846 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002847 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002848 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002849 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002850 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002851}
2852
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002853void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002854 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002855}
2856
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002857void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002858 uint32_t reference_offsets) {
2859 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002860 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2861 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002862 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002863 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002864 // All of the fields that contain object references are guaranteed
2865 // to be at the beginning of the fields list.
2866 for (size_t i = 0; i < num_reference_fields; ++i) {
2867 // Note that byte_offset is the offset from the beginning of
2868 // object, not the offset into instance data
2869 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002870 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002871 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2872 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2873 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002874 CHECK_NE(new_bit, 0U);
2875 reference_offsets |= new_bit;
2876 } else {
2877 reference_offsets = CLASS_WALK_SUPER;
2878 break;
2879 }
2880 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002881 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002882 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002883 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002884 } else {
2885 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002886 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002887}
2888
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002889String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002890 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002891 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002892 if (resolved != NULL) {
2893 return resolved;
2894 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002895 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2896 int32_t utf16_length = dex_file.GetStringLength(string_id);
2897 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002898 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002899 dex_cache->SetResolvedString(string_idx, string);
2900 return string;
2901}
2902
2903Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002904 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002905 DexCache* dex_cache,
2906 const ClassLoader* class_loader) {
2907 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002908 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002909 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002910 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002911 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002912 // TODO: we used to throw here if resolved's class loader was not the
2913 // boot class loader. This was to permit different classes with the
2914 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002915 dex_cache->SetResolvedType(type_idx, resolved);
2916 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08002917 CHECK(Thread::Current()->IsExceptionPending())
2918 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002919 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002920 }
2921 return resolved;
2922}
2923
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002924Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2925 uint32_t method_idx,
2926 DexCache* dex_cache,
2927 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002928 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002929 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2930 if (resolved != NULL) {
2931 return resolved;
2932 }
2933 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2934 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2935 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002936 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002937 return NULL;
2938 }
2939
Ian Rogers0571d352011-11-03 19:51:38 -07002940 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2941 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002942 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002943 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002944 } else if (klass->IsInterface()) {
2945 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002946 } else {
2947 resolved = klass->FindVirtualMethod(name, signature);
2948 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002949 if (resolved != NULL) {
2950 dex_cache->SetResolvedMethod(method_idx, resolved);
2951 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002952 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002953 }
2954 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002955}
2956
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002957Field* ClassLinker::ResolveField(const DexFile& dex_file,
2958 uint32_t field_idx,
2959 DexCache* dex_cache,
2960 const ClassLoader* class_loader,
2961 bool is_static) {
2962 Field* resolved = dex_cache->GetResolvedField(field_idx);
2963 if (resolved != NULL) {
2964 return resolved;
2965 }
2966 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2967 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2968 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002969 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002970 return NULL;
2971 }
2972
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002973 const char* name = dex_file.GetFieldName(field_id);
2974 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002975 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002976 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002977 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002978 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002979 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002980 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002981 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002982 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002983 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2984 }
2985 return resolved;
2986}
2987
2988Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2989 uint32_t field_idx,
2990 DexCache* dex_cache,
2991 const ClassLoader* class_loader) {
2992 Field* resolved = dex_cache->GetResolvedField(field_idx);
2993 if (resolved != NULL) {
2994 return resolved;
2995 }
2996 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2997 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2998 if (klass == NULL) {
2999 DCHECK(Thread::Current()->IsExceptionPending());
3000 return NULL;
3001 }
3002
3003 const char* name = dex_file.GetFieldName(field_id);
3004 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3005 resolved = klass->FindField(name, type);
3006 if (resolved != NULL) {
3007 dex_cache->SetResolvedField(field_idx, resolved);
3008 } else {
3009 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003010 }
3011 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003012}
3013
Ian Rogersad25ac52011-10-04 19:13:33 -07003014const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3015 Class* declaring_class = referrer->GetDeclaringClass();
3016 DexCache* dex_cache = declaring_class->GetDexCache();
3017 const DexFile& dex_file = FindDexFile(dex_cache);
3018 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3019 return dex_file.GetShorty(method_id.proto_idx_);
3020}
3021
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003022void ClassLinker::DumpAllClasses(int flags) const {
3023 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3024 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3025 std::vector<Class*> all_classes;
3026 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003027 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003028 typedef Table::const_iterator It; // TODO: C++0x auto
3029 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3030 all_classes.push_back(it->second);
3031 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003032 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3033 all_classes.push_back(it->second);
3034 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003035 }
3036
3037 for (size_t i = 0; i < all_classes.size(); ++i) {
3038 all_classes[i]->DumpClass(std::cerr, flags);
3039 }
3040}
3041
Elliott Hughescac6cc72011-11-03 20:31:21 -07003042void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3043 MutexLock mu(classes_lock_);
3044 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3045 << classes_.size() << " allocated classes\n";
3046}
3047
Elliott Hughese27955c2011-08-26 15:21:24 -07003048size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003049 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003050 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003051}
3052
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003053pid_t ClassLinker::GetClassesLockOwner() {
3054 return classes_lock_.GetOwner();
3055}
3056
3057pid_t ClassLinker::GetDexLockOwner() {
3058 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003059}
3060
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003061void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3062 DCHECK(!init_done_);
3063
3064 DCHECK(klass != NULL);
3065 DCHECK(klass->GetClassLoader() == NULL);
3066
3067 DCHECK(class_roots_ != NULL);
3068 DCHECK(class_roots_->Get(class_root) == NULL);
3069 class_roots_->Set(class_root, klass);
3070}
3071
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003072} // namespace art