blob: 01ba9af42fd679f99819d012de8e2175b8c45b71 [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
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800587 std::string oat_file_option_string("--oat-file=");
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800588 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() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800736 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700737 CHECK(!init_done_);
738
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700739 const std::vector<Space*>& spaces = Heap::GetSpaces();
740 for (size_t i = 0; i < spaces.size(); i++) {
741 Space* space = spaces[i] ;
742 if (space->IsImageSpace()) {
743 OatFile* oat_file = OpenOat(space);
744 CHECK(oat_file != NULL) << "Failed to open oat file for image";
745 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
746 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
747
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800748 if (i == 0) {
749 // Special case of setting up the String class early so that we can test arbitrary objects
750 // as being Strings or not
751 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
752 ->AsObjectArray<Class>()->Get(kJavaLangString);
753 String::SetClass(java_lang_String);
754 }
755
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700756 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
757 static_cast<uint32_t>(dex_caches->GetLength()));
758 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700759 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800760 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800761 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
762 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700763 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800764 LOG(FATAL) << "Failed to open dex file " << dex_file_location
765 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700766 }
767
Brian Carlstromaded5f72011-10-07 17:15:04 -0700768 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700769
Brian Carlstromdf143242011-10-10 18:05:34 -0700770 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700771 }
772 }
773 }
774
Brian Carlstroma663ea52011-08-19 23:33:41 -0700775 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
776 DCHECK(heap_bitmap != NULL);
777
Brian Carlstroma663ea52011-08-19 23:33:41 -0700778 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700779 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700780
781 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700782 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
783 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700784
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800785 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700786 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
787 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800788 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700789 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700790 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700791 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
792 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
793 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
794 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
795 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
796 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
797 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
798 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700799 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700800 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700801
802 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700803
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800804 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700805}
806
Brian Carlstrom78128a62011-09-15 17:21:19 -0700807void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700808 DCHECK(obj != NULL);
809 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700810 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700811
Elliott Hughesdbb40792011-11-18 17:05:22 -0800812 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700813 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700814 return;
815 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700816 if (obj->IsClass()) {
817 // restore class to ClassLinker::classes_ table
818 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800819 ClassHelper kh(klass, class_linker);
820 bool success = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
Ian Rogers5d76c432011-10-31 21:42:49 -0700821 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700822 return;
823 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700824}
825
826// Keep in sync with InitCallback. Anything we visit, we need to
827// reinit references to when reinitializing a ClassLinker from a
828// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700829void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
830 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700831
832 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700833 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700834 }
835
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700836 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700837 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700838 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700839 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700840 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700841 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700842 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700843 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700844
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700845 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700846}
847
Elliott Hughesa2155262011-11-16 16:26:58 -0800848void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
849 MutexLock mu(classes_lock_);
850 typedef Table::const_iterator It; // TODO: C++0x auto
851 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
852 if (!visitor(it->second, arg)) {
853 return;
854 }
855 }
856 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
857 if (!visitor(it->second, arg)) {
858 return;
859 }
860 }
861}
862
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700863ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700864 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700865 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700866 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700867 BooleanArray::ResetArrayClass();
868 ByteArray::ResetArrayClass();
869 CharArray::ResetArrayClass();
870 DoubleArray::ResetArrayClass();
871 FloatArray::ResetArrayClass();
872 IntArray::ResetArrayClass();
873 LongArray::ResetArrayClass();
874 ShortArray::ResetArrayClass();
875 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700876 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700877 STLDeleteElements(&boot_class_path_);
878 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700879}
880
881DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700882 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
883 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700884 return NULL;
885 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700886 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
887 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700888 return NULL;
889 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700890 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
891 if (strings.get() == NULL) {
892 return NULL;
893 }
894 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
895 if (types.get() == NULL) {
896 return NULL;
897 }
898 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
899 if (methods.get() == NULL) {
900 return NULL;
901 }
902 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
903 if (fields.get() == NULL) {
904 return NULL;
905 }
906 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
907 if (code_and_direct_methods.get() == NULL) {
908 return NULL;
909 }
910 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
911 if (initialized_static_storage.get() == NULL) {
912 return NULL;
913 }
914
915 dex_cache->Init(location.get(),
916 strings.get(),
917 types.get(),
918 methods.get(),
919 fields.get(),
920 code_and_direct_methods.get(),
921 initialized_static_storage.get());
922 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700923}
924
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700925CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
926 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700927}
928
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700929InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
930 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700931 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
932 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700933 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700934 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700935}
936
Brian Carlstrom4873d462011-08-21 15:23:39 -0700937Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
938 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700939 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700940 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700941 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700942 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700943}
944
Brian Carlstrom4873d462011-08-21 15:23:39 -0700945Class* ClassLinker::AllocClass(size_t class_size) {
946 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700947}
948
Jesse Wilson35baaab2011-08-10 16:18:03 -0400949Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700950 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700951}
952
953Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700954 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700955}
956
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700957ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
958 return ObjectArray<StackTraceElement>::Alloc(
959 GetClassRoot(kJavaLangStackTraceElementArrayClass),
960 length);
961}
962
Brian Carlstromaded5f72011-10-07 17:15:04 -0700963Class* EnsureResolved(Class* klass) {
964 DCHECK(klass != NULL);
965 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700966 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700967 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700968 ObjectLock lock(klass);
969 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700970 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700971 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800972 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700973 return NULL;
974 }
975 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700976 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700977 lock.Wait();
978 }
979 }
980 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700981 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700982 return NULL;
983 }
984 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700985 CHECK(klass->IsResolved()) << PrettyClass(klass);
986 CHECK(!self->IsExceptionPending())
987 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
988 return klass;
989}
990
Elliott Hughesdb7d5e92011-12-16 18:47:37 -0800991Class* ClassLinker::FindSystemClass(const char* descriptor) {
992 return FindClass(descriptor, NULL);
993}
994
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800995Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
996 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -0700997 Thread* self = Thread::Current();
998 DCHECK(self != NULL);
999 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001000 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001001 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1002 // for primitive classes that aren't backed by dex files.
1003 return FindPrimitiveClass(descriptor[0]);
1004 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001005 // Find the class in the loaded classes table.
1006 Class* klass = LookupClass(descriptor, class_loader);
1007 if (klass != NULL) {
1008 return EnsureResolved(klass);
1009 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001010 // Class is not yet loaded.
1011 if (descriptor[0] == '[') {
1012 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001013
Jesse Wilson47daf872011-11-23 11:42:45 -05001014 } else if (class_loader == NULL) {
1015 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1016 if (pair.second != NULL) {
1017 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1018 }
1019
1020 } else if (ClassLoader::UseCompileTimeClassPath()) {
1021 // first try the boot class path
1022 Class* system_class = FindSystemClass(descriptor);
1023 if (system_class != NULL) {
1024 return system_class;
1025 }
1026 CHECK(self->IsExceptionPending());
1027 self->ClearException();
1028
1029 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001030 const std::vector<const DexFile*>& class_path
1031 = ClassLoader::GetCompileTimeClassPath(class_loader);
1032 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001033 if (pair.second != NULL) {
1034 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001035 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001036
1037 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001038 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001039 ScopedThreadStateChange(self, Thread::kNative);
1040 JNIEnv* env = self->GetJniEnv();
1041 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1042 CHECK(c.get() != NULL);
1043 // TODO: cache method?
1044 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1045 CHECK(mid != NULL);
1046 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1047 if (class_name_object.get() == NULL) {
1048 return NULL;
1049 }
1050 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1051 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
Ian Rogers6b0870d2011-12-15 19:38:12 -08001052 if (!env->ExceptionOccurred()) {
1053 return Decode<Class*>(env, result.get());
1054 } else {
1055 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1056 // TODO: initialize the cause of the NCDFE to this exception
1057 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001058 }
1059
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001060 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Jesse Wilson47daf872011-11-23 11:42:45 -05001061 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001062}
1063
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001064Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001065 const ClassLoader* class_loader,
1066 const DexFile& dex_file,
1067 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001068 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001069 // Load the class from the dex file.
1070 if (!init_done_) {
1071 // finish up init of hand crafted class_roots_
1072 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001073 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001074 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001075 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001076 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001077 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001078 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001079 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001080 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001081 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001082 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001083 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001084 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001085 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001086 }
1087 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001088 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001089 }
1090 klass->SetDexCache(FindDexCache(dex_file));
1091 LoadClass(dex_file, dex_class_def, klass, class_loader);
1092 // Check for a pending exception during load
1093 Thread* self = Thread::Current();
1094 if (self->IsExceptionPending()) {
1095 return NULL;
1096 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001097 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001098 klass->SetClinitThreadId(self->GetTid());
1099 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001100 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001101 if (!success) {
1102 // We may fail to insert if we raced with another thread.
1103 klass->SetClinitThreadId(0);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001104 klass.reset(LookupClass(descriptor.data(), class_loader));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001105 CHECK(klass.get() != NULL);
1106 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001107 }
1108 // Finish loading (if necessary) by finding parents
1109 CHECK(!klass->IsLoaded());
1110 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1111 // Loading failed.
1112 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001113 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001114 lock.NotifyAll();
1115 return NULL;
1116 }
1117 CHECK(klass->IsLoaded());
1118 // Link the class (if necessary)
1119 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001120 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 // Linking failed.
1122 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001123 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001124 lock.NotifyAll();
1125 return NULL;
1126 }
1127 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001128
1129 /*
1130 * We send CLASS_PREPARE events to the debugger from here. The
1131 * definition of "preparation" is creating the static fields for a
1132 * class and initializing them to the standard default values, but not
1133 * executing any code (that comes later, during "initialization").
1134 *
1135 * We did the static preparation in LinkClass.
1136 *
1137 * The class has been prepared and resolved but possibly not yet verified
1138 * at this point.
1139 */
1140 Dbg::PostClassPrepare(klass.get());
1141
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001142 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001143}
1144
Brian Carlstrom4873d462011-08-21 15:23:39 -07001145// Precomputes size that will be needed for Class, matching LinkStaticFields
1146size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1147 const DexFile::ClassDef& dex_class_def) {
1148 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001149 size_t num_ref = 0;
1150 size_t num_32 = 0;
1151 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001152 if (class_data != NULL) {
1153 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1154 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001155 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001156 char c = descriptor[0];
1157 if (c == 'L' || c == '[') {
1158 num_ref++;
1159 } else if (c == 'J' || c == 'D') {
1160 num_64++;
1161 } else {
1162 num_32++;
1163 }
1164 }
1165 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001166 // start with generic class data
1167 size_t size = sizeof(Class);
1168 // follow with reference fields which must be contiguous at start
1169 size += (num_ref * sizeof(uint32_t));
1170 // if there are 64-bit fields to add, make sure they are aligned
1171 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1172 if (num_32 != 0) {
1173 // use an available 32-bit field for padding
1174 num_32--;
1175 }
1176 size += sizeof(uint32_t); // either way, we are adding a word
1177 DCHECK_EQ(size, RoundUp(size, 8));
1178 }
1179 // tack on any 64-bit fields now that alignment is assured
1180 size += (num_64 * sizeof(uint64_t));
1181 // tack on any remaining 32-bit fields
1182 size += (num_32 * sizeof(uint32_t));
1183 return size;
1184}
1185
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001186void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001187 // Every kind of method should at least get an invoke stub from the oat_method.
1188 // non-abstract methods also get their code pointers.
1189 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001190 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001191
1192 if (method->IsAbstract()) {
1193 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1194 return;
1195 }
1196 if (method->IsNative()) {
1197 // unregistering restores the dlsym lookup stub
1198 method->UnregisterNative();
1199 return;
1200 }
1201}
1202
Brian Carlstromf615a612011-07-23 12:50:34 -07001203void ClassLinker::LoadClass(const DexFile& dex_file,
1204 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001205 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001206 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001207 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001208 CHECK(klass->GetDexCache() != NULL);
1209 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001210 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001211 CHECK(descriptor != NULL);
1212
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001213 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001214 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001215 // Make sure that none of our runtime-only flags are set.
1216 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001217 klass->SetAccessFlags(access_flags);
1218 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001219 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001220 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001221
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001222 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001223
Ian Rogers0571d352011-11-03 19:51:38 -07001224 // Load fields fields.
1225 const byte* class_data = dex_file.GetClassData(dex_class_def);
1226 if (class_data == NULL) {
1227 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001228 }
Ian Rogers0571d352011-11-03 19:51:38 -07001229 ClassDataItemIterator it(dex_file, class_data);
1230 if (it.NumStaticFields() != 0) {
1231 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1232 }
1233 if (it.NumInstanceFields() != 0) {
1234 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1235 }
1236 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1237 SirtRef<Field> sfield(AllocField());
1238 klass->SetStaticField(i, sfield.get());
1239 LoadField(dex_file, it, klass, sfield);
1240 }
1241 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1242 SirtRef<Field> ifield(AllocField());
1243 klass->SetInstanceField(i, ifield.get());
1244 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001245 }
1246
Brian Carlstromaded5f72011-10-07 17:15:04 -07001247 UniquePtr<const OatFile::OatClass> oat_class;
1248 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001249 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001250 if (oat_file != NULL) {
1251 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1252 if (oat_dex_file != NULL) {
1253 uint32_t class_def_index;
1254 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1255 CHECK(found) << descriptor;
1256 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001257 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001258 }
1259 }
1260 }
Ian Rogers0571d352011-11-03 19:51:38 -07001261 // Load methods.
1262 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001263 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001264 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001265 }
Ian Rogers0571d352011-11-03 19:51:38 -07001266 if (it.NumVirtualMethods() != 0) {
1267 // TODO: append direct methods to class object
1268 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001269 }
Ian Rogers0571d352011-11-03 19:51:38 -07001270 size_t method_index = 0;
1271 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1272 SirtRef<Method> method(AllocMethod());
1273 klass->SetDirectMethod(i, method.get());
1274 LoadMethod(dex_file, it, klass, method);
1275 if (oat_class.get() != NULL) {
1276 LinkCode(method, oat_class.get(), method_index);
1277 }
1278 method_index++;
1279 }
1280 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1281 SirtRef<Method> method(AllocMethod());
1282 klass->SetVirtualMethod(i, method.get());
1283 LoadMethod(dex_file, it, klass, method);
1284 if (oat_class.get() != NULL) {
1285 LinkCode(method, oat_class.get(), method_index);
1286 }
1287 method_index++;
1288 }
1289 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001290}
1291
Ian Rogers0571d352011-11-03 19:51:38 -07001292void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1293 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001294 uint32_t field_idx = it.GetMemberIndex();
1295 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001296 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001297 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001298}
1299
Ian Rogers0571d352011-11-03 19:51:38 -07001300void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1301 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001302 uint32_t method_idx = it.GetMemberIndex();
1303 dst->SetDexMethodIndex(method_idx);
1304 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001305 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001306
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001307
1308 StringPiece method_name(dex_file.GetMethodName(method_id));
1309 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001310 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1311 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001312
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001313 if (method_name == "finalize") {
1314 // Create the prototype for a signature of "()V"
1315 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1316 if (void_string_id != NULL) {
1317 const DexFile::TypeId* void_type_id =
1318 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1319 if (void_type_id != NULL) {
1320 std::vector<uint16_t> no_args;
1321 const DexFile::ProtoId* finalizer_proto =
1322 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1323 if (finalizer_proto != NULL) {
1324 // We have the prototype in the dex file
1325 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1326 klass->SetFinalizable();
1327 } else {
1328 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1329 // The Enum class declares a "final" finalize() method to prevent subclasses from
1330 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1331 // subclasses, so we exclude it here.
1332 // We also want to avoid setting the flag on Object, where we know that finalize() is
1333 // empty.
1334 if (klass_descriptor != "Ljava/lang/Object;" &&
1335 klass_descriptor != "Ljava/lang/Enum;") {
1336 klass->SetFinalizable();
1337 }
1338 }
1339 }
1340 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001341 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001342 }
Ian Rogers0571d352011-11-03 19:51:38 -07001343 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001344 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001345
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001346 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1347 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1348 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1349 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1350 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1351 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001352
Brian Carlstrom934486c2011-07-12 23:42:50 -07001353 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001354}
1355
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001356void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001357 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1358 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001359}
1360
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001361void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1362 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001363 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001364 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001365}
1366
Brian Carlstromaded5f72011-10-07 17:15:04 -07001367bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001368 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001369 for (size_t i = 0; i != dex_files_.size(); ++i) {
1370 if (dex_files_[i] == &dex_file) {
1371 return true;
1372 }
1373 }
1374 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001375}
1376
Brian Carlstromaded5f72011-10-07 17:15:04 -07001377bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001378 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001379 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001380}
1381
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001382void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001383 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001384 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001385 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001386 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001387 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001388}
1389
Brian Carlstromaded5f72011-10-07 17:15:04 -07001390void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001391 {
1392 MutexLock mu(dex_lock_);
1393 if (IsDexFileRegisteredLocked(dex_file)) {
1394 return;
1395 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001396 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001397 // Don't alloc while holding the lock, since allocation may need to
1398 // suspend all threads and another thread may need the dex_lock_ to
1399 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001400 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001401 {
1402 MutexLock mu(dex_lock_);
1403 if (IsDexFileRegisteredLocked(dex_file)) {
1404 return;
1405 }
1406 RegisterDexFileLocked(dex_file, dex_cache);
1407 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001408}
1409
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001410void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001411 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001412 RegisterDexFileLocked(dex_file, dex_cache);
1413}
1414
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001415const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001416 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001417 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001418 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1419 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001420 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001421 }
1422 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001423 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001424 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001425}
1426
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001427DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001428 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001429 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001430 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001431 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001432 }
1433 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001434 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001435 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001436}
1437
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001438Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1439 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001440 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001441 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001442 CHECK(primitive_class != NULL);
1443 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001444 primitive_class->SetPrimitiveType(type);
1445 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001446 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001447 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1448 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001449}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001450
Brian Carlstrombe977852011-07-19 14:54:54 -07001451// Create an array class (i.e. the class object for the array, not the
1452// array itself). "descriptor" looks like "[C" or "[[[[B" or
1453// "[Ljava/lang/String;".
1454//
1455// If "descriptor" refers to an array of primitives, look up the
1456// primitive type's internally-generated class object.
1457//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001458// "class_loader" is the class loader of the class that's referring to
1459// us. It's used to ensure that we're looking for the element type in
1460// the right context. It does NOT become the class loader for the
1461// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001462//
1463// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001464Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001465 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001466
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001467 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001468 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001469 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001470 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001471 return NULL;
1472 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001473
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001474 // See if the component type is already loaded. Array classes are
1475 // always associated with the class loader of their underlying
1476 // element type -- an array of Strings goes with the loader for
1477 // java/lang/String -- so we need to look for it there. (The
1478 // caller should have checked for the existence of the class
1479 // before calling here, but they did so with *their* class loader,
1480 // not the component type's loader.)
1481 //
1482 // If we find it, the caller adds "loader" to the class' initiating
1483 // loader list, which should prevent us from going through this again.
1484 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001485 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001486 // are the same, because our caller (FindClass) just did the
1487 // lookup. (Even if we get this wrong we still have correct behavior,
1488 // because we effectively do this lookup again when we add the new
1489 // class to the hash table --- necessary because of possible races with
1490 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001491 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001492 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001493 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001494 return new_class;
1495 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001496 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001497
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001498 // Fill out the fields in the Class.
1499 //
1500 // It is possible to execute some methods against arrays, because
1501 // all arrays are subclasses of java_lang_Object_, so we need to set
1502 // up a vtable. We can just point at the one in java_lang_Object_.
1503 //
1504 // Array classes are simple enough that we don't need to do a full
1505 // link step.
1506
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001507 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001508 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001509 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001510 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001511 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001512 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001513 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001514 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001515 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001516 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001517 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001518 }
1519 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001520 if (new_class.get() == NULL) {
1521 new_class.reset(AllocClass(sizeof(Class)));
1522 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001523 return NULL;
1524 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001525 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001526 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001527 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001528 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001529 new_class->SetSuperClass(java_lang_Object);
1530 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001531 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001532 new_class->SetClassLoader(component_type->GetClassLoader());
1533 new_class->SetStatus(Class::kStatusInitialized);
1534 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001535 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001536
1537
1538 // All arrays have java/lang/Cloneable and java/io/Serializable as
1539 // interfaces. We need to set that up here, so that stuff like
1540 // "instanceof" works right.
1541 //
1542 // Note: The GC could run during the call to FindSystemClass,
1543 // so we need to make sure the class object is GC-valid while we're in
1544 // there. Do this by clearing the interface list so the GC will just
1545 // think that the entries are null.
1546
1547
1548 // Use the single, global copies of "interfaces" and "iftable"
1549 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001550 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001551 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001552
1553 // Inherit access flags from the component type. Arrays can't be
1554 // used as a superclass or interface, so we want to add "final"
1555 // and remove "interface".
1556 //
1557 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001558 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001559 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001560 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1561 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001562
Ian Rogers5d76c432011-10-31 21:42:49 -07001563 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001564 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001565 }
1566 // Another thread must have loaded the class after we
1567 // started but before we finished. Abandon what we've
1568 // done.
1569 //
1570 // (Yes, this happens.)
1571
1572 // Grab the winning class.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001573 Class* other_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001574 DCHECK(other_class != NULL);
1575 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001576}
1577
1578Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001579 switch (Primitive::GetType(type)) {
1580 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001581 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001582 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001583 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001584 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001585 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001586 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001587 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001588 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001589 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001590 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001591 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001592 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001593 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001594 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001595 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001596 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001597 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001598 case Primitive::kPrimNot:
1599 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001600 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001601 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001602 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001603 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001604}
1605
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001606bool ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001607 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001608 DexCache* dex_cache = klass->GetDexCache();
1609 std::string source;
1610 if (dex_cache != NULL) {
1611 source += " from ";
1612 source += dex_cache->GetLocation()->ToModifiedUtf8();
1613 }
1614 LOG(INFO) << "Loaded class " << descriptor << source;
1615 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001616 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001617 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001618 Table::iterator it;
1619 if (image_class) {
1620 // TODO: sanity check there's no match in classes_
1621 it = image_classes_.insert(std::make_pair(hash, klass));
1622 } else {
1623 // TODO: sanity check there's no match in image_classes_
1624 it = classes_.insert(std::make_pair(hash, klass));
1625 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001626 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001627}
1628
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001629bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1630 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001631 MutexLock mu(classes_lock_);
1632 typedef Table::const_iterator It; // TODO: C++0x auto
1633 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001634 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001635 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1636 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001637 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001638 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001639 classes_.erase(it);
1640 return true;
1641 }
1642 }
1643 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1644 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001645 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001646 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001647 image_classes_.erase(it);
1648 return true;
1649 }
1650 }
1651 return false;
1652}
1653
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001654Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1655 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001656 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001657 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001658 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001659 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001660 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001661 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001662 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001663 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001664 return klass;
1665 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001666 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001667 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1668 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001669 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001670 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001671 return klass;
1672 }
1673 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001674 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001675}
1676
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001677void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001678 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001679 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001680 MutexLock mu(classes_lock_);
1681 typedef Table::const_iterator It; // TODO: C++0x auto
1682 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001683 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001684 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001685 Class* klass = it->second;
1686 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001687 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001688 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001689 }
1690 }
1691 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001692 Class* klass = it->second;
1693 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001694 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001695 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001696 }
1697 }
1698}
1699
jeffhao98eacac2011-09-14 16:11:53 -07001700void ClassLinker::VerifyClass(Class* klass) {
1701 if (klass->IsVerified()) {
1702 return;
1703 }
1704
1705 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001706 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001707
Ian Rogersd81871c2011-10-03 13:57:23 -07001708 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001709 klass->SetStatus(Class::kStatusVerified);
1710 } else {
1711 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001712 Thread* self = Thread::Current();
1713 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1714 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001715 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001716 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001717 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001718 }
jeffhao98eacac2011-09-14 16:11:53 -07001719}
1720
Ian Rogersc2b44472011-12-14 21:17:17 -08001721static void CheckProxyConstructor(Method* constructor);
1722static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1723
Jesse Wilson95caa792011-10-12 18:14:17 -04001724Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001725 ClassLoader* loader, ObjectArray<Method>* methods,
1726 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001727 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001728 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001729 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001730 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001731 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001732 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001733 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001734 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001735 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001736 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001737
1738 klass->SetStatus(Class::kStatusIdx);
1739
1740 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1741
1742 // Create static field that holds throws, instance fields are inherited
1743 klass->SetSFields(AllocObjectArray<Field>(1));
1744 SirtRef<Field> sfield(AllocField());
1745 klass->SetStaticField(0, sfield.get());
1746 sfield->SetDexFieldIndex(-1);
1747 sfield->SetDeclaringClass(klass.get());
1748 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001749
Ian Rogers466bb252011-10-14 03:29:56 -07001750 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001751 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001752 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001753
Ian Rogers466bb252011-10-14 03:29:56 -07001754 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001755 size_t num_virtual_methods = methods->GetLength();
1756 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1757 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001758 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001759 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001760 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001761
1762 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1763 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1764 DCHECK(!Thread::Current()->IsExceptionPending());
1765
1766 // Link the fields and virtual methods, creating vtable and iftables
1767 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001768 DCHECK(Thread::Current()->IsExceptionPending());
1769 return NULL;
1770 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001771 sfield->SetObject(NULL, throws); // initialize throws field
1772 klass->SetStatus(Class::kStatusInitialized);
1773
1774 // sanity checks
1775#ifndef NDEBUG
1776 bool debug = true;
1777#else
1778 bool debug = false;
1779#endif
1780 if (debug) {
1781 CHECK(klass->GetIFields() == NULL);
1782 CheckProxyConstructor(klass->GetDirectMethod(0));
1783 for (size_t i = 0; i < num_virtual_methods; ++i) {
1784 SirtRef<Method> prototype(methods->Get(i));
1785 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1786 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001787 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08001788 throws_field_name += name->ToModifiedUtf8();
1789 throws_field_name += ".throws";
1790 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1791
1792 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1793 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1794 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001795 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001796}
1797
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001798std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1799 DCHECK(proxy_class->IsProxyClass());
1800 String* name = proxy_class->GetName();
1801 DCHECK(name != NULL);
1802 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1803}
1804
1805
1806Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001807 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001808 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001809 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001810 Method* proxy_constructor = proxy_direct_methods->Get(2);
1811 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1812 // code_ too)
1813 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1814 // Make this constructor public and fix the class to be our Proxy version
1815 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001816 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001817 return constructor;
1818}
1819
1820static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001821 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001822 MethodHelper mh(constructor);
1823 CHECK_STREQ(mh.GetName(), "<init>");
1824 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001825 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001826}
1827
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001828Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1829 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1830 // prototype method
1831 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1832 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001833 // as necessary
1834 Method* method = down_cast<Method*>(prototype->Clone());
1835
1836 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1837 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001838 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001839 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001840
Ian Rogers466bb252011-10-14 03:29:56 -07001841 // At runtime the method looks like a reference and argument saving method, clone the code
1842 // related parameters from this method.
1843 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1844 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1845 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1846 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1847 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001848 return method;
1849}
Jesse Wilson95caa792011-10-12 18:14:17 -04001850
Ian Rogersc2b44472011-12-14 21:17:17 -08001851static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001852 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001853 CHECK(!prototype->IsFinal());
1854 CHECK(method->IsFinal());
1855 CHECK(!method->IsAbstract());
1856 MethodHelper mh(method);
1857 const char* method_name = mh.GetName();
1858 const char* method_shorty = mh.GetShorty();
1859 Class* method_return = mh.GetReturnType();
1860
1861 mh.ChangeMethod(prototype.get());
1862
1863 CHECK_STREQ(mh.GetName(), method_name);
1864 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001865
1866 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001867 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001868}
1869
Brian Carlstrom25c33252011-09-18 15:58:35 -07001870bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001871 CHECK(klass->IsResolved() || klass->IsErroneous())
1872 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001873
Carl Shapirob5573532011-07-12 18:22:59 -07001874 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001875
Brian Carlstrom25c33252011-09-18 15:58:35 -07001876 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001877 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001878 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001879 ObjectLock lock(klass);
1880
Brian Carlstromd1422f82011-09-28 11:37:09 -07001881 if (klass->GetStatus() == Class::kStatusInitialized) {
1882 return true;
1883 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001884
Brian Carlstromd1422f82011-09-28 11:37:09 -07001885 if (klass->IsErroneous()) {
1886 ThrowEarlierClassFailure(klass);
1887 return false;
1888 }
1889
1890 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001891 VerifyClass(klass);
1892 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001893 return false;
1894 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001895 }
1896
Brian Carlstrom25c33252011-09-18 15:58:35 -07001897 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1898 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001899 // if the class has a <clinit> but we can't run it during compilation,
1900 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001901 return false;
1902 }
1903
Brian Carlstromd1422f82011-09-28 11:37:09 -07001904 // If the class is kStatusInitializing, either this thread is
1905 // initializing higher up the stack or another thread has beat us
1906 // to initializing and we need to wait. Either way, this
1907 // invocation of InitializeClass will not be responsible for
1908 // running <clinit> and will return.
1909 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001910 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001911 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001912 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001913 return true;
1914 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001915 // No. That's fine. Wait for another thread to finish initializing.
1916 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001917 }
1918
1919 if (!ValidateSuperClassDescriptors(klass)) {
1920 klass->SetStatus(Class::kStatusError);
1921 return false;
1922 }
1923
Brian Carlstromd1422f82011-09-28 11:37:09 -07001924 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001925
Elliott Hughesdcc24742011-09-07 14:02:44 -07001926 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001927 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001928 }
1929
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001930 uint64_t t0 = NanoTime();
1931
Brian Carlstrom25c33252011-09-18 15:58:35 -07001932 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001933 return false;
1934 }
1935
1936 InitializeStaticFields(klass);
1937
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001938 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001939 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001940 }
1941
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001942 uint64_t t1 = NanoTime();
1943
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001944 {
1945 ObjectLock lock(klass);
1946
1947 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001948 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001949 klass->SetStatus(Class::kStatusError);
1950 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001951 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1952 RuntimeStats* thread_stats = self->GetStats();
1953 ++global_stats->class_init_count;
1954 ++thread_stats->class_init_count;
1955 global_stats->class_init_time_ns += (t1 - t0);
1956 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001957 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001958 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001959 ClassHelper kh(klass);
1960 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08001961 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001962 }
1963 lock.NotifyAll();
1964 }
1965
1966 return true;
1967}
1968
Brian Carlstromd1422f82011-09-28 11:37:09 -07001969bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1970 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001971 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001972 lock.Wait();
1973
1974 // When we wake up, repeat the test for init-in-progress. If
1975 // there's an exception pending (only possible if
1976 // "interruptShouldThrow" was set), bail out.
1977 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001978 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001979 klass->SetStatus(Class::kStatusError);
1980 return false;
1981 }
1982 // Spurious wakeup? Go back to waiting.
1983 if (klass->GetStatus() == Class::kStatusInitializing) {
1984 continue;
1985 }
1986 if (klass->IsErroneous()) {
1987 // The caller wants an exception, but it was thrown in a
1988 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001989 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001990 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001991 return false;
1992 }
1993 if (klass->IsInitialized()) {
1994 return true;
1995 }
1996 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1997 }
1998 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1999}
2000
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002001bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2002 if (klass->IsInterface()) {
2003 return true;
2004 }
2005 // begin with the methods local to the superclass
2006 if (klass->HasSuperClass() &&
2007 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2008 const Class* super = klass->GetSuperClass();
2009 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002010 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002011 if (method != super->GetVirtualMethod(i) &&
2012 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002013 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2014
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002015 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2016 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2017 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002018 return false;
2019 }
2020 }
2021 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002022 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2023 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2024 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002025 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2026 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002027 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002028 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002029 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002030 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2031
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002032 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2033 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2034 PrettyMethod(method).c_str(),
2035 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002036 return false;
2037 }
2038 }
2039 }
2040 }
2041 return true;
2042}
2043
2044bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002045 const Class* klass1,
2046 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002047 if (klass1 == klass2) {
2048 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002049 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002050 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002051 const DexFile::ProtoId& proto_id =
2052 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002053 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2054 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002055 if (descriptor == NULL) {
2056 break;
2057 }
2058 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2059 // Found a non-primitive type.
2060 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2061 return false;
2062 }
2063 }
2064 }
2065 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002066 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002067 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002068 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002069 return false;
2070 }
2071 }
2072 return true;
2073}
2074
2075// Returns true if classes referenced by the descriptor are the
2076// same classes in klass1 as they are in klass2.
2077bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002078 const Class* klass1,
2079 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002080 CHECK(descriptor != NULL);
2081 CHECK(klass1 != NULL);
2082 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002083 if (klass1 == klass2) {
2084 return true;
2085 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002086 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002087 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002088 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002089 // TODO: found2 == NULL
2090 // TODO: lookup found1 in initiating loader list
2091 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002092 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002093 return found1 == found2;
2094 } else {
2095 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002096 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002097}
2098
Brian Carlstrom25c33252011-09-18 15:58:35 -07002099bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002100 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002101 if (!klass->IsInterface() && klass->HasSuperClass()) {
2102 Class* super_class = klass->GetSuperClass();
2103 if (super_class->GetStatus() != Class::kStatusInitialized) {
2104 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002105 Thread* self = Thread::Current();
2106 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002107 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002108 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002109 // TODO: check for a pending exception
2110 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002111 if (!can_run_clinit) {
2112 // Don't set status to error when we can't run <clinit>.
2113 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2114 klass->SetStatus(Class::kStatusVerified);
2115 return false;
2116 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002117 klass->SetStatus(Class::kStatusError);
2118 klass->NotifyAll();
2119 return false;
2120 }
2121 }
2122 }
2123 return true;
2124}
2125
Brian Carlstrom25c33252011-09-18 15:58:35 -07002126bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002127 CHECK(c != NULL);
2128 if (c->IsInitialized()) {
2129 return true;
2130 }
2131
Elliott Hughes5f791332011-09-15 17:45:30 -07002132 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002133 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002134 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002135 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002136}
2137
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002138void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002139 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002140 const ClassLoader* cl = c->GetClassLoader();
2141 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002142 ClassDataItemIterator it(dex_file, class_data);
2143 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2144 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002145 }
2146}
2147
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002148void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002149 size_t num_static_fields = klass->NumStaticFields();
2150 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002151 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002152 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002153 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002154 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002155 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002156 return;
2157 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002158 ClassHelper kh(klass);
2159 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002160 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002161 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002162 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002163
Ian Rogers0571d352011-11-03 19:51:38 -07002164 if (it.HasNext()) {
2165 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2166 std::map<uint32_t, Field*> field_map;
2167 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2168 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2169 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002170 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002171 }
2172}
2173
Ian Rogersc2b44472011-12-14 21:17:17 -08002174bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002175 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002176 if (!LinkSuperClass(klass)) {
2177 return false;
2178 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002179 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002180 return false;
2181 }
2182 if (!LinkInstanceFields(klass)) {
2183 return false;
2184 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002185 if (!LinkStaticFields(klass)) {
2186 return false;
2187 }
2188 CreateReferenceInstanceOffsets(klass);
2189 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002190 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2191 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002192 return true;
2193}
2194
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002195bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002196 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002197 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2198 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2199 if (class_def == NULL) {
2200 return false;
2201 }
2202 uint16_t super_class_idx = class_def->superclass_idx_;
2203 if (super_class_idx != DexFile::kDexNoIndex16) {
2204 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002205 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002206 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002207 return false;
2208 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002209 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002210 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002211 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2212 if (interfaces != NULL) {
2213 for (size_t i = 0; i < interfaces->Size(); i++) {
2214 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2215 Class* interface = ResolveType(dex_file, idx, klass.get());
2216 if (interface == NULL) {
2217 DCHECK(Thread::Current()->IsExceptionPending());
2218 return false;
2219 }
2220 // Verify
2221 if (!klass->CanAccess(interface)) {
2222 // TODO: the RI seemed to ignore this in my testing.
2223 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2224 "Interface %s implemented by class %s is inaccessible",
2225 PrettyDescriptor(interface).c_str(),
2226 PrettyDescriptor(klass.get()).c_str());
2227 return false;
2228 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002229 }
2230 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002231 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002232 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002233 return true;
2234}
2235
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002236bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002237 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002238 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002239 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002240 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002241 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002242 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002243 return false;
2244 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002245 return true;
2246 }
2247 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002248 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002249 return false;
2250 }
2251 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002252 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002253 Thread* thread = Thread::Current();
2254 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002255 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002256 PrettyDescriptor(super).c_str(),
2257 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002258 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002259 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002260 return false;
2261 }
2262 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002263 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002264 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002265 PrettyDescriptor(super).c_str(),
2266 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002267 return false;
2268 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002269
2270 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2271 if (super->IsFinalizable()) {
2272 klass->SetFinalizable();
2273 }
2274
Elliott Hughes2da50362011-10-10 16:57:08 -07002275 // Inherit reference flags (if any) from the superclass.
2276 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2277 if (reference_flags != 0) {
2278 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2279 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002280 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002281 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002282 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002283 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002284 return false;
2285 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002286
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002287#ifndef NDEBUG
2288 // Ensure super classes are fully resolved prior to resolving fields..
2289 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002290 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002291 super = super->GetSuperClass();
2292 }
2293#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 return true;
2295}
2296
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002297// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002298bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299 if (klass->IsInterface()) {
2300 // No vtable.
2301 size_t count = klass->NumVirtualMethods();
2302 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002303 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002304 return false;
2305 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002306 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002307 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002308 }
jeffhaobdb76512011-09-07 11:43:16 -07002309 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002310 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002311 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002312 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002313 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002314 }
2315 return true;
2316}
2317
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002318bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002319 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002320 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2321 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002322 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002323 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002324 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002325 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002326 MethodHelper local_mh(NULL, this);
2327 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002328 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002329 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002330 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002331 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002332 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002333 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002334 super_mh.ChangeMethod(super_method);
2335 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002336 // Verify
2337 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002338 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002339 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002340 PrettyDescriptor(klass.get()).c_str(),
2341 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002342 return false;
2343 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002344 vtable->Set(j, local_method);
2345 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002346 break;
2347 }
2348 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002349 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002350 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002351 vtable->Set(actual_count, local_method);
2352 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002353 actual_count += 1;
2354 }
2355 }
2356 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002357 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358 return false;
2359 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002360 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002361 CHECK_LE(actual_count, max_count);
2362 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002363 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002364 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002365 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002366 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002367 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002368 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002369 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002370 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002371 return false;
2372 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002373 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002374 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002375 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2376 vtable->Set(i, virtual_method);
2377 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002378 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002379 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002380 }
2381 return true;
2382}
2383
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002384bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002385 size_t super_ifcount;
2386 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002387 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002388 } else {
2389 super_ifcount = 0;
2390 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002391 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002392 ClassHelper kh(klass.get(), this);
2393 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2394 ifcount += num_interfaces;
2395 for (size_t i = 0; i < num_interfaces; i++) {
2396 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2397 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002398 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002399 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002400 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002401 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002402 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002403 return true;
2404 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002405 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002406 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002407 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2408 for (size_t i = 0; i < super_ifcount; i++) {
2409 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2410 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002411 }
2412 // Flatten the interface inheritance hierarchy.
2413 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002414 for (size_t i = 0; i < num_interfaces; i++) {
2415 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002416 DCHECK(interface != NULL);
2417 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002418 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002419 Thread* thread = Thread::Current();
2420 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002421 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002422 PrettyDescriptor(klass.get()).c_str(),
2423 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002424 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002425 return false;
2426 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002427 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002428 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002429 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002430 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2431 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002432 }
2433 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002434 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002435 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002436
2437 // If we're an interface, we don't need the vtable pointers, so we're done.
2438 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002439 return true;
2440 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002441 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002442 MethodHelper vtable_mh(NULL, this);
2443 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002444 for (size_t i = 0; i < ifcount; ++i) {
2445 InterfaceEntry* interface_entry = iftable->Get(i);
2446 Class* interface = interface_entry->GetInterface();
2447 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2448 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002449 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002450 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2451 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002452 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002453 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002454 // For each method listed in the interface's method list, find the
2455 // matching method in our class's method list. We want to favor the
2456 // subclass over the superclass, which just requires walking
2457 // back from the end of the vtable. (This only matters if the
2458 // superclass defines a private method and this class redefines
2459 // it -- otherwise it would use the same vtable slot. In .dex files
2460 // those don't end up in the virtual method table, so it shouldn't
2461 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002462 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2463 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002464 vtable_mh.ChangeMethod(vtable_method);
2465 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002466 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002467 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002468 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002469 return false;
2470 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002471 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002472 break;
2473 }
2474 }
2475 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002476 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002477 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002478 Method* mir_method = miranda_list[mir];
2479 vtable_mh.ChangeMethod(mir_method);
2480 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002481 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002482 break;
2483 }
2484 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002485 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002486 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002487 miranda_method.reset(AllocMethod());
2488 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2489 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002490 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002491 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002492 }
2493 }
2494 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002495 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002496 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002497 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002498 klass->SetVirtualMethods((old_method_count == 0)
2499 ? AllocObjectArray<Method>(new_method_count)
2500 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002501
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002502 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2503 CHECK(vtable != NULL);
2504 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002505 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002506 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002507 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002508 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002509 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002510 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2511 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2512 klass->SetVirtualMethod(old_method_count + i, method);
2513 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002514 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002515 // TODO: do not assign to the vtable field until it is fully constructed.
2516 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002517 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002518
2519 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2520 for (int i = 0; i < vtable->GetLength(); ++i) {
2521 CHECK(vtable->Get(i) != NULL);
2522 }
2523
2524// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2525
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002526 return true;
2527}
2528
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002529bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2530 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002531 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002532}
2533
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002534bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2535 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002536 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002537 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002538 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002539 return success;
2540}
2541
Brian Carlstromdbc05252011-09-09 01:59:59 -07002542struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002543 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002544 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002545 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002546 fh_->ChangeField(field1);
2547 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2548 fh_->ChangeField(field2);
2549 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002550 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2551 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2552 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2553 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002554 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2555 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2556 if (order1 != order2) {
2557 return order1 < order2;
2558 }
2559
2560 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002561 fh_->ChangeField(field1);
2562 StringPiece name1(fh_->GetName());
2563 fh_->ChangeField(field2);
2564 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002565 return name1 < name2;
2566 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002567
2568 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002569};
2570
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002571bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002572 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002573 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002574
2575 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002576 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577
2578 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002579 size_t size;
2580 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002581 if (is_static) {
2582 size = klass->GetClassSize();
2583 field_offset = Class::FieldsOffset();
2584 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002585 Class* super_class = klass->GetSuperClass();
2586 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002587 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002588 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002589 }
2590 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002591 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002592
Brian Carlstromdbc05252011-09-09 01:59:59 -07002593 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002594
Brian Carlstromdbc05252011-09-09 01:59:59 -07002595 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002596 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002597 std::deque<Field*> grouped_and_sorted_fields;
2598 for (size_t i = 0; i < num_fields; i++) {
2599 grouped_and_sorted_fields.push_back(fields->Get(i));
2600 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002601 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002602 std::sort(grouped_and_sorted_fields.begin(),
2603 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002604 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002605
2606 // References should be at the front.
2607 size_t current_field = 0;
2608 size_t num_reference_fields = 0;
2609 for (; current_field < num_fields; current_field++) {
2610 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002611 fh.ChangeField(field);
2612 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002613 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002614 if (isPrimitive) {
2615 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002616 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002617 grouped_and_sorted_fields.pop_front();
2618 num_reference_fields++;
2619 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002620 field->SetOffset(field_offset);
2621 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002622 }
2623
2624 // Now we want to pack all of the double-wide fields together. If
2625 // we're not aligned, though, we want to shuffle one 32-bit field
2626 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002627 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002628 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2629 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002630 fh.ChangeField(field);
2631 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002632 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2633 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002634 continue;
2635 }
2636 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002637 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002638 // drop the consumed field
2639 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2640 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002641 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002642 // whether we found a 32-bit field for padding or not, we advance
2643 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002644 }
2645
2646 // Alignment is good, shuffle any double-wide fields forward, and
2647 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002648 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002649 while (!grouped_and_sorted_fields.empty()) {
2650 Field* field = grouped_and_sorted_fields.front();
2651 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002652 fh.ChangeField(field);
2653 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002654 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002655 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002656 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002657 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002658 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002659 ? sizeof(uint64_t)
2660 : sizeof(uint32_t)));
2661 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002662 }
2663
Elliott Hughesadb460d2011-10-05 17:02:34 -07002664 // 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 -08002665 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2666 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002667 // We know there are no non-reference fields in the Reference classes, and we know
2668 // that 'referent' is alphabetically last, so this is easy...
2669 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002670 fh.ChangeField(fields->Get(num_fields - 1));
2671 StringPiece name(fh.GetName());
2672 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002673 --num_reference_fields;
2674 }
2675
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002676#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002677 // Make sure that all reference fields appear before
2678 // non-reference fields, and all double-wide fields are aligned.
2679 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002680 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002681 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002682 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002683 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002684 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002685 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002686 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2687 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002688 fh.ChangeField(field);
2689 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002690 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002691 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002692 is_primitive = true; // We lied above, so we have to expect a lie here.
2693 }
2694 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002695 if (!seen_non_ref) {
2696 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002697 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002698 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002699 } else {
2700 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002701 }
2702 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002703 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002704 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002705 }
2706#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002707 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002708 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002709 if (is_static) {
2710 klass->SetNumReferenceStaticFields(num_reference_fields);
2711 klass->SetClassSize(size);
2712 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002713 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002714 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002715 klass->SetObjectSize(size);
2716 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002717 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002718 return true;
2719}
2720
2721// Set the bitmap of reference offsets, refOffsets, from the ifields
2722// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002723void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002724 uint32_t reference_offsets = 0;
2725 Class* super_class = klass->GetSuperClass();
2726 if (super_class != NULL) {
2727 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002728 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002729 if (reference_offsets == CLASS_WALK_SUPER) {
2730 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002731 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002732 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002733 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002734 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002735}
2736
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002737void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002738 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002739}
2740
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002741void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002742 uint32_t reference_offsets) {
2743 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002744 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2745 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002746 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002747 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002748 // All of the fields that contain object references are guaranteed
2749 // to be at the beginning of the fields list.
2750 for (size_t i = 0; i < num_reference_fields; ++i) {
2751 // Note that byte_offset is the offset from the beginning of
2752 // object, not the offset into instance data
2753 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002754 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002755 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2756 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2757 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002758 CHECK_NE(new_bit, 0U);
2759 reference_offsets |= new_bit;
2760 } else {
2761 reference_offsets = CLASS_WALK_SUPER;
2762 break;
2763 }
2764 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002765 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002766 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002767 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002768 } else {
2769 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002770 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002771}
2772
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002773String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002774 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002775 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002776 if (resolved != NULL) {
2777 return resolved;
2778 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002779 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2780 int32_t utf16_length = dex_file.GetStringLength(string_id);
2781 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002782 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002783 dex_cache->SetResolvedString(string_idx, string);
2784 return string;
2785}
2786
2787Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002788 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002789 DexCache* dex_cache,
2790 const ClassLoader* class_loader) {
2791 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002792 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002793 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002794 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002795 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002796 // TODO: we used to throw here if resolved's class loader was not the
2797 // boot class loader. This was to permit different classes with the
2798 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002799 dex_cache->SetResolvedType(type_idx, resolved);
2800 } else {
2801 DCHECK(Thread::Current()->IsExceptionPending());
2802 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002803 }
2804 return resolved;
2805}
2806
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002807Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2808 uint32_t method_idx,
2809 DexCache* dex_cache,
2810 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002811 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002812 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2813 if (resolved != NULL) {
2814 return resolved;
2815 }
2816 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2817 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2818 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002819 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002820 return NULL;
2821 }
2822
Ian Rogers0571d352011-11-03 19:51:38 -07002823 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2824 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002825 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002826 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002827 } else if (klass->IsInterface()) {
2828 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002829 } else {
2830 resolved = klass->FindVirtualMethod(name, signature);
2831 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002832 if (resolved != NULL) {
2833 dex_cache->SetResolvedMethod(method_idx, resolved);
2834 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002835 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002836 }
2837 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002838}
2839
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002840Field* ClassLinker::ResolveField(const DexFile& dex_file,
2841 uint32_t field_idx,
2842 DexCache* dex_cache,
2843 const ClassLoader* class_loader,
2844 bool is_static) {
2845 Field* resolved = dex_cache->GetResolvedField(field_idx);
2846 if (resolved != NULL) {
2847 return resolved;
2848 }
2849 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2850 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2851 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002852 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002853 return NULL;
2854 }
2855
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002856 const char* name = dex_file.GetFieldName(field_id);
2857 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002858 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002859 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002860 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002861 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002862 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002863 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002864 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002865 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002866 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2867 }
2868 return resolved;
2869}
2870
2871Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2872 uint32_t field_idx,
2873 DexCache* dex_cache,
2874 const ClassLoader* class_loader) {
2875 Field* resolved = dex_cache->GetResolvedField(field_idx);
2876 if (resolved != NULL) {
2877 return resolved;
2878 }
2879 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2880 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2881 if (klass == NULL) {
2882 DCHECK(Thread::Current()->IsExceptionPending());
2883 return NULL;
2884 }
2885
2886 const char* name = dex_file.GetFieldName(field_id);
2887 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
2888 resolved = klass->FindField(name, type);
2889 if (resolved != NULL) {
2890 dex_cache->SetResolvedField(field_idx, resolved);
2891 } else {
2892 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002893 }
2894 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002895}
2896
Ian Rogersad25ac52011-10-04 19:13:33 -07002897const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2898 Class* declaring_class = referrer->GetDeclaringClass();
2899 DexCache* dex_cache = declaring_class->GetDexCache();
2900 const DexFile& dex_file = FindDexFile(dex_cache);
2901 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2902 return dex_file.GetShorty(method_id.proto_idx_);
2903}
2904
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002905void ClassLinker::DumpAllClasses(int flags) const {
2906 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2907 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2908 std::vector<Class*> all_classes;
2909 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002910 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002911 typedef Table::const_iterator It; // TODO: C++0x auto
2912 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2913 all_classes.push_back(it->second);
2914 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002915 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2916 all_classes.push_back(it->second);
2917 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002918 }
2919
2920 for (size_t i = 0; i < all_classes.size(); ++i) {
2921 all_classes[i]->DumpClass(std::cerr, flags);
2922 }
2923}
2924
Elliott Hughescac6cc72011-11-03 20:31:21 -07002925void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2926 MutexLock mu(classes_lock_);
2927 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2928 << classes_.size() << " allocated classes\n";
2929}
2930
Elliott Hughese27955c2011-08-26 15:21:24 -07002931size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002932 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002933 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002934}
2935
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002936pid_t ClassLinker::GetClassesLockOwner() {
2937 return classes_lock_.GetOwner();
2938}
2939
2940pid_t ClassLinker::GetDexLockOwner() {
2941 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002942}
2943
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002944void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
2945 DCHECK(!init_done_);
2946
2947 DCHECK(klass != NULL);
2948 DCHECK(klass->GetClassLoader() == NULL);
2949
2950 DCHECK(class_roots_ != NULL);
2951 DCHECK(class_roots_->Get(class_root) == NULL);
2952 class_roots_->Set(class_root, klass);
2953}
2954
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002955} // namespace art