blob: 5a3887aa4217a30e26225c74b74f5a7dc1b158d3 [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 Hughesdb7d5e92011-12-16 18:47:37 -0800996Class* ClassLinker::FindSystemClass(const char* descriptor) {
997 return FindClass(descriptor, NULL);
998}
999
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001000Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
1001 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001002 Thread* self = Thread::Current();
1003 DCHECK(self != NULL);
1004 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001005 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001006 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1007 // for primitive classes that aren't backed by dex files.
1008 return FindPrimitiveClass(descriptor[0]);
1009 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001010 // Find the class in the loaded classes table.
1011 Class* klass = LookupClass(descriptor, class_loader);
1012 if (klass != NULL) {
1013 return EnsureResolved(klass);
1014 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001015 // Class is not yet loaded.
1016 if (descriptor[0] == '[') {
1017 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001018
Jesse Wilson47daf872011-11-23 11:42:45 -05001019 } else if (class_loader == NULL) {
1020 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1021 if (pair.second != NULL) {
1022 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1023 }
1024
1025 } else if (ClassLoader::UseCompileTimeClassPath()) {
1026 // first try the boot class path
1027 Class* system_class = FindSystemClass(descriptor);
1028 if (system_class != NULL) {
1029 return system_class;
1030 }
1031 CHECK(self->IsExceptionPending());
1032 self->ClearException();
1033
1034 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001035 const std::vector<const DexFile*>& class_path
1036 = ClassLoader::GetCompileTimeClassPath(class_loader);
1037 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001038 if (pair.second != NULL) {
1039 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001040 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001041
1042 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001043 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001044 ScopedThreadStateChange(self, Thread::kNative);
1045 JNIEnv* env = self->GetJniEnv();
1046 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1047 CHECK(c.get() != NULL);
1048 // TODO: cache method?
1049 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1050 CHECK(mid != NULL);
1051 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1052 if (class_name_object.get() == NULL) {
1053 return NULL;
1054 }
1055 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1056 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
Ian Rogers6b0870d2011-12-15 19:38:12 -08001057 if (!env->ExceptionOccurred()) {
1058 return Decode<Class*>(env, result.get());
1059 } else {
1060 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1061 // TODO: initialize the cause of the NCDFE to this exception
1062 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001063 }
1064
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001065 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001066 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001067}
1068
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001069Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001070 const ClassLoader* class_loader,
1071 const DexFile& dex_file,
1072 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001073 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001074 // Load the class from the dex file.
1075 if (!init_done_) {
1076 // finish up init of hand crafted class_roots_
1077 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001078 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001079 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001080 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001081 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001082 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001083 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001084 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001085 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001086 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001087 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001088 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001089 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001090 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001091 }
1092 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001093 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001094 }
1095 klass->SetDexCache(FindDexCache(dex_file));
1096 LoadClass(dex_file, dex_class_def, klass, class_loader);
1097 // Check for a pending exception during load
1098 Thread* self = Thread::Current();
1099 if (self->IsExceptionPending()) {
1100 return NULL;
1101 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001102 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001103 klass->SetClinitThreadId(self->GetTid());
1104 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001105 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001106 if (!success) {
1107 // We may fail to insert if we raced with another thread.
1108 klass->SetClinitThreadId(0);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001109 klass.reset(LookupClass(descriptor.data(), class_loader));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001110 CHECK(klass.get() != NULL);
1111 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001112 }
1113 // Finish loading (if necessary) by finding parents
1114 CHECK(!klass->IsLoaded());
1115 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1116 // Loading failed.
1117 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001118 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001119 lock.NotifyAll();
1120 return NULL;
1121 }
1122 CHECK(klass->IsLoaded());
1123 // Link the class (if necessary)
1124 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001125 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001126 // Linking failed.
1127 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001128 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001129 lock.NotifyAll();
1130 return NULL;
1131 }
1132 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001133
1134 /*
1135 * We send CLASS_PREPARE events to the debugger from here. The
1136 * definition of "preparation" is creating the static fields for a
1137 * class and initializing them to the standard default values, but not
1138 * executing any code (that comes later, during "initialization").
1139 *
1140 * We did the static preparation in LinkClass.
1141 *
1142 * The class has been prepared and resolved but possibly not yet verified
1143 * at this point.
1144 */
1145 Dbg::PostClassPrepare(klass.get());
1146
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001147 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001148}
1149
Brian Carlstrom4873d462011-08-21 15:23:39 -07001150// Precomputes size that will be needed for Class, matching LinkStaticFields
1151size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1152 const DexFile::ClassDef& dex_class_def) {
1153 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001154 size_t num_ref = 0;
1155 size_t num_32 = 0;
1156 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001157 if (class_data != NULL) {
1158 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1159 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001160 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001161 char c = descriptor[0];
1162 if (c == 'L' || c == '[') {
1163 num_ref++;
1164 } else if (c == 'J' || c == 'D') {
1165 num_64++;
1166 } else {
1167 num_32++;
1168 }
1169 }
1170 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001171 // start with generic class data
1172 size_t size = sizeof(Class);
1173 // follow with reference fields which must be contiguous at start
1174 size += (num_ref * sizeof(uint32_t));
1175 // if there are 64-bit fields to add, make sure they are aligned
1176 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1177 if (num_32 != 0) {
1178 // use an available 32-bit field for padding
1179 num_32--;
1180 }
1181 size += sizeof(uint32_t); // either way, we are adding a word
1182 DCHECK_EQ(size, RoundUp(size, 8));
1183 }
1184 // tack on any 64-bit fields now that alignment is assured
1185 size += (num_64 * sizeof(uint64_t));
1186 // tack on any remaining 32-bit fields
1187 size += (num_32 * sizeof(uint32_t));
1188 return size;
1189}
1190
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001192 // Every kind of method should at least get an invoke stub from the oat_method.
1193 // non-abstract methods also get their code pointers.
1194 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001195 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001196
1197 if (method->IsAbstract()) {
1198 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1199 return;
1200 }
1201 if (method->IsNative()) {
1202 // unregistering restores the dlsym lookup stub
1203 method->UnregisterNative();
1204 return;
1205 }
1206}
1207
Brian Carlstromf615a612011-07-23 12:50:34 -07001208void ClassLinker::LoadClass(const DexFile& dex_file,
1209 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001210 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001211 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001212 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001213 CHECK(klass->GetDexCache() != NULL);
1214 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001215 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001216 CHECK(descriptor != NULL);
1217
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001218 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001219 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001220 // Make sure that none of our runtime-only flags are set.
1221 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001222 klass->SetAccessFlags(access_flags);
1223 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001224 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001225 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001226
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001227 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001228
Ian Rogers0571d352011-11-03 19:51:38 -07001229 // Load fields fields.
1230 const byte* class_data = dex_file.GetClassData(dex_class_def);
1231 if (class_data == NULL) {
1232 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001233 }
Ian Rogers0571d352011-11-03 19:51:38 -07001234 ClassDataItemIterator it(dex_file, class_data);
1235 if (it.NumStaticFields() != 0) {
1236 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1237 }
1238 if (it.NumInstanceFields() != 0) {
1239 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1240 }
1241 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1242 SirtRef<Field> sfield(AllocField());
1243 klass->SetStaticField(i, sfield.get());
1244 LoadField(dex_file, it, klass, sfield);
1245 }
1246 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1247 SirtRef<Field> ifield(AllocField());
1248 klass->SetInstanceField(i, ifield.get());
1249 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001250 }
1251
Brian Carlstromaded5f72011-10-07 17:15:04 -07001252 UniquePtr<const OatFile::OatClass> oat_class;
1253 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001254 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001255 if (oat_file != NULL) {
1256 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1257 if (oat_dex_file != NULL) {
1258 uint32_t class_def_index;
1259 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1260 CHECK(found) << descriptor;
1261 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001262 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001263 }
1264 }
1265 }
Ian Rogers0571d352011-11-03 19:51:38 -07001266 // Load methods.
1267 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001268 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001269 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001270 }
Ian Rogers0571d352011-11-03 19:51:38 -07001271 if (it.NumVirtualMethods() != 0) {
1272 // TODO: append direct methods to class object
1273 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001274 }
Ian Rogers0571d352011-11-03 19:51:38 -07001275 size_t method_index = 0;
1276 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1277 SirtRef<Method> method(AllocMethod());
1278 klass->SetDirectMethod(i, method.get());
1279 LoadMethod(dex_file, it, klass, method);
1280 if (oat_class.get() != NULL) {
1281 LinkCode(method, oat_class.get(), method_index);
1282 }
1283 method_index++;
1284 }
1285 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1286 SirtRef<Method> method(AllocMethod());
1287 klass->SetVirtualMethod(i, method.get());
1288 LoadMethod(dex_file, it, klass, method);
1289 if (oat_class.get() != NULL) {
1290 LinkCode(method, oat_class.get(), method_index);
1291 }
1292 method_index++;
1293 }
1294 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001295}
1296
Ian Rogers0571d352011-11-03 19:51:38 -07001297void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1298 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001299 uint32_t field_idx = it.GetMemberIndex();
1300 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001301 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001302 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001303}
1304
Ian Rogers0571d352011-11-03 19:51:38 -07001305void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1306 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001307 uint32_t method_idx = it.GetMemberIndex();
1308 dst->SetDexMethodIndex(method_idx);
1309 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001310 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001311
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001312
1313 StringPiece method_name(dex_file.GetMethodName(method_id));
1314 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001315 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1316 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001317
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001318 if (method_name == "finalize") {
1319 // Create the prototype for a signature of "()V"
1320 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1321 if (void_string_id != NULL) {
1322 const DexFile::TypeId* void_type_id =
1323 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1324 if (void_type_id != NULL) {
1325 std::vector<uint16_t> no_args;
1326 const DexFile::ProtoId* finalizer_proto =
1327 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1328 if (finalizer_proto != NULL) {
1329 // We have the prototype in the dex file
1330 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1331 klass->SetFinalizable();
1332 } else {
1333 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1334 // The Enum class declares a "final" finalize() method to prevent subclasses from
1335 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1336 // subclasses, so we exclude it here.
1337 // We also want to avoid setting the flag on Object, where we know that finalize() is
1338 // empty.
1339 if (klass_descriptor != "Ljava/lang/Object;" &&
1340 klass_descriptor != "Ljava/lang/Enum;") {
1341 klass->SetFinalizable();
1342 }
1343 }
1344 }
1345 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001346 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001347 }
Ian Rogers0571d352011-11-03 19:51:38 -07001348 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001349 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001350
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001351 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1352 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1353 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1354 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1355 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1356 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001357
Brian Carlstrom934486c2011-07-12 23:42:50 -07001358 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001359}
1360
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001361void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001362 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1363 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001364}
1365
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001366void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1367 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001368 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001369 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001370}
1371
Brian Carlstromaded5f72011-10-07 17:15:04 -07001372bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001373 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001374 for (size_t i = 0; i != dex_files_.size(); ++i) {
1375 if (dex_files_[i] == &dex_file) {
1376 return true;
1377 }
1378 }
1379 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001380}
1381
Brian Carlstromaded5f72011-10-07 17:15:04 -07001382bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001383 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001384 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001385}
1386
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001387void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001388 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001389 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001390 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001391 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001392 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001393}
1394
Brian Carlstromaded5f72011-10-07 17:15:04 -07001395void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001396 {
1397 MutexLock mu(dex_lock_);
1398 if (IsDexFileRegisteredLocked(dex_file)) {
1399 return;
1400 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001401 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001402 // Don't alloc while holding the lock, since allocation may need to
1403 // suspend all threads and another thread may need the dex_lock_ to
1404 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001405 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001406 {
1407 MutexLock mu(dex_lock_);
1408 if (IsDexFileRegisteredLocked(dex_file)) {
1409 return;
1410 }
1411 RegisterDexFileLocked(dex_file, dex_cache);
1412 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001413}
1414
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001415void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001416 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001417 RegisterDexFileLocked(dex_file, dex_cache);
1418}
1419
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001420const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001421 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001422 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001423 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1424 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001425 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001426 }
1427 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001428 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001429 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001430}
1431
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001432DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001433 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001434 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001435 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001436 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001437 }
1438 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001439 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001440 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001441}
1442
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001443Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1444 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001445 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001446 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001447 CHECK(primitive_class != NULL);
1448 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001449 primitive_class->SetPrimitiveType(type);
1450 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001451 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001452 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1453 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001454}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001455
Brian Carlstrombe977852011-07-19 14:54:54 -07001456// Create an array class (i.e. the class object for the array, not the
1457// array itself). "descriptor" looks like "[C" or "[[[[B" or
1458// "[Ljava/lang/String;".
1459//
1460// If "descriptor" refers to an array of primitives, look up the
1461// primitive type's internally-generated class object.
1462//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001463// "class_loader" is the class loader of the class that's referring to
1464// us. It's used to ensure that we're looking for the element type in
1465// the right context. It does NOT become the class loader for the
1466// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001467//
1468// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001469Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001470 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001471
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001472 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001473 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001474 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001475 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001476 return NULL;
1477 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001478
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001479 // See if the component type is already loaded. Array classes are
1480 // always associated with the class loader of their underlying
1481 // element type -- an array of Strings goes with the loader for
1482 // java/lang/String -- so we need to look for it there. (The
1483 // caller should have checked for the existence of the class
1484 // before calling here, but they did so with *their* class loader,
1485 // not the component type's loader.)
1486 //
1487 // If we find it, the caller adds "loader" to the class' initiating
1488 // loader list, which should prevent us from going through this again.
1489 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001490 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001491 // are the same, because our caller (FindClass) just did the
1492 // lookup. (Even if we get this wrong we still have correct behavior,
1493 // because we effectively do this lookup again when we add the new
1494 // class to the hash table --- necessary because of possible races with
1495 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001496 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001497 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001498 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001499 return new_class;
1500 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001501 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001502
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001503 // Fill out the fields in the Class.
1504 //
1505 // It is possible to execute some methods against arrays, because
1506 // all arrays are subclasses of java_lang_Object_, so we need to set
1507 // up a vtable. We can just point at the one in java_lang_Object_.
1508 //
1509 // Array classes are simple enough that we don't need to do a full
1510 // link step.
1511
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001512 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001513 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001514 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001515 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001516 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001517 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001518 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001519 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001520 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001521 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001522 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001523 }
1524 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001525 if (new_class.get() == NULL) {
1526 new_class.reset(AllocClass(sizeof(Class)));
1527 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001528 return NULL;
1529 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001530 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001531 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001532 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001533 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001534 new_class->SetSuperClass(java_lang_Object);
1535 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001536 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001537 new_class->SetClassLoader(component_type->GetClassLoader());
1538 new_class->SetStatus(Class::kStatusInitialized);
1539 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001540 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001541
1542
1543 // All arrays have java/lang/Cloneable and java/io/Serializable as
1544 // interfaces. We need to set that up here, so that stuff like
1545 // "instanceof" works right.
1546 //
1547 // Note: The GC could run during the call to FindSystemClass,
1548 // so we need to make sure the class object is GC-valid while we're in
1549 // there. Do this by clearing the interface list so the GC will just
1550 // think that the entries are null.
1551
1552
1553 // Use the single, global copies of "interfaces" and "iftable"
1554 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001555 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001556 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001557
1558 // Inherit access flags from the component type. Arrays can't be
1559 // used as a superclass or interface, so we want to add "final"
1560 // and remove "interface".
1561 //
1562 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001563 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001564 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001565 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1566 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001567
Ian Rogers5d76c432011-10-31 21:42:49 -07001568 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001569 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001570 }
1571 // Another thread must have loaded the class after we
1572 // started but before we finished. Abandon what we've
1573 // done.
1574 //
1575 // (Yes, this happens.)
1576
1577 // Grab the winning class.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001578 Class* other_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001579 DCHECK(other_class != NULL);
1580 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001581}
1582
1583Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001584 switch (Primitive::GetType(type)) {
1585 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001586 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001587 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001588 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001589 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001590 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001591 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001592 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001593 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001594 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001595 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001596 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001597 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001598 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001599 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001600 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001601 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001602 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001603 case Primitive::kPrimNot:
1604 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001605 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001606 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001607 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001608 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001609}
1610
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001611bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001612 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001613 DexCache* dex_cache = klass->GetDexCache();
1614 std::string source;
1615 if (dex_cache != NULL) {
1616 source += " from ";
1617 source += dex_cache->GetLocation()->ToModifiedUtf8();
1618 }
1619 LOG(INFO) << "Loaded class " << descriptor << source;
1620 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001621 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001622 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001623 Table::iterator it;
1624 if (image_class) {
1625 // TODO: sanity check there's no match in classes_
1626 it = image_classes_.insert(std::make_pair(hash, klass));
1627 } else {
1628 // TODO: sanity check there's no match in image_classes_
1629 it = classes_.insert(std::make_pair(hash, klass));
1630 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001631 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001632}
1633
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001634bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1635 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001636 MutexLock mu(classes_lock_);
1637 typedef Table::const_iterator It; // TODO: C++0x auto
1638 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001639 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001640 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1641 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001642 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001643 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001644 classes_.erase(it);
1645 return true;
1646 }
1647 }
1648 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1649 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001650 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001651 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001652 image_classes_.erase(it);
1653 return true;
1654 }
1655 }
1656 return false;
1657}
1658
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001659Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1660 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001661 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001662 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001663 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001664 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001665 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001666 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001667 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001668 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001669 return klass;
1670 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001671 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001672 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1673 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001674 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001675 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001676 return klass;
1677 }
1678 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001679 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001680}
1681
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001682void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001683 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001684 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001685 MutexLock mu(classes_lock_);
1686 typedef Table::const_iterator It; // TODO: C++0x auto
1687 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001688 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001689 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001690 Class* klass = it->second;
1691 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001692 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001693 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001694 }
1695 }
1696 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001697 Class* klass = it->second;
1698 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001699 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001700 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001701 }
1702 }
1703}
1704
jeffhao98eacac2011-09-14 16:11:53 -07001705void ClassLinker::VerifyClass(Class* klass) {
1706 if (klass->IsVerified()) {
1707 return;
1708 }
1709
1710 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001711 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001712
Ian Rogersd81871c2011-10-03 13:57:23 -07001713 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001714 klass->SetStatus(Class::kStatusVerified);
1715 } else {
1716 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001717 Thread* self = Thread::Current();
1718 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1719 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001720 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001721 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001722 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001723 }
jeffhao98eacac2011-09-14 16:11:53 -07001724}
1725
Ian Rogersc2b44472011-12-14 21:17:17 -08001726static void CheckProxyConstructor(Method* constructor);
1727static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1728
Jesse Wilson95caa792011-10-12 18:14:17 -04001729Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001730 ClassLoader* loader, ObjectArray<Method>* methods,
1731 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001732 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001733 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001734 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001735 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001736 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001737 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001738 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001739 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001740 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001741 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001742
1743 klass->SetStatus(Class::kStatusIdx);
1744
1745 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1746
1747 // Create static field that holds throws, instance fields are inherited
1748 klass->SetSFields(AllocObjectArray<Field>(1));
1749 SirtRef<Field> sfield(AllocField());
1750 klass->SetStaticField(0, sfield.get());
1751 sfield->SetDexFieldIndex(-1);
1752 sfield->SetDeclaringClass(klass.get());
1753 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001754
Ian Rogers466bb252011-10-14 03:29:56 -07001755 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001756 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001757 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001758
Ian Rogers466bb252011-10-14 03:29:56 -07001759 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001760 size_t num_virtual_methods = methods->GetLength();
1761 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1762 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001763 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001764 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001765 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001766
1767 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1768 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1769 DCHECK(!Thread::Current()->IsExceptionPending());
1770
1771 // Link the fields and virtual methods, creating vtable and iftables
1772 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001773 DCHECK(Thread::Current()->IsExceptionPending());
1774 return NULL;
1775 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001776 sfield->SetObject(NULL, throws); // initialize throws field
1777 klass->SetStatus(Class::kStatusInitialized);
1778
1779 // sanity checks
1780#ifndef NDEBUG
1781 bool debug = true;
1782#else
1783 bool debug = false;
1784#endif
1785 if (debug) {
1786 CHECK(klass->GetIFields() == NULL);
1787 CheckProxyConstructor(klass->GetDirectMethod(0));
1788 for (size_t i = 0; i < num_virtual_methods; ++i) {
1789 SirtRef<Method> prototype(methods->Get(i));
1790 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1791 }
1792 std::string throws_field_name = "java.lang.Class[][] ";
1793 throws_field_name += name->ToModifiedUtf8();
1794 throws_field_name += ".throws";
1795 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1796
1797 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1798 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1799 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001800 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001801}
1802
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001803std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1804 DCHECK(proxy_class->IsProxyClass());
1805 String* name = proxy_class->GetName();
1806 DCHECK(name != NULL);
1807 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1808}
1809
1810
1811Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001812 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001813 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001814 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001815 Method* proxy_constructor = proxy_direct_methods->Get(2);
1816 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1817 // code_ too)
1818 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1819 // Make this constructor public and fix the class to be our Proxy version
1820 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001821 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001822 return constructor;
1823}
1824
1825static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001826 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001827 MethodHelper mh(constructor);
1828 CHECK_STREQ(mh.GetName(), "<init>");
1829 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001830 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001831}
1832
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001833Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1834 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1835 // prototype method
1836 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1837 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001838 // as necessary
1839 Method* method = down_cast<Method*>(prototype->Clone());
1840
1841 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1842 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001843 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001844 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001845
Ian Rogers466bb252011-10-14 03:29:56 -07001846 // At runtime the method looks like a reference and argument saving method, clone the code
1847 // related parameters from this method.
1848 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1849 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1850 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1851 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1852 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001853 return method;
1854}
Jesse Wilson95caa792011-10-12 18:14:17 -04001855
Ian Rogersc2b44472011-12-14 21:17:17 -08001856static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001857 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001858 CHECK(!prototype->IsFinal());
1859 CHECK(method->IsFinal());
1860 CHECK(!method->IsAbstract());
1861 MethodHelper mh(method);
1862 const char* method_name = mh.GetName();
1863 const char* method_shorty = mh.GetShorty();
1864 Class* method_return = mh.GetReturnType();
1865
1866 mh.ChangeMethod(prototype.get());
1867
1868 CHECK_STREQ(mh.GetName(), method_name);
1869 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001870
1871 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001872 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001873}
1874
Brian Carlstrom25c33252011-09-18 15:58:35 -07001875bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001876 CHECK(klass->IsResolved() || klass->IsErroneous())
1877 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001878
Carl Shapirob5573532011-07-12 18:22:59 -07001879 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001880
Brian Carlstrom25c33252011-09-18 15:58:35 -07001881 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001882 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001883 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001884 ObjectLock lock(klass);
1885
Brian Carlstromd1422f82011-09-28 11:37:09 -07001886 if (klass->GetStatus() == Class::kStatusInitialized) {
1887 return true;
1888 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001889
Brian Carlstromd1422f82011-09-28 11:37:09 -07001890 if (klass->IsErroneous()) {
1891 ThrowEarlierClassFailure(klass);
1892 return false;
1893 }
1894
1895 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001896 VerifyClass(klass);
1897 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001898 return false;
1899 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001900 }
1901
Brian Carlstrom25c33252011-09-18 15:58:35 -07001902 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1903 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001904 // if the class has a <clinit> but we can't run it during compilation,
1905 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001906 return false;
1907 }
1908
Brian Carlstromd1422f82011-09-28 11:37:09 -07001909 // If the class is kStatusInitializing, either this thread is
1910 // initializing higher up the stack or another thread has beat us
1911 // to initializing and we need to wait. Either way, this
1912 // invocation of InitializeClass will not be responsible for
1913 // running <clinit> and will return.
1914 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001915 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001916 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001917 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001918 return true;
1919 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001920 // No. That's fine. Wait for another thread to finish initializing.
1921 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001922 }
1923
1924 if (!ValidateSuperClassDescriptors(klass)) {
1925 klass->SetStatus(Class::kStatusError);
1926 return false;
1927 }
1928
Brian Carlstromd1422f82011-09-28 11:37:09 -07001929 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001930
Elliott Hughesdcc24742011-09-07 14:02:44 -07001931 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001932 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001933 }
1934
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001935 uint64_t t0 = NanoTime();
1936
Brian Carlstrom25c33252011-09-18 15:58:35 -07001937 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001938 return false;
1939 }
1940
1941 InitializeStaticFields(klass);
1942
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001943 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001944 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001945 }
1946
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001947 uint64_t t1 = NanoTime();
1948
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001949 {
1950 ObjectLock lock(klass);
1951
1952 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001953 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001954 klass->SetStatus(Class::kStatusError);
1955 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001956 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1957 RuntimeStats* thread_stats = self->GetStats();
1958 ++global_stats->class_init_count;
1959 ++thread_stats->class_init_count;
1960 global_stats->class_init_time_ns += (t1 - t0);
1961 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001962 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001963 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001964 ClassHelper kh(klass);
1965 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08001966 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967 }
1968 lock.NotifyAll();
1969 }
1970
1971 return true;
1972}
1973
Brian Carlstromd1422f82011-09-28 11:37:09 -07001974bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1975 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001976 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001977 lock.Wait();
1978
1979 // When we wake up, repeat the test for init-in-progress. If
1980 // there's an exception pending (only possible if
1981 // "interruptShouldThrow" was set), bail out.
1982 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001983 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001984 klass->SetStatus(Class::kStatusError);
1985 return false;
1986 }
1987 // Spurious wakeup? Go back to waiting.
1988 if (klass->GetStatus() == Class::kStatusInitializing) {
1989 continue;
1990 }
1991 if (klass->IsErroneous()) {
1992 // The caller wants an exception, but it was thrown in a
1993 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001994 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001995 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001996 return false;
1997 }
1998 if (klass->IsInitialized()) {
1999 return true;
2000 }
2001 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2002 }
2003 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2004}
2005
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002006bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2007 if (klass->IsInterface()) {
2008 return true;
2009 }
2010 // begin with the methods local to the superclass
2011 if (klass->HasSuperClass() &&
2012 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2013 const Class* super = klass->GetSuperClass();
2014 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002015 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002016 if (method != super->GetVirtualMethod(i) &&
2017 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002018 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2019
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002020 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2021 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2022 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002023 return false;
2024 }
2025 }
2026 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002027 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2028 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2029 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002030 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2031 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002032 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002033 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002034 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002035 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2036
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002037 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2038 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2039 PrettyMethod(method).c_str(),
2040 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041 return false;
2042 }
2043 }
2044 }
2045 }
2046 return true;
2047}
2048
2049bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002050 const Class* klass1,
2051 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002052 if (klass1 == klass2) {
2053 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002054 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002055 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002056 const DexFile::ProtoId& proto_id =
2057 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002058 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2059 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002060 if (descriptor == NULL) {
2061 break;
2062 }
2063 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2064 // Found a non-primitive type.
2065 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2066 return false;
2067 }
2068 }
2069 }
2070 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002071 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002072 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002073 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002074 return false;
2075 }
2076 }
2077 return true;
2078}
2079
2080// Returns true if classes referenced by the descriptor are the
2081// same classes in klass1 as they are in klass2.
2082bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002083 const Class* klass1,
2084 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002085 CHECK(descriptor != NULL);
2086 CHECK(klass1 != NULL);
2087 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002088 if (klass1 == klass2) {
2089 return true;
2090 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002091 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002092 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002093 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002094 // TODO: found2 == NULL
2095 // TODO: lookup found1 in initiating loader list
2096 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002097 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002098 return found1 == found2;
2099 } else {
2100 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002101 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002102}
2103
Brian Carlstrom25c33252011-09-18 15:58:35 -07002104bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002105 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002106 if (!klass->IsInterface() && klass->HasSuperClass()) {
2107 Class* super_class = klass->GetSuperClass();
2108 if (super_class->GetStatus() != Class::kStatusInitialized) {
2109 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002110 Thread* self = Thread::Current();
2111 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002112 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002113 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002114 // TODO: check for a pending exception
2115 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002116 if (!can_run_clinit) {
2117 // Don't set status to error when we can't run <clinit>.
2118 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2119 klass->SetStatus(Class::kStatusVerified);
2120 return false;
2121 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002122 klass->SetStatus(Class::kStatusError);
2123 klass->NotifyAll();
2124 return false;
2125 }
2126 }
2127 }
2128 return true;
2129}
2130
Brian Carlstrom25c33252011-09-18 15:58:35 -07002131bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002132 CHECK(c != NULL);
2133 if (c->IsInitialized()) {
2134 return true;
2135 }
2136
Elliott Hughes5f791332011-09-15 17:45:30 -07002137 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002138 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002139 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002140 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002141}
2142
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002143void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002144 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002145 const ClassLoader* cl = c->GetClassLoader();
2146 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002147 ClassDataItemIterator it(dex_file, class_data);
2148 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2149 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002150 }
2151}
2152
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002153void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002154 size_t num_static_fields = klass->NumStaticFields();
2155 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002156 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002157 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002158 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002159 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002160 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002161 return;
2162 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002163 ClassHelper kh(klass);
2164 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002165 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002166 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002167 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002168
Ian Rogers0571d352011-11-03 19:51:38 -07002169 if (it.HasNext()) {
2170 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2171 std::map<uint32_t, Field*> field_map;
2172 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2173 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2174 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002175 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002176 }
2177}
2178
Ian Rogersc2b44472011-12-14 21:17:17 -08002179bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002180 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002181 if (!LinkSuperClass(klass)) {
2182 return false;
2183 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002184 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002185 return false;
2186 }
2187 if (!LinkInstanceFields(klass)) {
2188 return false;
2189 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002190 if (!LinkStaticFields(klass)) {
2191 return false;
2192 }
2193 CreateReferenceInstanceOffsets(klass);
2194 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002195 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2196 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002197 return true;
2198}
2199
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002200bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002201 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002202 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2203 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2204 if (class_def == NULL) {
2205 return false;
2206 }
2207 uint16_t super_class_idx = class_def->superclass_idx_;
2208 if (super_class_idx != DexFile::kDexNoIndex16) {
2209 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002210 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002211 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002212 return false;
2213 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002214 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002215 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002216 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2217 if (interfaces != NULL) {
2218 for (size_t i = 0; i < interfaces->Size(); i++) {
2219 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2220 Class* interface = ResolveType(dex_file, idx, klass.get());
2221 if (interface == NULL) {
2222 DCHECK(Thread::Current()->IsExceptionPending());
2223 return false;
2224 }
2225 // Verify
2226 if (!klass->CanAccess(interface)) {
2227 // TODO: the RI seemed to ignore this in my testing.
2228 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2229 "Interface %s implemented by class %s is inaccessible",
2230 PrettyDescriptor(interface).c_str(),
2231 PrettyDescriptor(klass.get()).c_str());
2232 return false;
2233 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002234 }
2235 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002236 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002237 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002238 return true;
2239}
2240
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002241bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002242 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002243 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002244 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002245 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002246 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002247 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002248 return false;
2249 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002250 return true;
2251 }
2252 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002253 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002254 return false;
2255 }
2256 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002257 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002258 Thread* thread = Thread::Current();
2259 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002260 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002261 PrettyDescriptor(super).c_str(),
2262 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002263 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002264 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265 return false;
2266 }
2267 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002268 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002269 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002270 PrettyDescriptor(super).c_str(),
2271 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002272 return false;
2273 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002274
2275 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2276 if (super->IsFinalizable()) {
2277 klass->SetFinalizable();
2278 }
2279
Elliott Hughes2da50362011-10-10 16:57:08 -07002280 // Inherit reference flags (if any) from the superclass.
2281 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2282 if (reference_flags != 0) {
2283 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2284 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002285 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002286 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002287 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002288 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002289 return false;
2290 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002291
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002292#ifndef NDEBUG
2293 // Ensure super classes are fully resolved prior to resolving fields..
2294 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002295 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002296 super = super->GetSuperClass();
2297 }
2298#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299 return true;
2300}
2301
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002302// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002303bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002304 if (klass->IsInterface()) {
2305 // No vtable.
2306 size_t count = klass->NumVirtualMethods();
2307 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002308 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309 return false;
2310 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002311 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002312 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002313 }
jeffhaobdb76512011-09-07 11:43:16 -07002314 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002315 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002316 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002317 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002318 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002319 }
2320 return true;
2321}
2322
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002323bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002324 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002325 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2326 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002327 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002328 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002329 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002330 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002331 MethodHelper local_mh(NULL, this);
2332 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002333 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002334 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002335 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002336 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002337 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002338 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002339 super_mh.ChangeMethod(super_method);
2340 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002341 // Verify
2342 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002343 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002344 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002345 PrettyDescriptor(klass.get()).c_str(),
2346 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002347 return false;
2348 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002349 vtable->Set(j, local_method);
2350 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002351 break;
2352 }
2353 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002354 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002355 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002356 vtable->Set(actual_count, local_method);
2357 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358 actual_count += 1;
2359 }
2360 }
2361 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002362 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002363 return false;
2364 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002365 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002366 CHECK_LE(actual_count, max_count);
2367 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002368 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002369 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002370 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002371 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002372 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002373 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002374 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002375 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002376 return false;
2377 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002378 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002379 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002380 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2381 vtable->Set(i, virtual_method);
2382 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002383 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002384 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002385 }
2386 return true;
2387}
2388
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002389bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002390 size_t super_ifcount;
2391 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002392 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002393 } else {
2394 super_ifcount = 0;
2395 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002396 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002397 ClassHelper kh(klass.get(), this);
2398 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2399 ifcount += num_interfaces;
2400 for (size_t i = 0; i < num_interfaces; i++) {
2401 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2402 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002403 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002404 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002405 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002406 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002407 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002408 return true;
2409 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002410 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002411 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002412 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2413 for (size_t i = 0; i < super_ifcount; i++) {
2414 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2415 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002416 }
2417 // Flatten the interface inheritance hierarchy.
2418 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002419 for (size_t i = 0; i < num_interfaces; i++) {
2420 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002421 DCHECK(interface != NULL);
2422 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002423 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002424 Thread* thread = Thread::Current();
2425 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002426 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002427 PrettyDescriptor(klass.get()).c_str(),
2428 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002429 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 return false;
2431 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002432 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002433 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002434 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002435 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2436 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002437 }
2438 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002439 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002440 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002441
2442 // If we're an interface, we don't need the vtable pointers, so we're done.
2443 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002444 return true;
2445 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002446 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002447 MethodHelper vtable_mh(NULL, this);
2448 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002449 for (size_t i = 0; i < ifcount; ++i) {
2450 InterfaceEntry* interface_entry = iftable->Get(i);
2451 Class* interface = interface_entry->GetInterface();
2452 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2453 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002454 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002455 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2456 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002457 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002458 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002459 // For each method listed in the interface's method list, find the
2460 // matching method in our class's method list. We want to favor the
2461 // subclass over the superclass, which just requires walking
2462 // back from the end of the vtable. (This only matters if the
2463 // superclass defines a private method and this class redefines
2464 // it -- otherwise it would use the same vtable slot. In .dex files
2465 // those don't end up in the virtual method table, so it shouldn't
2466 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002467 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2468 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002469 vtable_mh.ChangeMethod(vtable_method);
2470 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002471 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002472 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002473 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002474 return false;
2475 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002476 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002477 break;
2478 }
2479 }
2480 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002481 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002482 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002483 Method* mir_method = miranda_list[mir];
2484 vtable_mh.ChangeMethod(mir_method);
2485 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002486 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002487 break;
2488 }
2489 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002490 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002491 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002492 miranda_method.reset(AllocMethod());
2493 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2494 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002495 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002496 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002497 }
2498 }
2499 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002500 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002501 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002502 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002503 klass->SetVirtualMethods((old_method_count == 0)
2504 ? AllocObjectArray<Method>(new_method_count)
2505 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002506
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002507 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2508 CHECK(vtable != NULL);
2509 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002510 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002511 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002512 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002513 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002514 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002515 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2516 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2517 klass->SetVirtualMethod(old_method_count + i, method);
2518 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002520 // TODO: do not assign to the vtable field until it is fully constructed.
2521 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002522 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002523
2524 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2525 for (int i = 0; i < vtable->GetLength(); ++i) {
2526 CHECK(vtable->Get(i) != NULL);
2527 }
2528
2529// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2530
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002531 return true;
2532}
2533
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002534bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2535 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002536 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002537}
2538
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002539bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2540 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002541 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002542 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002543 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002544 return success;
2545}
2546
Brian Carlstromdbc05252011-09-09 01:59:59 -07002547struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002548 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002549 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002550 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002551 fh_->ChangeField(field1);
2552 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2553 fh_->ChangeField(field2);
2554 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002555 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2556 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2557 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2558 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002559 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2560 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2561 if (order1 != order2) {
2562 return order1 < order2;
2563 }
2564
2565 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002566 fh_->ChangeField(field1);
2567 StringPiece name1(fh_->GetName());
2568 fh_->ChangeField(field2);
2569 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002570 return name1 < name2;
2571 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002572
2573 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002574};
2575
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002576bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002578 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002579
2580 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002581 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002582
2583 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002584 size_t size;
2585 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002586 if (is_static) {
2587 size = klass->GetClassSize();
2588 field_offset = Class::FieldsOffset();
2589 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002590 Class* super_class = klass->GetSuperClass();
2591 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002592 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002593 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002594 }
2595 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002596 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002597
Brian Carlstromdbc05252011-09-09 01:59:59 -07002598 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002599
Brian Carlstromdbc05252011-09-09 01:59:59 -07002600 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002601 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002602 std::deque<Field*> grouped_and_sorted_fields;
2603 for (size_t i = 0; i < num_fields; i++) {
2604 grouped_and_sorted_fields.push_back(fields->Get(i));
2605 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002606 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002607 std::sort(grouped_and_sorted_fields.begin(),
2608 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002609 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002610
2611 // References should be at the front.
2612 size_t current_field = 0;
2613 size_t num_reference_fields = 0;
2614 for (; current_field < num_fields; current_field++) {
2615 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002616 fh.ChangeField(field);
2617 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002618 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002619 if (isPrimitive) {
2620 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002621 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002622 grouped_and_sorted_fields.pop_front();
2623 num_reference_fields++;
2624 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002625 field->SetOffset(field_offset);
2626 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002627 }
2628
2629 // Now we want to pack all of the double-wide fields together. If
2630 // we're not aligned, though, we want to shuffle one 32-bit field
2631 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002632 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002633 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2634 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002635 fh.ChangeField(field);
2636 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002637 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2638 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002639 continue;
2640 }
2641 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002642 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002643 // drop the consumed field
2644 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2645 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002646 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002647 // whether we found a 32-bit field for padding or not, we advance
2648 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002649 }
2650
2651 // Alignment is good, shuffle any double-wide fields forward, and
2652 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002653 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002654 while (!grouped_and_sorted_fields.empty()) {
2655 Field* field = grouped_and_sorted_fields.front();
2656 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002657 fh.ChangeField(field);
2658 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002659 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002660 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002661 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002662 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002663 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002664 ? sizeof(uint64_t)
2665 : sizeof(uint32_t)));
2666 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002667 }
2668
Elliott Hughesadb460d2011-10-05 17:02:34 -07002669 // 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 -08002670 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2671 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002672 // We know there are no non-reference fields in the Reference classes, and we know
2673 // that 'referent' is alphabetically last, so this is easy...
2674 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002675 fh.ChangeField(fields->Get(num_fields - 1));
2676 StringPiece name(fh.GetName());
2677 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002678 --num_reference_fields;
2679 }
2680
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002681#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002682 // Make sure that all reference fields appear before
2683 // non-reference fields, and all double-wide fields are aligned.
2684 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002685 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002686 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002687 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002688 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002689 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002690 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002691 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2692 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002693 fh.ChangeField(field);
2694 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002695 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002696 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002697 is_primitive = true; // We lied above, so we have to expect a lie here.
2698 }
2699 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002700 if (!seen_non_ref) {
2701 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002702 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002703 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002704 } else {
2705 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002706 }
2707 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002708 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002709 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002710 }
2711#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002712 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002713 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002714 if (is_static) {
2715 klass->SetNumReferenceStaticFields(num_reference_fields);
2716 klass->SetClassSize(size);
2717 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002718 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002719 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002720 klass->SetObjectSize(size);
2721 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002722 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002723 return true;
2724}
2725
2726// Set the bitmap of reference offsets, refOffsets, from the ifields
2727// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002728void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002729 uint32_t reference_offsets = 0;
2730 Class* super_class = klass->GetSuperClass();
2731 if (super_class != NULL) {
2732 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002733 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002734 if (reference_offsets == CLASS_WALK_SUPER) {
2735 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002736 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002737 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002738 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002739 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002740}
2741
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002742void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002743 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002744}
2745
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002746void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002747 uint32_t reference_offsets) {
2748 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002749 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2750 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002751 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002752 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002753 // All of the fields that contain object references are guaranteed
2754 // to be at the beginning of the fields list.
2755 for (size_t i = 0; i < num_reference_fields; ++i) {
2756 // Note that byte_offset is the offset from the beginning of
2757 // object, not the offset into instance data
2758 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002759 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002760 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2761 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2762 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002763 CHECK_NE(new_bit, 0U);
2764 reference_offsets |= new_bit;
2765 } else {
2766 reference_offsets = CLASS_WALK_SUPER;
2767 break;
2768 }
2769 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002770 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002771 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002772 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002773 } else {
2774 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002775 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002776}
2777
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002778String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002779 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002780 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002781 if (resolved != NULL) {
2782 return resolved;
2783 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002784 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2785 int32_t utf16_length = dex_file.GetStringLength(string_id);
2786 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002787 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002788 dex_cache->SetResolvedString(string_idx, string);
2789 return string;
2790}
2791
2792Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002793 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002794 DexCache* dex_cache,
2795 const ClassLoader* class_loader) {
2796 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002797 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002798 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002799 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002800 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002801 // TODO: we used to throw here if resolved's class loader was not the
2802 // boot class loader. This was to permit different classes with the
2803 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002804 dex_cache->SetResolvedType(type_idx, resolved);
2805 } else {
2806 DCHECK(Thread::Current()->IsExceptionPending());
2807 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002808 }
2809 return resolved;
2810}
2811
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002812Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2813 uint32_t method_idx,
2814 DexCache* dex_cache,
2815 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002816 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002817 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2818 if (resolved != NULL) {
2819 return resolved;
2820 }
2821 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2822 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2823 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002824 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002825 return NULL;
2826 }
2827
Ian Rogers0571d352011-11-03 19:51:38 -07002828 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2829 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002830 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002831 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002832 } else if (klass->IsInterface()) {
2833 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002834 } else {
2835 resolved = klass->FindVirtualMethod(name, signature);
2836 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002837 if (resolved != NULL) {
2838 dex_cache->SetResolvedMethod(method_idx, resolved);
2839 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002840 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002841 }
2842 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002843}
2844
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002845Field* ClassLinker::ResolveField(const DexFile& dex_file,
2846 uint32_t field_idx,
2847 DexCache* dex_cache,
2848 const ClassLoader* class_loader,
2849 bool is_static) {
2850 Field* resolved = dex_cache->GetResolvedField(field_idx);
2851 if (resolved != NULL) {
2852 return resolved;
2853 }
2854 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2855 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2856 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002857 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002858 return NULL;
2859 }
2860
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002861 const char* name = dex_file.GetFieldName(field_id);
2862 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002863 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002864 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002865 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002866 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002867 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002868 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002869 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002870 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002871 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2872 }
2873 return resolved;
2874}
2875
2876Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2877 uint32_t field_idx,
2878 DexCache* dex_cache,
2879 const ClassLoader* class_loader) {
2880 Field* resolved = dex_cache->GetResolvedField(field_idx);
2881 if (resolved != NULL) {
2882 return resolved;
2883 }
2884 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2885 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2886 if (klass == NULL) {
2887 DCHECK(Thread::Current()->IsExceptionPending());
2888 return NULL;
2889 }
2890
2891 const char* name = dex_file.GetFieldName(field_id);
2892 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
2893 resolved = klass->FindField(name, type);
2894 if (resolved != NULL) {
2895 dex_cache->SetResolvedField(field_idx, resolved);
2896 } else {
2897 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002898 }
2899 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002900}
2901
Ian Rogersad25ac52011-10-04 19:13:33 -07002902const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2903 Class* declaring_class = referrer->GetDeclaringClass();
2904 DexCache* dex_cache = declaring_class->GetDexCache();
2905 const DexFile& dex_file = FindDexFile(dex_cache);
2906 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2907 return dex_file.GetShorty(method_id.proto_idx_);
2908}
2909
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002910void ClassLinker::DumpAllClasses(int flags) const {
2911 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2912 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2913 std::vector<Class*> all_classes;
2914 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002915 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002916 typedef Table::const_iterator It; // TODO: C++0x auto
2917 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2918 all_classes.push_back(it->second);
2919 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002920 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2921 all_classes.push_back(it->second);
2922 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002923 }
2924
2925 for (size_t i = 0; i < all_classes.size(); ++i) {
2926 all_classes[i]->DumpClass(std::cerr, flags);
2927 }
2928}
2929
Elliott Hughescac6cc72011-11-03 20:31:21 -07002930void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2931 MutexLock mu(classes_lock_);
2932 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2933 << classes_.size() << " allocated classes\n";
2934}
2935
Elliott Hughese27955c2011-08-26 15:21:24 -07002936size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002937 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002938 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002939}
2940
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002941pid_t ClassLinker::GetClassesLockOwner() {
2942 return classes_lock_.GetOwner();
2943}
2944
2945pid_t ClassLinker::GetDexLockOwner() {
2946 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002947}
2948
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002949void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
2950 DCHECK(!init_done_);
2951
2952 DCHECK(klass != NULL);
2953 DCHECK(klass->GetClassLoader() == NULL);
2954
2955 DCHECK(class_roots_ != NULL);
2956 DCHECK(class_roots_->Get(class_root) == NULL);
2957 class_roots_->Set(class_root, klass);
2958}
2959
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002960} // namespace art