blob: df2e971b939daf948f86c10256c8683d40a3ca27 [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 Carlstromdbf05b72011-12-15 00:55:24 -08005#include <sys/types.h>
6#include <sys/wait.h>
7
Brian Carlstromdbc05252011-09-09 01:59:59 -07008#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07009#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070010#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070011#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070012
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070013#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070014#include "class_loader.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080015#include "debugger.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070016#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070017#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "dex_verifier.h"
19#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070020#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070021#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070022#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070023#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070024#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080026#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070027#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070028#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070029#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070030#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070031#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070032#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070033#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070034#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070036
37namespace art {
38
Elliott Hughes4a2b4172011-09-20 17:08:25 -070039namespace {
40
Elliott Hughes362f9bc2011-10-17 18:56:41 -070041void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070042void ThrowNoClassDefFoundError(const char* fmt, ...) {
43 va_list args;
44 va_start(args, fmt);
45 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
46 va_end(args);
47}
48
Elliott Hughes362f9bc2011-10-17 18:56:41 -070049void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070050void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070051 va_list args;
52 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070053 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070054 va_end(args);
55}
56
Elliott Hughes362f9bc2011-10-17 18:56:41 -070057void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070058void ThrowLinkageError(const char* fmt, ...) {
59 va_list args;
60 va_start(args, fmt);
61 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
62 va_end(args);
63}
64
Ian Rogers9f1ab122011-12-12 08:52:43 -080065void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
66 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080067 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070068 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080069 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
70 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080071 std::string location(kh.GetLocation());
72 if (!location.empty()) {
73 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070074 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070075 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070076}
77
Ian Rogersb067ac22011-12-13 18:05:09 -080078void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080079 const StringPiece& name) {
80 ClassHelper kh(c);
81 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080082 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080083 << " in class " << kh.GetDescriptor() << " or its superclasses";
84 std::string location(kh.GetLocation());
85 if (!location.empty()) {
86 msg << " (defined in " << location << ")";
87 }
88 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
89}
90
Elliott Hughes4a2b4172011-09-20 17:08:25 -070091void ThrowEarlierClassFailure(Class* c) {
92 /*
93 * The class failed to initialize on a previous attempt, so we want to throw
94 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
95 * failed in verification, in which case v2 5.4.1 says we need to re-throw
96 * the previous error.
97 */
98 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
99
100 if (c->GetVerifyErrorClass() != NULL) {
101 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800102 ClassHelper ve_ch(c->GetVerifyErrorClass());
103 std::string error_descriptor(ve_ch.GetDescriptor());
104 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700105 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800106 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700107 }
108}
109
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700110void WrapExceptionInInitializer() {
111 JNIEnv* env = Thread::Current()->GetJniEnv();
112
113 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
114 CHECK(cause.get() != NULL);
115
116 env->ExceptionClear();
117
118 // TODO: add java.lang.Error to JniConstants?
119 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
120 CHECK(error_class.get() != NULL);
121 if (env->IsInstanceOf(cause.get(), error_class.get())) {
122 // We only wrap non-Error exceptions; an Error can just be used as-is.
123 env->Throw(cause.get());
124 return;
125 }
126
127 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
128 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
129 CHECK(eiie_class.get() != NULL);
130
131 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
132 CHECK(mid != NULL);
133
134 ScopedLocalRef<jthrowable> eiie(env,
135 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
136 env->Throw(eiie.get());
137}
138
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800139static size_t Hash(const char* s) {
140 // This is the java.lang.String hashcode for convenience, not interoperability.
141 size_t hash = 0;
142 for (; *s != '\0'; ++s) {
143 hash = hash * 31 + *s;
144 }
145 return hash;
146}
147
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700148} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700149
Elliott Hughes418d20f2011-09-22 14:00:39 -0700150const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700151 "Ljava/lang/Class;",
152 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700153 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700154 "[Ljava/lang/Object;",
155 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700156 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700157 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700158 "Ljava/lang/reflect/Field;",
159 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700160 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700161 "Ljava/lang/ClassLoader;",
162 "Ldalvik/system/BaseDexClassLoader;",
163 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700164 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700165 "Z",
166 "B",
167 "C",
168 "D",
169 "F",
170 "I",
171 "J",
172 "S",
173 "V",
174 "[Z",
175 "[B",
176 "[C",
177 "[D",
178 "[F",
179 "[I",
180 "[J",
181 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700182 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700183};
184
Elliott Hughes5f791332011-09-15 17:45:30 -0700185class ObjectLock {
186 public:
187 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
188 CHECK(object != NULL);
189 obj_->MonitorEnter(self_);
190 }
191
192 ~ObjectLock() {
193 obj_->MonitorExit(self_);
194 }
195
196 void Wait() {
197 return Monitor::Wait(self_, obj_, 0, 0, false);
198 }
199
200 void Notify() {
201 obj_->Notify();
202 }
203
204 void NotifyAll() {
205 obj_->NotifyAll();
206 }
207
208 private:
209 Thread* self_;
210 Object* obj_;
211 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
212};
213
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800214ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700215 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800216 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700217 class_linker->Init(boot_class_path);
218 return class_linker.release();
219}
220
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800221ClassLinker* ClassLinker::Create(InternTable* intern_table) {
222 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700223 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700224 return class_linker.release();
225}
226
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800227ClassLinker::ClassLinker(InternTable* intern_table)
228 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700229 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700230 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700231 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700232 init_done_(false),
233 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700234 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700235}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700236
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700237void CreateClassPath(const std::string& class_path,
238 std::vector<const DexFile*>& class_path_vector) {
239 std::vector<std::string> parsed;
240 Split(class_path, ':', parsed);
241 for (size_t i = 0; i < parsed.size(); ++i) {
242 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700243 if (dex_file == NULL) {
244 LOG(WARNING) << "Failed to open dex file " << parsed[i];
245 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700246 class_path_vector.push_back(dex_file);
247 }
248 }
249}
250
251void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800252 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700253
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700254 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700255
Elliott Hughes30646832011-10-13 16:59:46 -0700256 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700257 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
258 CHECK(java_lang_Class.get() != NULL);
259 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700260 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700261 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700262
Elliott Hughes418d20f2011-09-22 14:00:39 -0700263 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700264 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
265 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700266
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700267 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700268 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
269 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700270 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700271 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700272 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700273
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700274 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700275 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
276 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700277
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700278 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700279 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700280
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700281 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
283 char_array_class->SetComponentType(char_class.get());
284 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700285
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700286 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700287 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
288 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700289 java_lang_String->SetObjectSize(sizeof(String));
290 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400291
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700292 // Create storage for root classes, save away our work so far (requires
293 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700294 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700295 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700296 SetClassRoot(kJavaLangClass, java_lang_Class.get());
297 SetClassRoot(kJavaLangObject, java_lang_Object.get());
298 SetClassRoot(kClassArrayClass, class_array_class.get());
299 SetClassRoot(kObjectArrayClass, object_array_class.get());
300 SetClassRoot(kCharArrayClass, char_array_class.get());
301 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302
303 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700304 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
305 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
306 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
307 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
308 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
309 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
310 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
311 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700312
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700313 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700314 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315
316 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700317 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700318 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700319 IntArray::SetArrayClass(int_array_class.get());
320 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700321
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700322 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700323
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700324 // setup boot_class_path_ and register class_path now that we can
325 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700326 std::vector<const DexFile*> boot_class_path_vector;
327 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700328 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700329 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
330 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700331 CHECK(dex_file != NULL);
332 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700333 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334
Elliott Hughes80609252011-09-23 17:24:51 -0700335 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700336 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700337 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700338 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700339 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700340 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
341
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700342 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
343 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700345 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700348
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700349 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700352 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700354 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700355
356 // now we can use FindSystemClass
357
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700358 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700359 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700360 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700361
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700362 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363 java_lang_Object->SetStatus(Class::kStatusNotReady);
364 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700365 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700366 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
367 java_lang_String->SetStatus(Class::kStatusNotReady);
368 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700369 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700370 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
371
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700372 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700373 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
374 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
375
376 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
377 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
378
379 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700380 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381
382 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
383 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
384
385 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700386 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700387
388 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
389 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
390
391 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
392 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
393
394 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
395 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
396
Elliott Hughes418d20f2011-09-22 14:00:39 -0700397 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700398 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700399
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700400 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700401 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700402
403 // Setup the single, global copies of "interfaces" and "iftable"
404 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
405 CHECK(java_lang_Cloneable != NULL);
406 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
407 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700408 // We assume that Cloneable/Serializable don't have superinterfaces --
409 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700410 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800411 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
412 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700413
Elliott Hughes418d20f2011-09-22 14:00:39 -0700414 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800415 ClassHelper kh(class_array_class.get(), this);
416 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
417 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
418 kh.ChangeClass(object_array_class.get());
419 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
420 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700421 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700422 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700423 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700424 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425
Elliott Hughes80609252011-09-23 17:24:51 -0700426 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
427 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700428 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700429
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700430 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700431 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700432 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700433
434 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700435 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700436 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700437
Ian Rogers466bb252011-10-14 03:29:56 -0700438 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
439
440 // Create java.lang.reflect.Proxy root
441 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
442 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
443
Brian Carlstrom1f870082011-08-23 16:02:11 -0700444 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700445 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
446 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700447 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700448 java_lang_ref_FinalizerReference->SetAccessFlags(
449 java_lang_ref_FinalizerReference->GetAccessFlags() |
450 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700451 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452 java_lang_ref_PhantomReference->SetAccessFlags(
453 java_lang_ref_PhantomReference->GetAccessFlags() |
454 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700455 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700456 java_lang_ref_SoftReference->SetAccessFlags(
457 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700458 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459 java_lang_ref_WeakReference->SetAccessFlags(
460 java_lang_ref_WeakReference->GetAccessFlags() |
461 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700462
Brian Carlstromaded5f72011-10-07 17:15:04 -0700463 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700464 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700465 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700466 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
467
468 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
469 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
470 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
471
472 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
473 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
474 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
475 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
476
477 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700478 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
479 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700480 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700481
Brian Carlstroma663ea52011-08-19 23:33:41 -0700482 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700483
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800484 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700485}
486
487void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800488 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700489
490 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700491 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700492 // as the types of the field can't be resolved prior to the runtime being
493 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700494 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700495 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700496 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
497
Elliott Hughesadb460d2011-10-05 17:02:34 -0700498 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
499
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800500 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
501
Brian Carlstrom16192862011-09-12 17:50:06 -0700502 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800503 FieldHelper fh(pendingNext, this);
504 CHECK_STREQ(fh.GetName(), "pendingNext");
505 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
506 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700507
508 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800509 fh.ChangeField(queue);
510 CHECK_STREQ(fh.GetName(), "queue");
511 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
512 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700513
514 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800515 fh.ChangeField(queueNext);
516 CHECK_STREQ(fh.GetName(), "queueNext");
517 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
518 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700519
520 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800521 fh.ChangeField(referent);
522 CHECK_STREQ(fh.GetName(), "referent");
523 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
524 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700525
526 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800527 fh.ChangeField(zombie);
528 CHECK_STREQ(fh.GetName(), "zombie");
529 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
530 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700531
532 Heap::SetReferenceOffsets(referent->GetOffset(),
533 queue->GetOffset(),
534 queueNext->GetOffset(),
535 pendingNext->GetOffset(),
536 zombie->GetOffset());
537
Brian Carlstroma663ea52011-08-19 23:33:41 -0700538 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700539 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700540 ClassRoot class_root = static_cast<ClassRoot>(i);
541 Class* klass = GetClassRoot(class_root);
542 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700543 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700544 // note SetClassRoot does additional validation.
545 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700546 }
547
Elliott Hughes92f14b22011-10-06 12:29:54 -0700548 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700549
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700550 // disable the slow paths in FindClass and CreatePrimitiveClass now
551 // that Object, Class, and Object[] are setup
552 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700553
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800554 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700555}
556
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700557void ClassLinker::RunRootClinits() {
558 Thread* self = Thread::Current();
559 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
560 Class* c = GetClassRoot(ClassRoot(i));
561 if (!c->IsArrayClass() && !c->IsPrimitive()) {
562 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700563 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700564 }
565 }
566}
567
jeffhao262bf462011-10-20 18:36:32 -0700568const OatFile* ClassLinker::GenerateOatFile(const std::string& filename) {
569 std::string oat_filename(GetArtCacheFilenameOrDie(OatFile::DexFilenameToOatFilename(filename)));
570
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800571 std::string dex2oat_string("/system/bin/dex2oat");
572#ifndef NDEBUG
573 dex2oat_string += 'd';
574#endif
575 const char* dex2oat = dex2oat_string.c_str();
576
577 const char* class_path = Runtime::Current()->GetClassPath().c_str();
578
579 std::string boot_image_option_string("--boot-image=");
580 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
581 const char* boot_image_option = boot_image_option_string.c_str();
582
583 std::string dex_file_option_string("--dex-file=");
584 dex_file_option_string += filename;
585 const char* dex_file_option = dex_file_option_string.c_str();
586
587 std::string oat_file_option_string("--oat=");
588 oat_file_option_string += oat_filename;
589 const char* oat_file_option = oat_file_option_string.c_str();
590
jeffhao262bf462011-10-20 18:36:32 -0700591 // fork and exec dex2oat
592 pid_t pid = fork();
593 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800594 // no allocation allowed between fork and exec
595 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700596 "--runtime-arg", "-Xms64m",
597 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500598 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800599 "--runtime-arg", class_path,
600 boot_image_option,
601 dex_file_option,
602 oat_file_option,
jeffhao262bf462011-10-20 18:36:32 -0700603 NULL);
604
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800605 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
jeffhao262bf462011-10-20 18:36:32 -0700606 return NULL;
607 } else {
608 // wait for dex2oat to finish
609 int status;
610 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
611 if (got_pid != pid) {
612 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
613 return NULL;
614 }
615 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800616 LOG(ERROR) << dex2oat << " failed with dex-file=" << filename;
jeffhao262bf462011-10-20 18:36:32 -0700617 return NULL;
618 }
619 }
620 return OatFile::Open(oat_filename, "", NULL);
621}
622
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700623OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700624 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700625 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800626 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700627 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800628 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
629 // check the down cast
630 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700631 std::string oat_filename;
632 oat_filename += runtime->GetHostPrefix();
633 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700634 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700635 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700636 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700637 return NULL;
638 }
639 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
640 uint32_t image_oat_checksum = image_header.GetOatChecksum();
641 if (oat_checksum != image_oat_checksum) {
642 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
643 << " to expected oat checksum " << std::hex << oat_checksum
644 << " in image";
645 return NULL;
646 }
647 oat_files_.push_back(oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800648 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700649 return oat_file;
650}
651
Brian Carlstromae826982011-11-09 01:33:42 -0800652const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
653 for (size_t i = 0; i < oat_files_.size(); i++) {
654 const OatFile* oat_file = oat_files_[i];
655 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800656 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800657 return oat_file;
658 }
659 }
660 return NULL;
661}
662
663const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700664 MutexLock mu(dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800665 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
666 if (oat_file != NULL) {
667 return oat_file;
668 }
669
670 oat_file = FindOatFileFromOatLocation(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
jeffhao262bf462011-10-20 18:36:32 -0700671 if (oat_file != NULL) {
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700672 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
673 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
674 return oat_file;
675 }
676 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
677 << " is older than " << dex_file.GetLocation() << " --- regenerating";
Elliott Hughes234da572011-11-03 22:13:06 -0700678 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
679 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
680 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700681 // Fall through...
jeffhao262bf462011-10-20 18:36:32 -0700682 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700683 // Generate oat file if it wasn't found or was obsolete.
jeffhao262bf462011-10-20 18:36:32 -0700684 oat_file = GenerateOatFile(dex_file.GetLocation());
685 if (oat_file == NULL) {
686 LOG(ERROR) << "Failed to generate oat file from dex file " << dex_file.GetLocation();
687 return NULL;
688 }
689 oat_files_.push_back(oat_file);
690 return oat_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700691}
692
Brian Carlstromae826982011-11-09 01:33:42 -0800693const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700694 for (size_t i = 0; i < oat_files_.size(); i++) {
695 const OatFile* oat_file = oat_files_[i];
696 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800697 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700698 return oat_file;
699 }
700 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700701 return NULL;
702}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700703
Brian Carlstromae826982011-11-09 01:33:42 -0800704const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
705 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700706 if (oat_file != NULL) {
707 return oat_file;
708 }
709
Brian Carlstromae826982011-11-09 01:33:42 -0800710 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700711 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800712 if (oat_location.empty() || oat_location[0] != '/') {
713 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700714 return NULL;
715 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700716
Brian Carlstroma9f19782011-10-13 00:14:47 -0700717 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800718 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800719 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700720 if (oat_file != NULL) {
721 return oat_file;
722 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700723 oat_file = OatFile::Open(cache_location, "", NULL);
724 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800725 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700726 return NULL;
727 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700728 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700729
Brian Carlstromae826982011-11-09 01:33:42 -0800730 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromfad71432011-10-16 20:25:10 -0700731 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700732 return oat_file;
733}
734
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700735void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700736 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800737 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700738 CHECK(!init_done_);
739
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700740 const std::vector<Space*>& spaces = Heap::GetSpaces();
741 for (size_t i = 0; i < spaces.size(); i++) {
742 Space* space = spaces[i] ;
743 if (space->IsImageSpace()) {
744 OatFile* oat_file = OpenOat(space);
745 CHECK(oat_file != NULL) << "Failed to open oat file for image";
746 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
747 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
748
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800749 if (i == 0) {
750 // Special case of setting up the String class early so that we can test arbitrary objects
751 // as being Strings or not
752 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
753 ->AsObjectArray<Class>()->Get(kJavaLangString);
754 String::SetClass(java_lang_String);
755 }
756
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700757 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
758 static_cast<uint32_t>(dex_caches->GetLength()));
759 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700760 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800761 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700762
763 std::string dex_filename;
764 dex_filename += runtime->GetHostPrefix();
765 dex_filename += dex_file_location;
766 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
767 if (dex_file == NULL) {
768 LOG(FATAL) << "Failed to open dex file " << dex_filename
769 << " referenced from oat file as " << dex_file_location;
770 }
771
Brian Carlstromaded5f72011-10-07 17:15:04 -0700772 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
773 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700774
Brian Carlstromdf143242011-10-10 18:05:34 -0700775 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700776 }
777 }
778 }
779
Brian Carlstroma663ea52011-08-19 23:33:41 -0700780 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
781 DCHECK(heap_bitmap != NULL);
782
Brian Carlstroma663ea52011-08-19 23:33:41 -0700783 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700784 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700785
786 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700787 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
788 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700789
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800790 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700791 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
792 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800793 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700794 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700795 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700796 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
797 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
798 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
799 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
800 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
801 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
802 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
803 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700804 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700805 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700806
807 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700808
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800809 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700810}
811
Brian Carlstrom78128a62011-09-15 17:21:19 -0700812void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700813 DCHECK(obj != NULL);
814 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700815 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700816
Elliott Hughesdbb40792011-11-18 17:05:22 -0800817 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700818 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700819 return;
820 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700821 if (obj->IsClass()) {
822 // restore class to ClassLinker::classes_ table
823 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800824 ClassHelper kh(klass, class_linker);
825 bool success = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
Ian Rogers5d76c432011-10-31 21:42:49 -0700826 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700827 return;
828 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700829}
830
831// Keep in sync with InitCallback. Anything we visit, we need to
832// reinit references to when reinitializing a ClassLinker from a
833// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700834void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
835 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700836
837 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700838 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700839 }
840
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700841 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700842 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700843 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700844 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700845 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700846 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700847 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700848 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700849
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700850 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700851}
852
Elliott Hughesa2155262011-11-16 16:26:58 -0800853void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
854 MutexLock mu(classes_lock_);
855 typedef Table::const_iterator It; // TODO: C++0x auto
856 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
857 if (!visitor(it->second, arg)) {
858 return;
859 }
860 }
861 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
862 if (!visitor(it->second, arg)) {
863 return;
864 }
865 }
866}
867
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700868ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700869 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700870 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700871 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700872 BooleanArray::ResetArrayClass();
873 ByteArray::ResetArrayClass();
874 CharArray::ResetArrayClass();
875 DoubleArray::ResetArrayClass();
876 FloatArray::ResetArrayClass();
877 IntArray::ResetArrayClass();
878 LongArray::ResetArrayClass();
879 ShortArray::ResetArrayClass();
880 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700881 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700882 STLDeleteElements(&boot_class_path_);
883 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700884}
885
886DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700887 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
888 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700889 return NULL;
890 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700891 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
892 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700893 return NULL;
894 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700895 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
896 if (strings.get() == NULL) {
897 return NULL;
898 }
899 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
900 if (types.get() == NULL) {
901 return NULL;
902 }
903 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
904 if (methods.get() == NULL) {
905 return NULL;
906 }
907 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
908 if (fields.get() == NULL) {
909 return NULL;
910 }
911 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
912 if (code_and_direct_methods.get() == NULL) {
913 return NULL;
914 }
915 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
916 if (initialized_static_storage.get() == NULL) {
917 return NULL;
918 }
919
920 dex_cache->Init(location.get(),
921 strings.get(),
922 types.get(),
923 methods.get(),
924 fields.get(),
925 code_and_direct_methods.get(),
926 initialized_static_storage.get());
927 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700928}
929
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700930CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
931 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700932}
933
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700934InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
935 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700936 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
937 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700938 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700939 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700940}
941
Brian Carlstrom4873d462011-08-21 15:23:39 -0700942Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
943 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700944 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700945 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700946 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700947 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700948}
949
Brian Carlstrom4873d462011-08-21 15:23:39 -0700950Class* ClassLinker::AllocClass(size_t class_size) {
951 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700952}
953
Jesse Wilson35baaab2011-08-10 16:18:03 -0400954Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700955 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700956}
957
958Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700959 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700960}
961
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700962ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
963 return ObjectArray<StackTraceElement>::Alloc(
964 GetClassRoot(kJavaLangStackTraceElementArrayClass),
965 length);
966}
967
Brian Carlstromaded5f72011-10-07 17:15:04 -0700968Class* EnsureResolved(Class* klass) {
969 DCHECK(klass != NULL);
970 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700971 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700972 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700973 ObjectLock lock(klass);
974 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700975 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700976 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800977 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700978 return NULL;
979 }
980 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700981 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700982 lock.Wait();
983 }
984 }
985 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700986 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700987 return NULL;
988 }
989 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700990 CHECK(klass->IsResolved()) << PrettyClass(klass);
991 CHECK(!self->IsExceptionPending())
992 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
993 return klass;
994}
995
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800996Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
997 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700998 Thread* self = Thread::Current();
999 DCHECK(self != NULL);
1000 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001001 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001002 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1003 // for primitive classes that aren't backed by dex files.
1004 return FindPrimitiveClass(descriptor[0]);
1005 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001006 // Find the class in the loaded classes table.
1007 Class* klass = LookupClass(descriptor, class_loader);
1008 if (klass != NULL) {
1009 return EnsureResolved(klass);
1010 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001011 // Class is not yet loaded.
1012 if (descriptor[0] == '[') {
1013 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001014
Jesse Wilson47daf872011-11-23 11:42:45 -05001015 } else if (class_loader == NULL) {
1016 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1017 if (pair.second != NULL) {
1018 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1019 }
1020
1021 } else if (ClassLoader::UseCompileTimeClassPath()) {
1022 // first try the boot class path
1023 Class* system_class = FindSystemClass(descriptor);
1024 if (system_class != NULL) {
1025 return system_class;
1026 }
1027 CHECK(self->IsExceptionPending());
1028 self->ClearException();
1029
1030 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001031 const std::vector<const DexFile*>& class_path
1032 = ClassLoader::GetCompileTimeClassPath(class_loader);
1033 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001034 if (pair.second != NULL) {
1035 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001036 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001037
1038 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001039 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001040 ScopedThreadStateChange(self, Thread::kNative);
1041 JNIEnv* env = self->GetJniEnv();
1042 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1043 CHECK(c.get() != NULL);
1044 // TODO: cache method?
1045 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1046 CHECK(mid != NULL);
1047 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1048 if (class_name_object.get() == NULL) {
1049 return NULL;
1050 }
1051 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1052 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
Ian Rogers6b0870d2011-12-15 19:38:12 -08001053 if (!env->ExceptionOccurred()) {
1054 return Decode<Class*>(env, result.get());
1055 } else {
1056 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1057 // TODO: initialize the cause of the NCDFE to this exception
1058 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001059 }
1060
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001061 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001062 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001063}
1064
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001065Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001066 const ClassLoader* class_loader,
1067 const DexFile& dex_file,
1068 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001069 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001070 // Load the class from the dex file.
1071 if (!init_done_) {
1072 // finish up init of hand crafted class_roots_
1073 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001074 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001075 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001076 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001077 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001078 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001079 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001080 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001081 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001082 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001083 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001084 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001085 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001086 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001087 }
1088 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001089 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001090 }
1091 klass->SetDexCache(FindDexCache(dex_file));
1092 LoadClass(dex_file, dex_class_def, klass, class_loader);
1093 // Check for a pending exception during load
1094 Thread* self = Thread::Current();
1095 if (self->IsExceptionPending()) {
1096 return NULL;
1097 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001098 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001099 klass->SetClinitThreadId(self->GetTid());
1100 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001101 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001102 if (!success) {
1103 // We may fail to insert if we raced with another thread.
1104 klass->SetClinitThreadId(0);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001105 klass.reset(LookupClass(descriptor.data(), class_loader));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001106 CHECK(klass.get() != NULL);
1107 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001108 }
1109 // Finish loading (if necessary) by finding parents
1110 CHECK(!klass->IsLoaded());
1111 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1112 // Loading failed.
1113 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001114 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001115 lock.NotifyAll();
1116 return NULL;
1117 }
1118 CHECK(klass->IsLoaded());
1119 // Link the class (if necessary)
1120 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001121 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001122 // Linking failed.
1123 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001124 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001125 lock.NotifyAll();
1126 return NULL;
1127 }
1128 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001129
1130 /*
1131 * We send CLASS_PREPARE events to the debugger from here. The
1132 * definition of "preparation" is creating the static fields for a
1133 * class and initializing them to the standard default values, but not
1134 * executing any code (that comes later, during "initialization").
1135 *
1136 * We did the static preparation in LinkClass.
1137 *
1138 * The class has been prepared and resolved but possibly not yet verified
1139 * at this point.
1140 */
1141 Dbg::PostClassPrepare(klass.get());
1142
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001143 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001144}
1145
Brian Carlstrom4873d462011-08-21 15:23:39 -07001146// Precomputes size that will be needed for Class, matching LinkStaticFields
1147size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1148 const DexFile::ClassDef& dex_class_def) {
1149 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001150 size_t num_ref = 0;
1151 size_t num_32 = 0;
1152 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001153 if (class_data != NULL) {
1154 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1155 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001156 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001157 char c = descriptor[0];
1158 if (c == 'L' || c == '[') {
1159 num_ref++;
1160 } else if (c == 'J' || c == 'D') {
1161 num_64++;
1162 } else {
1163 num_32++;
1164 }
1165 }
1166 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001167 // start with generic class data
1168 size_t size = sizeof(Class);
1169 // follow with reference fields which must be contiguous at start
1170 size += (num_ref * sizeof(uint32_t));
1171 // if there are 64-bit fields to add, make sure they are aligned
1172 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1173 if (num_32 != 0) {
1174 // use an available 32-bit field for padding
1175 num_32--;
1176 }
1177 size += sizeof(uint32_t); // either way, we are adding a word
1178 DCHECK_EQ(size, RoundUp(size, 8));
1179 }
1180 // tack on any 64-bit fields now that alignment is assured
1181 size += (num_64 * sizeof(uint64_t));
1182 // tack on any remaining 32-bit fields
1183 size += (num_32 * sizeof(uint32_t));
1184 return size;
1185}
1186
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001187void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001188 // Every kind of method should at least get an invoke stub from the oat_method.
1189 // non-abstract methods also get their code pointers.
1190 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001191 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001192
1193 if (method->IsAbstract()) {
1194 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1195 return;
1196 }
1197 if (method->IsNative()) {
1198 // unregistering restores the dlsym lookup stub
1199 method->UnregisterNative();
1200 return;
1201 }
1202}
1203
Brian Carlstromf615a612011-07-23 12:50:34 -07001204void ClassLinker::LoadClass(const DexFile& dex_file,
1205 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001206 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001207 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001208 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001209 CHECK(klass->GetDexCache() != NULL);
1210 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001211 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001212 CHECK(descriptor != NULL);
1213
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001214 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001215 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001216 // Make sure that none of our runtime-only flags are set.
1217 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001218 klass->SetAccessFlags(access_flags);
1219 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001220 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001221 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001222
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001223 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001224
Ian Rogers0571d352011-11-03 19:51:38 -07001225 // Load fields fields.
1226 const byte* class_data = dex_file.GetClassData(dex_class_def);
1227 if (class_data == NULL) {
1228 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001229 }
Ian Rogers0571d352011-11-03 19:51:38 -07001230 ClassDataItemIterator it(dex_file, class_data);
1231 if (it.NumStaticFields() != 0) {
1232 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1233 }
1234 if (it.NumInstanceFields() != 0) {
1235 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1236 }
1237 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1238 SirtRef<Field> sfield(AllocField());
1239 klass->SetStaticField(i, sfield.get());
1240 LoadField(dex_file, it, klass, sfield);
1241 }
1242 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1243 SirtRef<Field> ifield(AllocField());
1244 klass->SetInstanceField(i, ifield.get());
1245 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001246 }
1247
Brian Carlstromaded5f72011-10-07 17:15:04 -07001248 UniquePtr<const OatFile::OatClass> oat_class;
1249 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001250 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001251 if (oat_file != NULL) {
1252 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1253 if (oat_dex_file != NULL) {
1254 uint32_t class_def_index;
1255 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1256 CHECK(found) << descriptor;
1257 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001258 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001259 }
1260 }
1261 }
Ian Rogers0571d352011-11-03 19:51:38 -07001262 // Load methods.
1263 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001264 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001265 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001266 }
Ian Rogers0571d352011-11-03 19:51:38 -07001267 if (it.NumVirtualMethods() != 0) {
1268 // TODO: append direct methods to class object
1269 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001270 }
Ian Rogers0571d352011-11-03 19:51:38 -07001271 size_t method_index = 0;
1272 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1273 SirtRef<Method> method(AllocMethod());
1274 klass->SetDirectMethod(i, method.get());
1275 LoadMethod(dex_file, it, klass, method);
1276 if (oat_class.get() != NULL) {
1277 LinkCode(method, oat_class.get(), method_index);
1278 }
1279 method_index++;
1280 }
1281 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1282 SirtRef<Method> method(AllocMethod());
1283 klass->SetVirtualMethod(i, method.get());
1284 LoadMethod(dex_file, it, klass, method);
1285 if (oat_class.get() != NULL) {
1286 LinkCode(method, oat_class.get(), method_index);
1287 }
1288 method_index++;
1289 }
1290 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001291}
1292
Ian Rogers0571d352011-11-03 19:51:38 -07001293void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1294 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001295 uint32_t field_idx = it.GetMemberIndex();
1296 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001297 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001298 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001299}
1300
Ian Rogers0571d352011-11-03 19:51:38 -07001301void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1302 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001303 uint32_t method_idx = it.GetMemberIndex();
1304 dst->SetDexMethodIndex(method_idx);
1305 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001306 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001307
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001308
1309 StringPiece method_name(dex_file.GetMethodName(method_id));
1310 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001311 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1312 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001313
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001314 if (method_name == "finalize") {
1315 // Create the prototype for a signature of "()V"
1316 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1317 if (void_string_id != NULL) {
1318 const DexFile::TypeId* void_type_id =
1319 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1320 if (void_type_id != NULL) {
1321 std::vector<uint16_t> no_args;
1322 const DexFile::ProtoId* finalizer_proto =
1323 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1324 if (finalizer_proto != NULL) {
1325 // We have the prototype in the dex file
1326 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1327 klass->SetFinalizable();
1328 } else {
1329 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1330 // The Enum class declares a "final" finalize() method to prevent subclasses from
1331 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1332 // subclasses, so we exclude it here.
1333 // We also want to avoid setting the flag on Object, where we know that finalize() is
1334 // empty.
1335 if (klass_descriptor != "Ljava/lang/Object;" &&
1336 klass_descriptor != "Ljava/lang/Enum;") {
1337 klass->SetFinalizable();
1338 }
1339 }
1340 }
1341 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001342 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001343 }
Ian Rogers0571d352011-11-03 19:51:38 -07001344 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001345 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001346
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001347 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1348 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1349 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1350 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1351 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1352 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001353
Brian Carlstrom934486c2011-07-12 23:42:50 -07001354 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001355}
1356
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001357void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001358 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1359 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001360}
1361
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001362void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1363 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001364 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001365 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001366}
1367
Brian Carlstromaded5f72011-10-07 17:15:04 -07001368bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001369 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001370 for (size_t i = 0; i != dex_files_.size(); ++i) {
1371 if (dex_files_[i] == &dex_file) {
1372 return true;
1373 }
1374 }
1375 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001376}
1377
Brian Carlstromaded5f72011-10-07 17:15:04 -07001378bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001379 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001380 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001381}
1382
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001383void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001384 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001385 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001386 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001387 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001388 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001389}
1390
Brian Carlstromaded5f72011-10-07 17:15:04 -07001391void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001392 {
1393 MutexLock mu(dex_lock_);
1394 if (IsDexFileRegisteredLocked(dex_file)) {
1395 return;
1396 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001397 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001398 // Don't alloc while holding the lock, since allocation may need to
1399 // suspend all threads and another thread may need the dex_lock_ to
1400 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001401 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001402 {
1403 MutexLock mu(dex_lock_);
1404 if (IsDexFileRegisteredLocked(dex_file)) {
1405 return;
1406 }
1407 RegisterDexFileLocked(dex_file, dex_cache);
1408 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001409}
1410
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001411void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001412 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001413 RegisterDexFileLocked(dex_file, dex_cache);
1414}
1415
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001416const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001417 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001418 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001419 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1420 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001421 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001422 }
1423 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001424 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001425 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001426}
1427
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001428DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001429 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001430 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001431 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001432 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001433 }
1434 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001435 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001436 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001437}
1438
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001439Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1440 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001441 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001442 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001443 CHECK(primitive_class != NULL);
1444 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001445 primitive_class->SetPrimitiveType(type);
1446 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001447 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001448 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1449 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001450}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001451
Brian Carlstrombe977852011-07-19 14:54:54 -07001452// Create an array class (i.e. the class object for the array, not the
1453// array itself). "descriptor" looks like "[C" or "[[[[B" or
1454// "[Ljava/lang/String;".
1455//
1456// If "descriptor" refers to an array of primitives, look up the
1457// primitive type's internally-generated class object.
1458//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001459// "class_loader" is the class loader of the class that's referring to
1460// us. It's used to ensure that we're looking for the element type in
1461// the right context. It does NOT become the class loader for the
1462// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001463//
1464// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001465Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001466 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001467
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001468 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001469 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001470 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001471 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001472 return NULL;
1473 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001474
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001475 // See if the component type is already loaded. Array classes are
1476 // always associated with the class loader of their underlying
1477 // element type -- an array of Strings goes with the loader for
1478 // java/lang/String -- so we need to look for it there. (The
1479 // caller should have checked for the existence of the class
1480 // before calling here, but they did so with *their* class loader,
1481 // not the component type's loader.)
1482 //
1483 // If we find it, the caller adds "loader" to the class' initiating
1484 // loader list, which should prevent us from going through this again.
1485 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001486 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001487 // are the same, because our caller (FindClass) just did the
1488 // lookup. (Even if we get this wrong we still have correct behavior,
1489 // because we effectively do this lookup again when we add the new
1490 // class to the hash table --- necessary because of possible races with
1491 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001492 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001493 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001494 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001495 return new_class;
1496 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001497 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001498
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001499 // Fill out the fields in the Class.
1500 //
1501 // It is possible to execute some methods against arrays, because
1502 // all arrays are subclasses of java_lang_Object_, so we need to set
1503 // up a vtable. We can just point at the one in java_lang_Object_.
1504 //
1505 // Array classes are simple enough that we don't need to do a full
1506 // link step.
1507
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001508 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001509 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001510 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001511 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001512 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001513 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001514 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001515 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001516 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001517 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001518 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001519 }
1520 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001521 if (new_class.get() == NULL) {
1522 new_class.reset(AllocClass(sizeof(Class)));
1523 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001524 return NULL;
1525 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001526 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001527 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001528 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001529 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001530 new_class->SetSuperClass(java_lang_Object);
1531 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001532 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001533 new_class->SetClassLoader(component_type->GetClassLoader());
1534 new_class->SetStatus(Class::kStatusInitialized);
1535 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001536 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001537
1538
1539 // All arrays have java/lang/Cloneable and java/io/Serializable as
1540 // interfaces. We need to set that up here, so that stuff like
1541 // "instanceof" works right.
1542 //
1543 // Note: The GC could run during the call to FindSystemClass,
1544 // so we need to make sure the class object is GC-valid while we're in
1545 // there. Do this by clearing the interface list so the GC will just
1546 // think that the entries are null.
1547
1548
1549 // Use the single, global copies of "interfaces" and "iftable"
1550 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001551 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001552 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001553
1554 // Inherit access flags from the component type. Arrays can't be
1555 // used as a superclass or interface, so we want to add "final"
1556 // and remove "interface".
1557 //
1558 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001559 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001560 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001561 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1562 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001563
Ian Rogers5d76c432011-10-31 21:42:49 -07001564 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001565 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001566 }
1567 // Another thread must have loaded the class after we
1568 // started but before we finished. Abandon what we've
1569 // done.
1570 //
1571 // (Yes, this happens.)
1572
1573 // Grab the winning class.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001574 Class* other_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001575 DCHECK(other_class != NULL);
1576 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001577}
1578
1579Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001580 switch (Primitive::GetType(type)) {
1581 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001582 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001583 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001584 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001585 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001586 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001587 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001588 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001589 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001590 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001591 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001592 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001593 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001594 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001595 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001596 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001597 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001598 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001599 case Primitive::kPrimNot:
1600 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001601 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001602 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001603 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001604 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001605}
1606
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001607bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001608 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001609 DexCache* dex_cache = klass->GetDexCache();
1610 std::string source;
1611 if (dex_cache != NULL) {
1612 source += " from ";
1613 source += dex_cache->GetLocation()->ToModifiedUtf8();
1614 }
1615 LOG(INFO) << "Loaded class " << descriptor << source;
1616 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001617 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001618 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001619 Table::iterator it;
1620 if (image_class) {
1621 // TODO: sanity check there's no match in classes_
1622 it = image_classes_.insert(std::make_pair(hash, klass));
1623 } else {
1624 // TODO: sanity check there's no match in image_classes_
1625 it = classes_.insert(std::make_pair(hash, klass));
1626 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001627 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001628}
1629
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001630bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1631 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001632 MutexLock mu(classes_lock_);
1633 typedef Table::const_iterator It; // TODO: C++0x auto
1634 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001635 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001636 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1637 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001638 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001639 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001640 classes_.erase(it);
1641 return true;
1642 }
1643 }
1644 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1645 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001646 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001647 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001648 image_classes_.erase(it);
1649 return true;
1650 }
1651 }
1652 return false;
1653}
1654
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001655Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1656 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001657 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001658 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001659 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001660 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001661 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001662 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001663 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001664 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001665 return klass;
1666 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001667 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001668 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1669 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001670 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001671 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001672 return klass;
1673 }
1674 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001675 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001676}
1677
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001678void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001679 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001680 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001681 MutexLock mu(classes_lock_);
1682 typedef Table::const_iterator It; // TODO: C++0x auto
1683 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001684 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001685 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001686 Class* klass = it->second;
1687 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001688 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001689 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001690 }
1691 }
1692 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001693 Class* klass = it->second;
1694 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001695 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001696 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001697 }
1698 }
1699}
1700
jeffhao98eacac2011-09-14 16:11:53 -07001701void ClassLinker::VerifyClass(Class* klass) {
1702 if (klass->IsVerified()) {
1703 return;
1704 }
1705
1706 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001707 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001708
Ian Rogersd81871c2011-10-03 13:57:23 -07001709 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001710 klass->SetStatus(Class::kStatusVerified);
1711 } else {
1712 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001713 Thread* self = Thread::Current();
1714 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1715 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001716 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001717 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001718 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001719 }
jeffhao98eacac2011-09-14 16:11:53 -07001720}
1721
Ian Rogersc2b44472011-12-14 21:17:17 -08001722static void CheckProxyConstructor(Method* constructor);
1723static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1724
Jesse Wilson95caa792011-10-12 18:14:17 -04001725Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001726 ClassLoader* loader, ObjectArray<Method>* methods,
1727 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001728 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001729 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001730 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001731 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001732 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001733 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001734 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001735 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001736 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001737 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001738
1739 klass->SetStatus(Class::kStatusIdx);
1740
1741 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1742
1743 // Create static field that holds throws, instance fields are inherited
1744 klass->SetSFields(AllocObjectArray<Field>(1));
1745 SirtRef<Field> sfield(AllocField());
1746 klass->SetStaticField(0, sfield.get());
1747 sfield->SetDexFieldIndex(-1);
1748 sfield->SetDeclaringClass(klass.get());
1749 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001750
Ian Rogers466bb252011-10-14 03:29:56 -07001751 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001752 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001753 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001754
Ian Rogers466bb252011-10-14 03:29:56 -07001755 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001756 size_t num_virtual_methods = methods->GetLength();
1757 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1758 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001759 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001760 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001761 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001762
1763 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1764 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1765 DCHECK(!Thread::Current()->IsExceptionPending());
1766
1767 // Link the fields and virtual methods, creating vtable and iftables
1768 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001769 DCHECK(Thread::Current()->IsExceptionPending());
1770 return NULL;
1771 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001772 sfield->SetObject(NULL, throws); // initialize throws field
1773 klass->SetStatus(Class::kStatusInitialized);
1774
1775 // sanity checks
1776#ifndef NDEBUG
1777 bool debug = true;
1778#else
1779 bool debug = false;
1780#endif
1781 if (debug) {
1782 CHECK(klass->GetIFields() == NULL);
1783 CheckProxyConstructor(klass->GetDirectMethod(0));
1784 for (size_t i = 0; i < num_virtual_methods; ++i) {
1785 SirtRef<Method> prototype(methods->Get(i));
1786 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1787 }
1788 std::string throws_field_name = "java.lang.Class[][] ";
1789 throws_field_name += name->ToModifiedUtf8();
1790 throws_field_name += ".throws";
1791 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1792
1793 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1794 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1795 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001796 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001797}
1798
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001799std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1800 DCHECK(proxy_class->IsProxyClass());
1801 String* name = proxy_class->GetName();
1802 DCHECK(name != NULL);
1803 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1804}
1805
1806
1807Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001808 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001809 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001810 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001811 Method* proxy_constructor = proxy_direct_methods->Get(2);
1812 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1813 // code_ too)
1814 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1815 // Make this constructor public and fix the class to be our Proxy version
1816 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001817 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001818 return constructor;
1819}
1820
1821static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001822 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001823 MethodHelper mh(constructor);
1824 CHECK_STREQ(mh.GetName(), "<init>");
1825 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001826 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001827}
1828
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001829Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1830 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1831 // prototype method
1832 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1833 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001834 // as necessary
1835 Method* method = down_cast<Method*>(prototype->Clone());
1836
1837 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1838 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001839 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001840 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001841
Ian Rogers466bb252011-10-14 03:29:56 -07001842 // At runtime the method looks like a reference and argument saving method, clone the code
1843 // related parameters from this method.
1844 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1845 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1846 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1847 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1848 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001849 return method;
1850}
Jesse Wilson95caa792011-10-12 18:14:17 -04001851
Ian Rogersc2b44472011-12-14 21:17:17 -08001852static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001853 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001854 CHECK(!prototype->IsFinal());
1855 CHECK(method->IsFinal());
1856 CHECK(!method->IsAbstract());
1857 MethodHelper mh(method);
1858 const char* method_name = mh.GetName();
1859 const char* method_shorty = mh.GetShorty();
1860 Class* method_return = mh.GetReturnType();
1861
1862 mh.ChangeMethod(prototype.get());
1863
1864 CHECK_STREQ(mh.GetName(), method_name);
1865 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001866
1867 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001868 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001869}
1870
Brian Carlstrom25c33252011-09-18 15:58:35 -07001871bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001872 CHECK(klass->IsResolved() || klass->IsErroneous())
1873 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001874
Carl Shapirob5573532011-07-12 18:22:59 -07001875 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001876
Brian Carlstrom25c33252011-09-18 15:58:35 -07001877 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001878 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001879 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001880 ObjectLock lock(klass);
1881
Brian Carlstromd1422f82011-09-28 11:37:09 -07001882 if (klass->GetStatus() == Class::kStatusInitialized) {
1883 return true;
1884 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001885
Brian Carlstromd1422f82011-09-28 11:37:09 -07001886 if (klass->IsErroneous()) {
1887 ThrowEarlierClassFailure(klass);
1888 return false;
1889 }
1890
1891 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001892 VerifyClass(klass);
1893 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001894 return false;
1895 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001896 }
1897
Brian Carlstrom25c33252011-09-18 15:58:35 -07001898 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1899 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001900 // if the class has a <clinit> but we can't run it during compilation,
1901 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001902 return false;
1903 }
1904
Brian Carlstromd1422f82011-09-28 11:37:09 -07001905 // If the class is kStatusInitializing, either this thread is
1906 // initializing higher up the stack or another thread has beat us
1907 // to initializing and we need to wait. Either way, this
1908 // invocation of InitializeClass will not be responsible for
1909 // running <clinit> and will return.
1910 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001911 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001912 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001913 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001914 return true;
1915 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001916 // No. That's fine. Wait for another thread to finish initializing.
1917 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001918 }
1919
1920 if (!ValidateSuperClassDescriptors(klass)) {
1921 klass->SetStatus(Class::kStatusError);
1922 return false;
1923 }
1924
Brian Carlstromd1422f82011-09-28 11:37:09 -07001925 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001926
Elliott Hughesdcc24742011-09-07 14:02:44 -07001927 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001928 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001929 }
1930
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001931 uint64_t t0 = NanoTime();
1932
Brian Carlstrom25c33252011-09-18 15:58:35 -07001933 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001934 return false;
1935 }
1936
1937 InitializeStaticFields(klass);
1938
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001939 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001940 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001941 }
1942
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001943 uint64_t t1 = NanoTime();
1944
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001945 {
1946 ObjectLock lock(klass);
1947
1948 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001949 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001950 klass->SetStatus(Class::kStatusError);
1951 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001952 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1953 RuntimeStats* thread_stats = self->GetStats();
1954 ++global_stats->class_init_count;
1955 ++thread_stats->class_init_count;
1956 global_stats->class_init_time_ns += (t1 - t0);
1957 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001958 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001959 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001960 ClassHelper kh(klass);
1961 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08001962 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001963 }
1964 lock.NotifyAll();
1965 }
1966
1967 return true;
1968}
1969
Brian Carlstromd1422f82011-09-28 11:37:09 -07001970bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1971 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001972 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001973 lock.Wait();
1974
1975 // When we wake up, repeat the test for init-in-progress. If
1976 // there's an exception pending (only possible if
1977 // "interruptShouldThrow" was set), bail out.
1978 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001979 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001980 klass->SetStatus(Class::kStatusError);
1981 return false;
1982 }
1983 // Spurious wakeup? Go back to waiting.
1984 if (klass->GetStatus() == Class::kStatusInitializing) {
1985 continue;
1986 }
1987 if (klass->IsErroneous()) {
1988 // The caller wants an exception, but it was thrown in a
1989 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001990 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001991 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001992 return false;
1993 }
1994 if (klass->IsInitialized()) {
1995 return true;
1996 }
1997 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1998 }
1999 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2000}
2001
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002002bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2003 if (klass->IsInterface()) {
2004 return true;
2005 }
2006 // begin with the methods local to the superclass
2007 if (klass->HasSuperClass() &&
2008 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2009 const Class* super = klass->GetSuperClass();
2010 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002011 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002012 if (method != super->GetVirtualMethod(i) &&
2013 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002014 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2015
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002016 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2017 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2018 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002019 return false;
2020 }
2021 }
2022 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002023 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2024 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2025 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002026 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2027 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002028 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002029 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002030 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002031 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2032
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002033 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2034 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2035 PrettyMethod(method).c_str(),
2036 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002037 return false;
2038 }
2039 }
2040 }
2041 }
2042 return true;
2043}
2044
2045bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002046 const Class* klass1,
2047 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002048 if (klass1 == klass2) {
2049 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002050 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002051 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002052 const DexFile::ProtoId& proto_id =
2053 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002054 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2055 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002056 if (descriptor == NULL) {
2057 break;
2058 }
2059 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2060 // Found a non-primitive type.
2061 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2062 return false;
2063 }
2064 }
2065 }
2066 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002067 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002068 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002069 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002070 return false;
2071 }
2072 }
2073 return true;
2074}
2075
2076// Returns true if classes referenced by the descriptor are the
2077// same classes in klass1 as they are in klass2.
2078bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002079 const Class* klass1,
2080 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002081 CHECK(descriptor != NULL);
2082 CHECK(klass1 != NULL);
2083 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002084 if (klass1 == klass2) {
2085 return true;
2086 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002087 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002088 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002089 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002090 // TODO: found2 == NULL
2091 // TODO: lookup found1 in initiating loader list
2092 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002093 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002094 return found1 == found2;
2095 } else {
2096 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002097 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002098}
2099
Brian Carlstrom25c33252011-09-18 15:58:35 -07002100bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002101 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002102 if (!klass->IsInterface() && klass->HasSuperClass()) {
2103 Class* super_class = klass->GetSuperClass();
2104 if (super_class->GetStatus() != Class::kStatusInitialized) {
2105 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002106 Thread* self = Thread::Current();
2107 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002108 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002109 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002110 // TODO: check for a pending exception
2111 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002112 if (!can_run_clinit) {
2113 // Don't set status to error when we can't run <clinit>.
2114 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2115 klass->SetStatus(Class::kStatusVerified);
2116 return false;
2117 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118 klass->SetStatus(Class::kStatusError);
2119 klass->NotifyAll();
2120 return false;
2121 }
2122 }
2123 }
2124 return true;
2125}
2126
Brian Carlstrom25c33252011-09-18 15:58:35 -07002127bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002128 CHECK(c != NULL);
2129 if (c->IsInitialized()) {
2130 return true;
2131 }
2132
Elliott Hughes5f791332011-09-15 17:45:30 -07002133 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002134 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002135 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002136 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002137}
2138
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002139void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002140 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002141 const ClassLoader* cl = c->GetClassLoader();
2142 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002143 ClassDataItemIterator it(dex_file, class_data);
2144 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2145 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002146 }
2147}
2148
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002149void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002150 size_t num_static_fields = klass->NumStaticFields();
2151 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002152 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002153 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002154 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002155 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002156 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002157 return;
2158 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002159 ClassHelper kh(klass);
2160 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002161 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002162 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002163 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002164
Ian Rogers0571d352011-11-03 19:51:38 -07002165 if (it.HasNext()) {
2166 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2167 std::map<uint32_t, Field*> field_map;
2168 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2169 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2170 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002171 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002172 }
2173}
2174
Ian Rogersc2b44472011-12-14 21:17:17 -08002175bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002176 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002177 if (!LinkSuperClass(klass)) {
2178 return false;
2179 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002180 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002181 return false;
2182 }
2183 if (!LinkInstanceFields(klass)) {
2184 return false;
2185 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002186 if (!LinkStaticFields(klass)) {
2187 return false;
2188 }
2189 CreateReferenceInstanceOffsets(klass);
2190 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002191 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2192 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002193 return true;
2194}
2195
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002196bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002197 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002198 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2199 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2200 if (class_def == NULL) {
2201 return false;
2202 }
2203 uint16_t super_class_idx = class_def->superclass_idx_;
2204 if (super_class_idx != DexFile::kDexNoIndex16) {
2205 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002206 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002207 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002208 return false;
2209 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002210 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002211 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002212 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2213 if (interfaces != NULL) {
2214 for (size_t i = 0; i < interfaces->Size(); i++) {
2215 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2216 Class* interface = ResolveType(dex_file, idx, klass.get());
2217 if (interface == NULL) {
2218 DCHECK(Thread::Current()->IsExceptionPending());
2219 return false;
2220 }
2221 // Verify
2222 if (!klass->CanAccess(interface)) {
2223 // TODO: the RI seemed to ignore this in my testing.
2224 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2225 "Interface %s implemented by class %s is inaccessible",
2226 PrettyDescriptor(interface).c_str(),
2227 PrettyDescriptor(klass.get()).c_str());
2228 return false;
2229 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002230 }
2231 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002232 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002233 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002234 return true;
2235}
2236
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002237bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002238 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002239 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002240 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002241 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002242 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002243 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002244 return false;
2245 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002246 return true;
2247 }
2248 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002249 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002250 return false;
2251 }
2252 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002253 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002254 Thread* thread = Thread::Current();
2255 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002256 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002257 PrettyDescriptor(super).c_str(),
2258 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002259 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002260 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002261 return false;
2262 }
2263 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002264 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002265 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002266 PrettyDescriptor(super).c_str(),
2267 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002268 return false;
2269 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002270
2271 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2272 if (super->IsFinalizable()) {
2273 klass->SetFinalizable();
2274 }
2275
Elliott Hughes2da50362011-10-10 16:57:08 -07002276 // Inherit reference flags (if any) from the superclass.
2277 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2278 if (reference_flags != 0) {
2279 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2280 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002281 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002282 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002283 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002284 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002285 return false;
2286 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002287
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002288#ifndef NDEBUG
2289 // Ensure super classes are fully resolved prior to resolving fields..
2290 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002291 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002292 super = super->GetSuperClass();
2293 }
2294#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002295 return true;
2296}
2297
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002298// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002299bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002300 if (klass->IsInterface()) {
2301 // No vtable.
2302 size_t count = klass->NumVirtualMethods();
2303 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002304 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002305 return false;
2306 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002307 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002308 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309 }
jeffhaobdb76512011-09-07 11:43:16 -07002310 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002311 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002312 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002313 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002314 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002315 }
2316 return true;
2317}
2318
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002319bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002320 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002321 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2322 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002323 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002324 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002325 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002326 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002327 MethodHelper local_mh(NULL, this);
2328 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002329 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002330 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002331 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002332 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002333 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002334 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002335 super_mh.ChangeMethod(super_method);
2336 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002337 // Verify
2338 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002339 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002340 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002341 PrettyDescriptor(klass.get()).c_str(),
2342 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002343 return false;
2344 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002345 vtable->Set(j, local_method);
2346 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002347 break;
2348 }
2349 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002350 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002351 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002352 vtable->Set(actual_count, local_method);
2353 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002354 actual_count += 1;
2355 }
2356 }
2357 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002358 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002359 return false;
2360 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002361 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002362 CHECK_LE(actual_count, max_count);
2363 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002364 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002365 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002366 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002367 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002368 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002369 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002370 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002371 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002372 return false;
2373 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002374 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002375 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002376 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2377 vtable->Set(i, virtual_method);
2378 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002379 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002380 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002381 }
2382 return true;
2383}
2384
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002385bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002386 size_t super_ifcount;
2387 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002388 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002389 } else {
2390 super_ifcount = 0;
2391 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002392 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002393 ClassHelper kh(klass.get(), this);
2394 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2395 ifcount += num_interfaces;
2396 for (size_t i = 0; i < num_interfaces; i++) {
2397 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2398 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002399 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002400 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002401 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002402 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002403 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002404 return true;
2405 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002406 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002407 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002408 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2409 for (size_t i = 0; i < super_ifcount; i++) {
2410 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2411 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002412 }
2413 // Flatten the interface inheritance hierarchy.
2414 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002415 for (size_t i = 0; i < num_interfaces; i++) {
2416 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002417 DCHECK(interface != NULL);
2418 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002419 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002420 Thread* thread = Thread::Current();
2421 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002422 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002423 PrettyDescriptor(klass.get()).c_str(),
2424 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002425 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002426 return false;
2427 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002428 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002429 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002430 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002431 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2432 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002433 }
2434 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002435 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002436 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002437
2438 // If we're an interface, we don't need the vtable pointers, so we're done.
2439 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002440 return true;
2441 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002442 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002443 MethodHelper vtable_mh(NULL, this);
2444 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002445 for (size_t i = 0; i < ifcount; ++i) {
2446 InterfaceEntry* interface_entry = iftable->Get(i);
2447 Class* interface = interface_entry->GetInterface();
2448 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2449 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002450 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002451 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2452 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002453 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002454 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002455 // For each method listed in the interface's method list, find the
2456 // matching method in our class's method list. We want to favor the
2457 // subclass over the superclass, which just requires walking
2458 // back from the end of the vtable. (This only matters if the
2459 // superclass defines a private method and this class redefines
2460 // it -- otherwise it would use the same vtable slot. In .dex files
2461 // those don't end up in the virtual method table, so it shouldn't
2462 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002463 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2464 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002465 vtable_mh.ChangeMethod(vtable_method);
2466 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002467 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002468 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002469 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002470 return false;
2471 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002472 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002473 break;
2474 }
2475 }
2476 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002477 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002478 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002479 Method* mir_method = miranda_list[mir];
2480 vtable_mh.ChangeMethod(mir_method);
2481 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002482 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002483 break;
2484 }
2485 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002486 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002487 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002488 miranda_method.reset(AllocMethod());
2489 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2490 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002491 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002492 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002493 }
2494 }
2495 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002496 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002497 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002498 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002499 klass->SetVirtualMethods((old_method_count == 0)
2500 ? AllocObjectArray<Method>(new_method_count)
2501 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002502
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002503 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2504 CHECK(vtable != NULL);
2505 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002506 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002507 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002508 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002509 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002510 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002511 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2512 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2513 klass->SetVirtualMethod(old_method_count + i, method);
2514 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002515 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002516 // TODO: do not assign to the vtable field until it is fully constructed.
2517 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002518 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002519
2520 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2521 for (int i = 0; i < vtable->GetLength(); ++i) {
2522 CHECK(vtable->Get(i) != NULL);
2523 }
2524
2525// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2526
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002527 return true;
2528}
2529
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002530bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2531 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002532 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002533}
2534
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002535bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2536 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002537 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002538 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002539 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002540 return success;
2541}
2542
Brian Carlstromdbc05252011-09-09 01:59:59 -07002543struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002544 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002545 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002546 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002547 fh_->ChangeField(field1);
2548 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2549 fh_->ChangeField(field2);
2550 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002551 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2552 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2553 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2554 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002555 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2556 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2557 if (order1 != order2) {
2558 return order1 < order2;
2559 }
2560
2561 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002562 fh_->ChangeField(field1);
2563 StringPiece name1(fh_->GetName());
2564 fh_->ChangeField(field2);
2565 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002566 return name1 < name2;
2567 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002568
2569 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002570};
2571
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002572bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002573 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002574 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002575
2576 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002577 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002578
2579 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002580 size_t size;
2581 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002582 if (is_static) {
2583 size = klass->GetClassSize();
2584 field_offset = Class::FieldsOffset();
2585 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002586 Class* super_class = klass->GetSuperClass();
2587 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002588 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002589 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002590 }
2591 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002592 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002593
Brian Carlstromdbc05252011-09-09 01:59:59 -07002594 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002595
Brian Carlstromdbc05252011-09-09 01:59:59 -07002596 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002597 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002598 std::deque<Field*> grouped_and_sorted_fields;
2599 for (size_t i = 0; i < num_fields; i++) {
2600 grouped_and_sorted_fields.push_back(fields->Get(i));
2601 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002602 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002603 std::sort(grouped_and_sorted_fields.begin(),
2604 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002605 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002606
2607 // References should be at the front.
2608 size_t current_field = 0;
2609 size_t num_reference_fields = 0;
2610 for (; current_field < num_fields; current_field++) {
2611 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002612 fh.ChangeField(field);
2613 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002614 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002615 if (isPrimitive) {
2616 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002617 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002618 grouped_and_sorted_fields.pop_front();
2619 num_reference_fields++;
2620 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002621 field->SetOffset(field_offset);
2622 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002623 }
2624
2625 // Now we want to pack all of the double-wide fields together. If
2626 // we're not aligned, though, we want to shuffle one 32-bit field
2627 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002628 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002629 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2630 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002631 fh.ChangeField(field);
2632 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002633 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2634 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002635 continue;
2636 }
2637 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002638 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002639 // drop the consumed field
2640 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2641 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002642 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002643 // whether we found a 32-bit field for padding or not, we advance
2644 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002645 }
2646
2647 // Alignment is good, shuffle any double-wide fields forward, and
2648 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002649 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002650 while (!grouped_and_sorted_fields.empty()) {
2651 Field* field = grouped_and_sorted_fields.front();
2652 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002653 fh.ChangeField(field);
2654 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002655 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002656 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002657 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002658 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002659 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002660 ? sizeof(uint64_t)
2661 : sizeof(uint32_t)));
2662 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002663 }
2664
Elliott Hughesadb460d2011-10-05 17:02:34 -07002665 // 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 -08002666 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2667 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002668 // We know there are no non-reference fields in the Reference classes, and we know
2669 // that 'referent' is alphabetically last, so this is easy...
2670 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002671 fh.ChangeField(fields->Get(num_fields - 1));
2672 StringPiece name(fh.GetName());
2673 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002674 --num_reference_fields;
2675 }
2676
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002677#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002678 // Make sure that all reference fields appear before
2679 // non-reference fields, and all double-wide fields are aligned.
2680 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002681 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002682 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002683 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002684 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002685 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002686 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002687 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2688 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002689 fh.ChangeField(field);
2690 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002691 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002692 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002693 is_primitive = true; // We lied above, so we have to expect a lie here.
2694 }
2695 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002696 if (!seen_non_ref) {
2697 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002698 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002699 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002700 } else {
2701 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002702 }
2703 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002704 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002705 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002706 }
2707#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002708 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002709 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002710 if (is_static) {
2711 klass->SetNumReferenceStaticFields(num_reference_fields);
2712 klass->SetClassSize(size);
2713 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002714 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002715 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002716 klass->SetObjectSize(size);
2717 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002718 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002719 return true;
2720}
2721
2722// Set the bitmap of reference offsets, refOffsets, from the ifields
2723// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002724void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002725 uint32_t reference_offsets = 0;
2726 Class* super_class = klass->GetSuperClass();
2727 if (super_class != NULL) {
2728 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002729 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002730 if (reference_offsets == CLASS_WALK_SUPER) {
2731 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002732 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002733 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002734 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002735 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002736}
2737
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002738void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002739 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002740}
2741
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002742void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002743 uint32_t reference_offsets) {
2744 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002745 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2746 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002747 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002748 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002749 // All of the fields that contain object references are guaranteed
2750 // to be at the beginning of the fields list.
2751 for (size_t i = 0; i < num_reference_fields; ++i) {
2752 // Note that byte_offset is the offset from the beginning of
2753 // object, not the offset into instance data
2754 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002755 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002756 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2757 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2758 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002759 CHECK_NE(new_bit, 0U);
2760 reference_offsets |= new_bit;
2761 } else {
2762 reference_offsets = CLASS_WALK_SUPER;
2763 break;
2764 }
2765 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002766 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002767 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002768 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002769 } else {
2770 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002771 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002772}
2773
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002774String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002775 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002776 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002777 if (resolved != NULL) {
2778 return resolved;
2779 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002780 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2781 int32_t utf16_length = dex_file.GetStringLength(string_id);
2782 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002783 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002784 dex_cache->SetResolvedString(string_idx, string);
2785 return string;
2786}
2787
2788Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002789 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002790 DexCache* dex_cache,
2791 const ClassLoader* class_loader) {
2792 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002793 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002794 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002795 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002796 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002797 // TODO: we used to throw here if resolved's class loader was not the
2798 // boot class loader. This was to permit different classes with the
2799 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002800 dex_cache->SetResolvedType(type_idx, resolved);
2801 } else {
2802 DCHECK(Thread::Current()->IsExceptionPending());
2803 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002804 }
2805 return resolved;
2806}
2807
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002808Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2809 uint32_t method_idx,
2810 DexCache* dex_cache,
2811 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002812 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002813 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2814 if (resolved != NULL) {
2815 return resolved;
2816 }
2817 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2818 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2819 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002820 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002821 return NULL;
2822 }
2823
Ian Rogers0571d352011-11-03 19:51:38 -07002824 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2825 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002826 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002827 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002828 } else if (klass->IsInterface()) {
2829 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002830 } else {
2831 resolved = klass->FindVirtualMethod(name, signature);
2832 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002833 if (resolved != NULL) {
2834 dex_cache->SetResolvedMethod(method_idx, resolved);
2835 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002836 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002837 }
2838 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002839}
2840
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002841Field* ClassLinker::ResolveField(const DexFile& dex_file,
2842 uint32_t field_idx,
2843 DexCache* dex_cache,
2844 const ClassLoader* class_loader,
2845 bool is_static) {
2846 Field* resolved = dex_cache->GetResolvedField(field_idx);
2847 if (resolved != NULL) {
2848 return resolved;
2849 }
2850 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2851 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2852 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002853 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002854 return NULL;
2855 }
2856
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002857 const char* name = dex_file.GetFieldName(field_id);
2858 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002859 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002860 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002861 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002862 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002863 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002864 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002865 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002866 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002867 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2868 }
2869 return resolved;
2870}
2871
2872Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2873 uint32_t field_idx,
2874 DexCache* dex_cache,
2875 const ClassLoader* class_loader) {
2876 Field* resolved = dex_cache->GetResolvedField(field_idx);
2877 if (resolved != NULL) {
2878 return resolved;
2879 }
2880 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2881 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2882 if (klass == NULL) {
2883 DCHECK(Thread::Current()->IsExceptionPending());
2884 return NULL;
2885 }
2886
2887 const char* name = dex_file.GetFieldName(field_id);
2888 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
2889 resolved = klass->FindField(name, type);
2890 if (resolved != NULL) {
2891 dex_cache->SetResolvedField(field_idx, resolved);
2892 } else {
2893 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002894 }
2895 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002896}
2897
Ian Rogersad25ac52011-10-04 19:13:33 -07002898const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2899 Class* declaring_class = referrer->GetDeclaringClass();
2900 DexCache* dex_cache = declaring_class->GetDexCache();
2901 const DexFile& dex_file = FindDexFile(dex_cache);
2902 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2903 return dex_file.GetShorty(method_id.proto_idx_);
2904}
2905
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002906void ClassLinker::DumpAllClasses(int flags) const {
2907 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2908 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2909 std::vector<Class*> all_classes;
2910 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002911 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002912 typedef Table::const_iterator It; // TODO: C++0x auto
2913 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2914 all_classes.push_back(it->second);
2915 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002916 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2917 all_classes.push_back(it->second);
2918 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002919 }
2920
2921 for (size_t i = 0; i < all_classes.size(); ++i) {
2922 all_classes[i]->DumpClass(std::cerr, flags);
2923 }
2924}
2925
Elliott Hughescac6cc72011-11-03 20:31:21 -07002926void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2927 MutexLock mu(classes_lock_);
2928 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2929 << classes_.size() << " allocated classes\n";
2930}
2931
Elliott Hughese27955c2011-08-26 15:21:24 -07002932size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002933 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002934 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002935}
2936
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002937pid_t ClassLinker::GetClassesLockOwner() {
2938 return classes_lock_.GetOwner();
2939}
2940
2941pid_t ClassLinker::GetDexLockOwner() {
2942 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002943}
2944
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002945void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
2946 DCHECK(!init_done_);
2947
2948 DCHECK(klass != NULL);
2949 DCHECK(klass->GetClassLoader() == NULL);
2950
2951 DCHECK(class_roots_ != NULL);
2952 DCHECK(class_roots_->Get(class_root) == NULL);
2953 class_roots_->Set(class_root, klass);
2954}
2955
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002956} // namespace art