blob: ff8e17978bf26a0af6234ec5c61d0b3ac6a208da [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 Hughes362f9bc2011-10-17 18:56:41 -0700139} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700140
Elliott Hughes418d20f2011-09-22 14:00:39 -0700141const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700142 "Ljava/lang/Class;",
143 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700144 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700145 "[Ljava/lang/Object;",
146 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700147 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700148 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700149 "Ljava/lang/reflect/Field;",
150 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700151 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700152 "Ljava/lang/ClassLoader;",
153 "Ldalvik/system/BaseDexClassLoader;",
154 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700155 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700156 "Z",
157 "B",
158 "C",
159 "D",
160 "F",
161 "I",
162 "J",
163 "S",
164 "V",
165 "[Z",
166 "[B",
167 "[C",
168 "[D",
169 "[F",
170 "[I",
171 "[J",
172 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700173 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700174};
175
Elliott Hughes5f791332011-09-15 17:45:30 -0700176class ObjectLock {
177 public:
178 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
179 CHECK(object != NULL);
180 obj_->MonitorEnter(self_);
181 }
182
183 ~ObjectLock() {
184 obj_->MonitorExit(self_);
185 }
186
187 void Wait() {
188 return Monitor::Wait(self_, obj_, 0, 0, false);
189 }
190
191 void Notify() {
192 obj_->Notify();
193 }
194
195 void NotifyAll() {
196 obj_->NotifyAll();
197 }
198
199 private:
200 Thread* self_;
201 Object* obj_;
202 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
203};
204
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800205ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700206 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800207 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700208 class_linker->Init(boot_class_path);
209 return class_linker.release();
210}
211
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800212ClassLinker* ClassLinker::Create(InternTable* intern_table) {
213 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700214 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700215 return class_linker.release();
216}
217
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800218ClassLinker::ClassLinker(InternTable* intern_table)
219 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700220 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700221 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700222 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700223 init_done_(false),
224 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700225 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700226}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700227
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700228void CreateClassPath(const std::string& class_path,
229 std::vector<const DexFile*>& class_path_vector) {
230 std::vector<std::string> parsed;
231 Split(class_path, ':', parsed);
232 for (size_t i = 0; i < parsed.size(); ++i) {
233 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700234 if (dex_file == NULL) {
235 LOG(WARNING) << "Failed to open dex file " << parsed[i];
236 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700237 class_path_vector.push_back(dex_file);
238 }
239 }
240}
241
242void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800243 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700244
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700245 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700246
Elliott Hughes30646832011-10-13 16:59:46 -0700247 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700248 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
249 CHECK(java_lang_Class.get() != NULL);
250 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700251 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700252 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700253
Elliott Hughes418d20f2011-09-22 14:00:39 -0700254 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700255 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
256 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700257
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700258 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700259 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
260 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700261 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700262 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700264
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700265 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700266 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
267 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700268
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700269 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700270 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700271
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700272 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700273 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
274 char_array_class->SetComponentType(char_class.get());
275 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700276
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700277 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700278 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
279 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700280 java_lang_String->SetObjectSize(sizeof(String));
281 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400282
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283 // Create storage for root classes, save away our work so far (requires
284 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700285 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700286 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700287 SetClassRoot(kJavaLangClass, java_lang_Class.get());
288 SetClassRoot(kJavaLangObject, java_lang_Object.get());
289 SetClassRoot(kClassArrayClass, class_array_class.get());
290 SetClassRoot(kObjectArrayClass, object_array_class.get());
291 SetClassRoot(kCharArrayClass, char_array_class.get());
292 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700293
294 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700295 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
296 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
297 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
298 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
299 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
300 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
301 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
302 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700304 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700305 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306
307 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700308 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700309 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700310 IntArray::SetArrayClass(int_array_class.get());
311 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700312
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700313 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700314
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700315 // setup boot_class_path_ and register class_path now that we can
316 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700317 std::vector<const DexFile*> boot_class_path_vector;
318 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700319 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700320 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
321 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700322 CHECK(dex_file != NULL);
323 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700324 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700325
Elliott Hughes80609252011-09-23 17:24:51 -0700326 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700327 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700328 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700329 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700331 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
332
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
334 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700335 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700336 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700338 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700339
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700340 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700341 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700343 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700345 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346
347 // now we can use FindSystemClass
348
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700349 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700350 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700351 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700352
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700353 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 java_lang_Object->SetStatus(Class::kStatusNotReady);
355 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700356 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
358 java_lang_String->SetStatus(Class::kStatusNotReady);
359 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700360 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
362
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700363 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
365 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
366
367 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
368 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
369
370 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700371 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700372
373 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
374 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
375
376 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700377 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
379 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
380 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
381
382 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
383 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
384
385 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
386 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
387
Elliott Hughes418d20f2011-09-22 14:00:39 -0700388 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700389 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700390
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700391 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700392 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393
394 // Setup the single, global copies of "interfaces" and "iftable"
395 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
396 CHECK(java_lang_Cloneable != NULL);
397 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
398 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700399 // We assume that Cloneable/Serializable don't have superinterfaces --
400 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700401 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800402 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
403 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700404
Elliott Hughes418d20f2011-09-22 14:00:39 -0700405 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800406 ClassHelper kh(class_array_class.get(), this);
407 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
408 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
409 kh.ChangeClass(object_array_class.get());
410 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
411 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700412 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700413 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700414 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700415 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700416
Elliott Hughes80609252011-09-23 17:24:51 -0700417 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
418 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700419 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700420
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700421 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700422 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700423 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700424
425 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700426 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700427 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700428
Ian Rogers466bb252011-10-14 03:29:56 -0700429 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
430
431 // Create java.lang.reflect.Proxy root
432 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
433 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
434
Brian Carlstrom1f870082011-08-23 16:02:11 -0700435 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700436 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
437 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700438 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700439 java_lang_ref_FinalizerReference->SetAccessFlags(
440 java_lang_ref_FinalizerReference->GetAccessFlags() |
441 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700442 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700443 java_lang_ref_PhantomReference->SetAccessFlags(
444 java_lang_ref_PhantomReference->GetAccessFlags() |
445 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700446 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700447 java_lang_ref_SoftReference->SetAccessFlags(
448 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700449 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700450 java_lang_ref_WeakReference->SetAccessFlags(
451 java_lang_ref_WeakReference->GetAccessFlags() |
452 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700453
Brian Carlstromaded5f72011-10-07 17:15:04 -0700454 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700456 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
458
459 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
460 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
461 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
462
463 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
464 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
465 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
466 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
467
468 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700469 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
470 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700471 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700472
Brian Carlstroma663ea52011-08-19 23:33:41 -0700473 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700474
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800475 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700476}
477
478void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800479 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700480
481 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700482 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700483 // as the types of the field can't be resolved prior to the runtime being
484 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700485 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700486 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700487 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
488
Elliott Hughesadb460d2011-10-05 17:02:34 -0700489 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
490
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800491 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
492
Brian Carlstrom16192862011-09-12 17:50:06 -0700493 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800494 FieldHelper fh(pendingNext, this);
495 CHECK_STREQ(fh.GetName(), "pendingNext");
496 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
497 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700498
499 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800500 fh.ChangeField(queue);
501 CHECK_STREQ(fh.GetName(), "queue");
502 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
503 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700504
505 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800506 fh.ChangeField(queueNext);
507 CHECK_STREQ(fh.GetName(), "queueNext");
508 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
509 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700510
511 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800512 fh.ChangeField(referent);
513 CHECK_STREQ(fh.GetName(), "referent");
514 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
515 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700516
517 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800518 fh.ChangeField(zombie);
519 CHECK_STREQ(fh.GetName(), "zombie");
520 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
521 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700522
523 Heap::SetReferenceOffsets(referent->GetOffset(),
524 queue->GetOffset(),
525 queueNext->GetOffset(),
526 pendingNext->GetOffset(),
527 zombie->GetOffset());
528
Brian Carlstroma663ea52011-08-19 23:33:41 -0700529 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700530 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700531 ClassRoot class_root = static_cast<ClassRoot>(i);
532 Class* klass = GetClassRoot(class_root);
533 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700534 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700535 // note SetClassRoot does additional validation.
536 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700537 }
538
Elliott Hughes92f14b22011-10-06 12:29:54 -0700539 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700540
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700541 // disable the slow paths in FindClass and CreatePrimitiveClass now
542 // that Object, Class, and Object[] are setup
543 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700544
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800545 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700546}
547
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700548void ClassLinker::RunRootClinits() {
549 Thread* self = Thread::Current();
550 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
551 Class* c = GetClassRoot(ClassRoot(i));
552 if (!c->IsArrayClass() && !c->IsPrimitive()) {
553 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700554 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700555 }
556 }
557}
558
jeffhao262bf462011-10-20 18:36:32 -0700559const OatFile* ClassLinker::GenerateOatFile(const std::string& filename) {
560 std::string oat_filename(GetArtCacheFilenameOrDie(OatFile::DexFilenameToOatFilename(filename)));
561
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800562 std::string dex2oat_string("/system/bin/dex2oat");
563#ifndef NDEBUG
564 dex2oat_string += 'd';
565#endif
566 const char* dex2oat = dex2oat_string.c_str();
567
568 const char* class_path = Runtime::Current()->GetClassPath().c_str();
569
570 std::string boot_image_option_string("--boot-image=");
571 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
572 const char* boot_image_option = boot_image_option_string.c_str();
573
574 std::string dex_file_option_string("--dex-file=");
575 dex_file_option_string += filename;
576 const char* dex_file_option = dex_file_option_string.c_str();
577
578 std::string oat_file_option_string("--oat=");
579 oat_file_option_string += oat_filename;
580 const char* oat_file_option = oat_file_option_string.c_str();
581
jeffhao262bf462011-10-20 18:36:32 -0700582 // fork and exec dex2oat
583 pid_t pid = fork();
584 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800585 // no allocation allowed between fork and exec
586 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700587 "--runtime-arg", "-Xms64m",
588 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500589 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800590 "--runtime-arg", class_path,
591 boot_image_option,
592 dex_file_option,
593 oat_file_option,
jeffhao262bf462011-10-20 18:36:32 -0700594 NULL);
595
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800596 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
jeffhao262bf462011-10-20 18:36:32 -0700597 return NULL;
598 } else {
599 // wait for dex2oat to finish
600 int status;
601 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
602 if (got_pid != pid) {
603 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
604 return NULL;
605 }
606 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800607 LOG(ERROR) << dex2oat << " failed with dex-file=" << filename;
jeffhao262bf462011-10-20 18:36:32 -0700608 return NULL;
609 }
610 }
611 return OatFile::Open(oat_filename, "", NULL);
612}
613
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700614OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700615 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700616 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800617 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700618 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800619 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
620 // check the down cast
621 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700622 std::string oat_filename;
623 oat_filename += runtime->GetHostPrefix();
624 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700625 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700626 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700627 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700628 return NULL;
629 }
630 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
631 uint32_t image_oat_checksum = image_header.GetOatChecksum();
632 if (oat_checksum != image_oat_checksum) {
633 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
634 << " to expected oat checksum " << std::hex << oat_checksum
635 << " in image";
636 return NULL;
637 }
638 oat_files_.push_back(oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800639 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700640 return oat_file;
641}
642
Brian Carlstromae826982011-11-09 01:33:42 -0800643const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
644 for (size_t i = 0; i < oat_files_.size(); i++) {
645 const OatFile* oat_file = oat_files_[i];
646 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800647 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800648 return oat_file;
649 }
650 }
651 return NULL;
652}
653
654const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700655 MutexLock mu(dex_lock_);
Brian Carlstromae826982011-11-09 01:33:42 -0800656 const OatFile* oat_file = FindOpenedOatFileForDexFile(dex_file);
657 if (oat_file != NULL) {
658 return oat_file;
659 }
660
661 oat_file = FindOatFileFromOatLocation(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
jeffhao262bf462011-10-20 18:36:32 -0700662 if (oat_file != NULL) {
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700663 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
664 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
665 return oat_file;
666 }
667 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
668 << " is older than " << dex_file.GetLocation() << " --- regenerating";
Elliott Hughes234da572011-11-03 22:13:06 -0700669 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
670 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
671 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700672 // Fall through...
jeffhao262bf462011-10-20 18:36:32 -0700673 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700674 // Generate oat file if it wasn't found or was obsolete.
jeffhao262bf462011-10-20 18:36:32 -0700675 oat_file = GenerateOatFile(dex_file.GetLocation());
676 if (oat_file == NULL) {
677 LOG(ERROR) << "Failed to generate oat file from dex file " << dex_file.GetLocation();
678 return NULL;
679 }
680 oat_files_.push_back(oat_file);
681 return oat_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700682}
683
Brian Carlstromae826982011-11-09 01:33:42 -0800684const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700685 for (size_t i = 0; i < oat_files_.size(); i++) {
686 const OatFile* oat_file = oat_files_[i];
687 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800688 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700689 return oat_file;
690 }
691 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700692 return NULL;
693}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700694
Brian Carlstromae826982011-11-09 01:33:42 -0800695const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
696 const OatFile* oat_file = FindOpenedOatFileFromOatLocation(oat_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700697 if (oat_file != NULL) {
698 return oat_file;
699 }
700
Brian Carlstromae826982011-11-09 01:33:42 -0800701 oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700702 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800703 if (oat_location.empty() || oat_location[0] != '/') {
704 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700705 return NULL;
706 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700707
Brian Carlstroma9f19782011-10-13 00:14:47 -0700708 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800709 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800710 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700711 if (oat_file != NULL) {
712 return oat_file;
713 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700714 oat_file = OatFile::Open(cache_location, "", NULL);
715 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800716 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700717 return NULL;
718 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700719 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700720
Brian Carlstromae826982011-11-09 01:33:42 -0800721 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromfad71432011-10-16 20:25:10 -0700722 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700723 return oat_file;
724}
725
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700726void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700727 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800728 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700729 CHECK(!init_done_);
730
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700731 const std::vector<Space*>& spaces = Heap::GetSpaces();
732 for (size_t i = 0; i < spaces.size(); i++) {
733 Space* space = spaces[i] ;
734 if (space->IsImageSpace()) {
735 OatFile* oat_file = OpenOat(space);
736 CHECK(oat_file != NULL) << "Failed to open oat file for image";
737 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
738 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
739
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800740 if (i == 0) {
741 // Special case of setting up the String class early so that we can test arbitrary objects
742 // as being Strings or not
743 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
744 ->AsObjectArray<Class>()->Get(kJavaLangString);
745 String::SetClass(java_lang_String);
746 }
747
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700748 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
749 static_cast<uint32_t>(dex_caches->GetLength()));
750 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700751 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800752 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700753
754 std::string dex_filename;
755 dex_filename += runtime->GetHostPrefix();
756 dex_filename += dex_file_location;
757 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
758 if (dex_file == NULL) {
759 LOG(FATAL) << "Failed to open dex file " << dex_filename
760 << " referenced from oat file as " << dex_file_location;
761 }
762
Brian Carlstromaded5f72011-10-07 17:15:04 -0700763 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
764 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700765
Brian Carlstromdf143242011-10-10 18:05:34 -0700766 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700767 }
768 }
769 }
770
Brian Carlstroma663ea52011-08-19 23:33:41 -0700771 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
772 DCHECK(heap_bitmap != NULL);
773
Brian Carlstroma663ea52011-08-19 23:33:41 -0700774 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700775 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700776
777 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700778 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
779 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700780
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800781 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700782 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
783 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800784 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700785 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700786 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700787 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
788 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
789 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
790 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
791 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
792 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
793 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
794 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700795 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700796 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700797
798 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700799
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800800 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700801}
802
Brian Carlstrom78128a62011-09-15 17:21:19 -0700803void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700804 DCHECK(obj != NULL);
805 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700806 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700807
Elliott Hughesdbb40792011-11-18 17:05:22 -0800808 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700809 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700810 return;
811 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700812 if (obj->IsClass()) {
813 // restore class to ClassLinker::classes_ table
814 Class* klass = obj->AsClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800815 std::string descriptor(ClassHelper(klass, class_linker).GetDescriptor());
Ian Rogers5d76c432011-10-31 21:42:49 -0700816 bool success = class_linker->InsertClass(descriptor, klass, true);
817 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700818 return;
819 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700820}
821
822// Keep in sync with InitCallback. Anything we visit, we need to
823// reinit references to when reinitializing a ClassLinker from a
824// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700825void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
826 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700827
828 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700829 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700830 }
831
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700832 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700833 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700834 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700835 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700836 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700837 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700838 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700839 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700840
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700841 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700842}
843
Elliott Hughesa2155262011-11-16 16:26:58 -0800844void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
845 MutexLock mu(classes_lock_);
846 typedef Table::const_iterator It; // TODO: C++0x auto
847 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
848 if (!visitor(it->second, arg)) {
849 return;
850 }
851 }
852 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
853 if (!visitor(it->second, arg)) {
854 return;
855 }
856 }
857}
858
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700859ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700860 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700861 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700862 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700863 BooleanArray::ResetArrayClass();
864 ByteArray::ResetArrayClass();
865 CharArray::ResetArrayClass();
866 DoubleArray::ResetArrayClass();
867 FloatArray::ResetArrayClass();
868 IntArray::ResetArrayClass();
869 LongArray::ResetArrayClass();
870 ShortArray::ResetArrayClass();
871 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700872 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700873 STLDeleteElements(&boot_class_path_);
874 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700875}
876
877DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700878 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
879 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700880 return NULL;
881 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700882 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
883 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700884 return NULL;
885 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700886 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
887 if (strings.get() == NULL) {
888 return NULL;
889 }
890 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
891 if (types.get() == NULL) {
892 return NULL;
893 }
894 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
895 if (methods.get() == NULL) {
896 return NULL;
897 }
898 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
899 if (fields.get() == NULL) {
900 return NULL;
901 }
902 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
903 if (code_and_direct_methods.get() == NULL) {
904 return NULL;
905 }
906 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
907 if (initialized_static_storage.get() == NULL) {
908 return NULL;
909 }
910
911 dex_cache->Init(location.get(),
912 strings.get(),
913 types.get(),
914 methods.get(),
915 fields.get(),
916 code_and_direct_methods.get(),
917 initialized_static_storage.get());
918 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700919}
920
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700921CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
922 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700923}
924
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700925InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
926 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700927 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
928 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700929 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700930 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700931}
932
Brian Carlstrom4873d462011-08-21 15:23:39 -0700933Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
934 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700935 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700936 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700937 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700938 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700939}
940
Brian Carlstrom4873d462011-08-21 15:23:39 -0700941Class* ClassLinker::AllocClass(size_t class_size) {
942 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700943}
944
Jesse Wilson35baaab2011-08-10 16:18:03 -0400945Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700946 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700947}
948
949Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700950 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700951}
952
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700953ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
954 return ObjectArray<StackTraceElement>::Alloc(
955 GetClassRoot(kJavaLangStackTraceElementArrayClass),
956 length);
957}
958
Brian Carlstromaded5f72011-10-07 17:15:04 -0700959Class* EnsureResolved(Class* klass) {
960 DCHECK(klass != NULL);
961 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700962 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700963 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700964 ObjectLock lock(klass);
965 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700966 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700967 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800968 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700969 return NULL;
970 }
971 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700972 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700973 lock.Wait();
974 }
975 }
976 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700977 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700978 return NULL;
979 }
980 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700981 CHECK(klass->IsResolved()) << PrettyClass(klass);
982 CHECK(!self->IsExceptionPending())
983 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
984 return klass;
985}
986
987Class* ClassLinker::FindClass(const std::string& descriptor,
988 const ClassLoader* class_loader) {
989 CHECK_NE(descriptor.size(), 0U);
990 Thread* self = Thread::Current();
991 DCHECK(self != NULL);
992 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800993 if (descriptor.size() == 1) {
994 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
995 // for primitive classes that aren't backed by dex files.
996 return FindPrimitiveClass(descriptor[0]);
997 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700998 // Find the class in the loaded classes table.
999 Class* klass = LookupClass(descriptor, class_loader);
1000 if (klass != NULL) {
1001 return EnsureResolved(klass);
1002 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001003 // Class is not yet loaded.
1004 if (descriptor[0] == '[') {
1005 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001006
Jesse Wilson47daf872011-11-23 11:42:45 -05001007 } else if (class_loader == NULL) {
1008 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1009 if (pair.second != NULL) {
1010 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1011 }
1012
1013 } else if (ClassLoader::UseCompileTimeClassPath()) {
1014 // first try the boot class path
1015 Class* system_class = FindSystemClass(descriptor);
1016 if (system_class != NULL) {
1017 return system_class;
1018 }
1019 CHECK(self->IsExceptionPending());
1020 self->ClearException();
1021
1022 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001023 const std::vector<const DexFile*>& class_path
1024 = ClassLoader::GetCompileTimeClassPath(class_loader);
1025 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001026 if (pair.second != NULL) {
1027 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001028 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001029
1030 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001031 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001032 ScopedThreadStateChange(self, Thread::kNative);
1033 JNIEnv* env = self->GetJniEnv();
1034 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1035 CHECK(c.get() != NULL);
1036 // TODO: cache method?
1037 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1038 CHECK(mid != NULL);
1039 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1040 if (class_name_object.get() == NULL) {
1041 return NULL;
1042 }
1043 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1044 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
1045 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001046 }
1047
Jesse Wilson47daf872011-11-23 11:42:45 -05001048 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
1049 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001050}
1051
1052Class* ClassLinker::DefineClass(const std::string& descriptor,
1053 const ClassLoader* class_loader,
1054 const DexFile& dex_file,
1055 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001056 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001057 // Load the class from the dex file.
1058 if (!init_done_) {
1059 // finish up init of hand crafted class_roots_
1060 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001061 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001062 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001063 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001064 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001065 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001066 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001067 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001068 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001069 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001070 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001071 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001072 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001073 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001074 }
1075 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001076 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001077 }
1078 klass->SetDexCache(FindDexCache(dex_file));
1079 LoadClass(dex_file, dex_class_def, klass, class_loader);
1080 // Check for a pending exception during load
1081 Thread* self = Thread::Current();
1082 if (self->IsExceptionPending()) {
1083 return NULL;
1084 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001085 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001086 klass->SetClinitThreadId(self->GetTid());
1087 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001088 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001089 if (!success) {
1090 // We may fail to insert if we raced with another thread.
1091 klass->SetClinitThreadId(0);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001092 klass.reset(LookupClass(descriptor, class_loader));
1093 CHECK(klass.get() != NULL);
1094 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001095 }
1096 // Finish loading (if necessary) by finding parents
1097 CHECK(!klass->IsLoaded());
1098 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1099 // Loading failed.
1100 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001101 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001102 lock.NotifyAll();
1103 return NULL;
1104 }
1105 CHECK(klass->IsLoaded());
1106 // Link the class (if necessary)
1107 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001108 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001109 // Linking failed.
1110 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001111 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001112 lock.NotifyAll();
1113 return NULL;
1114 }
1115 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001116
1117 /*
1118 * We send CLASS_PREPARE events to the debugger from here. The
1119 * definition of "preparation" is creating the static fields for a
1120 * class and initializing them to the standard default values, but not
1121 * executing any code (that comes later, during "initialization").
1122 *
1123 * We did the static preparation in LinkClass.
1124 *
1125 * The class has been prepared and resolved but possibly not yet verified
1126 * at this point.
1127 */
1128 Dbg::PostClassPrepare(klass.get());
1129
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001130 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001131}
1132
Brian Carlstrom4873d462011-08-21 15:23:39 -07001133// Precomputes size that will be needed for Class, matching LinkStaticFields
1134size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1135 const DexFile::ClassDef& dex_class_def) {
1136 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001137 size_t num_ref = 0;
1138 size_t num_32 = 0;
1139 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001140 if (class_data != NULL) {
1141 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1142 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001143 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001144 char c = descriptor[0];
1145 if (c == 'L' || c == '[') {
1146 num_ref++;
1147 } else if (c == 'J' || c == 'D') {
1148 num_64++;
1149 } else {
1150 num_32++;
1151 }
1152 }
1153 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001154 // start with generic class data
1155 size_t size = sizeof(Class);
1156 // follow with reference fields which must be contiguous at start
1157 size += (num_ref * sizeof(uint32_t));
1158 // if there are 64-bit fields to add, make sure they are aligned
1159 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1160 if (num_32 != 0) {
1161 // use an available 32-bit field for padding
1162 num_32--;
1163 }
1164 size += sizeof(uint32_t); // either way, we are adding a word
1165 DCHECK_EQ(size, RoundUp(size, 8));
1166 }
1167 // tack on any 64-bit fields now that alignment is assured
1168 size += (num_64 * sizeof(uint64_t));
1169 // tack on any remaining 32-bit fields
1170 size += (num_32 * sizeof(uint32_t));
1171 return size;
1172}
1173
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001174void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001175 // Every kind of method should at least get an invoke stub from the oat_method.
1176 // non-abstract methods also get their code pointers.
1177 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001178 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001179
1180 if (method->IsAbstract()) {
1181 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1182 return;
1183 }
1184 if (method->IsNative()) {
1185 // unregistering restores the dlsym lookup stub
1186 method->UnregisterNative();
1187 return;
1188 }
1189}
1190
Brian Carlstromf615a612011-07-23 12:50:34 -07001191void ClassLinker::LoadClass(const DexFile& dex_file,
1192 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001193 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001194 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001195 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001196 CHECK(klass->GetDexCache() != NULL);
1197 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001198 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001199 CHECK(descriptor != NULL);
1200
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001201 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001202 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001203 // Make sure that none of our runtime-only flags are set.
1204 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001205 klass->SetAccessFlags(access_flags);
1206 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001207 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001208 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001209
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001210 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001211
Ian Rogers0571d352011-11-03 19:51:38 -07001212 // Load fields fields.
1213 const byte* class_data = dex_file.GetClassData(dex_class_def);
1214 if (class_data == NULL) {
1215 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001216 }
Ian Rogers0571d352011-11-03 19:51:38 -07001217 ClassDataItemIterator it(dex_file, class_data);
1218 if (it.NumStaticFields() != 0) {
1219 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1220 }
1221 if (it.NumInstanceFields() != 0) {
1222 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1223 }
1224 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1225 SirtRef<Field> sfield(AllocField());
1226 klass->SetStaticField(i, sfield.get());
1227 LoadField(dex_file, it, klass, sfield);
1228 }
1229 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1230 SirtRef<Field> ifield(AllocField());
1231 klass->SetInstanceField(i, ifield.get());
1232 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001233 }
1234
Brian Carlstromaded5f72011-10-07 17:15:04 -07001235 UniquePtr<const OatFile::OatClass> oat_class;
1236 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001237 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001238 if (oat_file != NULL) {
1239 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1240 if (oat_dex_file != NULL) {
1241 uint32_t class_def_index;
1242 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1243 CHECK(found) << descriptor;
1244 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001245 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001246 }
1247 }
1248 }
Ian Rogers0571d352011-11-03 19:51:38 -07001249 // Load methods.
1250 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001251 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001252 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001253 }
Ian Rogers0571d352011-11-03 19:51:38 -07001254 if (it.NumVirtualMethods() != 0) {
1255 // TODO: append direct methods to class object
1256 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001257 }
Ian Rogers0571d352011-11-03 19:51:38 -07001258 size_t method_index = 0;
1259 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1260 SirtRef<Method> method(AllocMethod());
1261 klass->SetDirectMethod(i, method.get());
1262 LoadMethod(dex_file, it, klass, method);
1263 if (oat_class.get() != NULL) {
1264 LinkCode(method, oat_class.get(), method_index);
1265 }
1266 method_index++;
1267 }
1268 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1269 SirtRef<Method> method(AllocMethod());
1270 klass->SetVirtualMethod(i, method.get());
1271 LoadMethod(dex_file, it, klass, method);
1272 if (oat_class.get() != NULL) {
1273 LinkCode(method, oat_class.get(), method_index);
1274 }
1275 method_index++;
1276 }
1277 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001278}
1279
Ian Rogers0571d352011-11-03 19:51:38 -07001280void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1281 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001282 uint32_t field_idx = it.GetMemberIndex();
1283 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001284 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001285 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001286}
1287
Ian Rogers0571d352011-11-03 19:51:38 -07001288void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1289 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001290 uint32_t method_idx = it.GetMemberIndex();
1291 dst->SetDexMethodIndex(method_idx);
1292 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001293 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001294
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001295
1296 StringPiece method_name(dex_file.GetMethodName(method_id));
1297 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001298 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1299 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001300
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001301 if (method_name == "finalize") {
1302 // Create the prototype for a signature of "()V"
1303 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1304 if (void_string_id != NULL) {
1305 const DexFile::TypeId* void_type_id =
1306 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1307 if (void_type_id != NULL) {
1308 std::vector<uint16_t> no_args;
1309 const DexFile::ProtoId* finalizer_proto =
1310 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1311 if (finalizer_proto != NULL) {
1312 // We have the prototype in the dex file
1313 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1314 klass->SetFinalizable();
1315 } else {
1316 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1317 // The Enum class declares a "final" finalize() method to prevent subclasses from
1318 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1319 // subclasses, so we exclude it here.
1320 // We also want to avoid setting the flag on Object, where we know that finalize() is
1321 // empty.
1322 if (klass_descriptor != "Ljava/lang/Object;" &&
1323 klass_descriptor != "Ljava/lang/Enum;") {
1324 klass->SetFinalizable();
1325 }
1326 }
1327 }
1328 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001329 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001330 }
Ian Rogers0571d352011-11-03 19:51:38 -07001331 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001332 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001333
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001334 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1335 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1336 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1337 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1338 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1339 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001340
Brian Carlstrom934486c2011-07-12 23:42:50 -07001341 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001342}
1343
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001344void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001345 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1346 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001347}
1348
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001349void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1350 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001351 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001352 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001353}
1354
Brian Carlstromaded5f72011-10-07 17:15:04 -07001355bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001356 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001357 for (size_t i = 0; i != dex_files_.size(); ++i) {
1358 if (dex_files_[i] == &dex_file) {
1359 return true;
1360 }
1361 }
1362 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001363}
1364
Brian Carlstromaded5f72011-10-07 17:15:04 -07001365bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001366 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001367 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001368}
1369
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001370void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001371 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001372 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001373 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001374 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001375 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001376}
1377
Brian Carlstromaded5f72011-10-07 17:15:04 -07001378void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001379 {
1380 MutexLock mu(dex_lock_);
1381 if (IsDexFileRegisteredLocked(dex_file)) {
1382 return;
1383 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001384 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001385 // Don't alloc while holding the lock, since allocation may need to
1386 // suspend all threads and another thread may need the dex_lock_ to
1387 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001388 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001389 {
1390 MutexLock mu(dex_lock_);
1391 if (IsDexFileRegisteredLocked(dex_file)) {
1392 return;
1393 }
1394 RegisterDexFileLocked(dex_file, dex_cache);
1395 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001396}
1397
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001398void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001399 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001400 RegisterDexFileLocked(dex_file, dex_cache);
1401}
1402
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001403const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001404 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001405 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001406 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1407 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001408 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001409 }
1410 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001411 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001412 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001413}
1414
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001415DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001416 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001417 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001418 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001419 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001420 }
1421 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001422 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001423 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001424}
1425
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001426Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1427 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001428 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001429 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001430 CHECK(primitive_class != NULL);
1431 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001432 primitive_class->SetPrimitiveType(type);
1433 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001434 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001435 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1436 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001437}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001438
Brian Carlstrombe977852011-07-19 14:54:54 -07001439// Create an array class (i.e. the class object for the array, not the
1440// array itself). "descriptor" looks like "[C" or "[[[[B" or
1441// "[Ljava/lang/String;".
1442//
1443// If "descriptor" refers to an array of primitives, look up the
1444// primitive type's internally-generated class object.
1445//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001446// "class_loader" is the class loader of the class that's referring to
1447// us. It's used to ensure that we're looking for the element type in
1448// the right context. It does NOT become the class loader for the
1449// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001450//
1451// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001452Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001453 const ClassLoader* class_loader) {
1454 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001455
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001456 // Identify the underlying component type
1457 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001458 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001459 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001460 return NULL;
1461 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001462
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001463 // See if the component type is already loaded. Array classes are
1464 // always associated with the class loader of their underlying
1465 // element type -- an array of Strings goes with the loader for
1466 // java/lang/String -- so we need to look for it there. (The
1467 // caller should have checked for the existence of the class
1468 // before calling here, but they did so with *their* class loader,
1469 // not the component type's loader.)
1470 //
1471 // If we find it, the caller adds "loader" to the class' initiating
1472 // loader list, which should prevent us from going through this again.
1473 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001474 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001475 // are the same, because our caller (FindClass) just did the
1476 // lookup. (Even if we get this wrong we still have correct behavior,
1477 // because we effectively do this lookup again when we add the new
1478 // class to the hash table --- necessary because of possible races with
1479 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001480 if (class_loader != component_type->GetClassLoader()) {
1481 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001482 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001483 return new_class;
1484 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001485 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001486
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001487 // Fill out the fields in the Class.
1488 //
1489 // It is possible to execute some methods against arrays, because
1490 // all arrays are subclasses of java_lang_Object_, so we need to set
1491 // up a vtable. We can just point at the one in java_lang_Object_.
1492 //
1493 // Array classes are simple enough that we don't need to do a full
1494 // link step.
1495
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001496 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001497 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001498 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001499 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001500 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001501 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001502 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001503 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001504 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001505 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001506 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001507 }
1508 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001509 if (new_class.get() == NULL) {
1510 new_class.reset(AllocClass(sizeof(Class)));
1511 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001512 return NULL;
1513 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001514 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001515 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001516 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001517 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001518 new_class->SetSuperClass(java_lang_Object);
1519 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001520 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001521 new_class->SetClassLoader(component_type->GetClassLoader());
1522 new_class->SetStatus(Class::kStatusInitialized);
1523 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001524 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001525
1526
1527 // All arrays have java/lang/Cloneable and java/io/Serializable as
1528 // interfaces. We need to set that up here, so that stuff like
1529 // "instanceof" works right.
1530 //
1531 // Note: The GC could run during the call to FindSystemClass,
1532 // so we need to make sure the class object is GC-valid while we're in
1533 // there. Do this by clearing the interface list so the GC will just
1534 // think that the entries are null.
1535
1536
1537 // Use the single, global copies of "interfaces" and "iftable"
1538 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001539 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001540 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001541
1542 // Inherit access flags from the component type. Arrays can't be
1543 // used as a superclass or interface, so we want to add "final"
1544 // and remove "interface".
1545 //
1546 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001547 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001548 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001549 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1550 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001551
Ian Rogers5d76c432011-10-31 21:42:49 -07001552 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001553 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001554 }
1555 // Another thread must have loaded the class after we
1556 // started but before we finished. Abandon what we've
1557 // done.
1558 //
1559 // (Yes, this happens.)
1560
1561 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001562 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001563 DCHECK(other_class != NULL);
1564 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001565}
1566
1567Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001568 switch (Primitive::GetType(type)) {
1569 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001570 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001571 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001572 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001573 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001574 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001575 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001576 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001577 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001578 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001579 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001580 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001581 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001582 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001583 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001584 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001585 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001586 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001587 case Primitive::kPrimNot:
1588 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001589 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001590 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001591 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001592 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001593}
1594
Ian Rogers5d76c432011-10-31 21:42:49 -07001595bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001596 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001597 DexCache* dex_cache = klass->GetDexCache();
1598 std::string source;
1599 if (dex_cache != NULL) {
1600 source += " from ";
1601 source += dex_cache->GetLocation()->ToModifiedUtf8();
1602 }
1603 LOG(INFO) << "Loaded class " << descriptor << source;
1604 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001605 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001606 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001607 Table::iterator it;
1608 if (image_class) {
1609 // TODO: sanity check there's no match in classes_
1610 it = image_classes_.insert(std::make_pair(hash, klass));
1611 } else {
1612 // TODO: sanity check there's no match in image_classes_
1613 it = classes_.insert(std::make_pair(hash, klass));
1614 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001615 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001616}
1617
Brian Carlstromae826982011-11-09 01:33:42 -08001618bool ClassLinker::RemoveClass(const std::string& descriptor, const ClassLoader* class_loader) {
1619 size_t hash = StringPieceHash()(descriptor);
1620 MutexLock mu(classes_lock_);
1621 typedef Table::const_iterator It; // TODO: C++0x auto
1622 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001623 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001624 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1625 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001626 kh.ChangeClass(klass);
1627 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001628 classes_.erase(it);
1629 return true;
1630 }
1631 }
1632 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1633 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001634 kh.ChangeClass(klass);
1635 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001636 image_classes_.erase(it);
1637 return true;
1638 }
1639 }
1640 return false;
1641}
1642
Brian Carlstromaded5f72011-10-07 17:15:04 -07001643Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001644 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001645 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001646 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001647 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001648 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001649 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001650 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001651 kh.ChangeClass(klass);
1652 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001653 return klass;
1654 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001655 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001656 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1657 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001658 kh.ChangeClass(klass);
1659 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001660 return klass;
1661 }
1662 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001663 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001664}
1665
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001666void ClassLinker::LookupClasses(const std::string& descriptor, std::vector<Class*>& classes) {
1667 classes.clear();
1668 size_t hash = StringPieceHash()(descriptor);
1669 MutexLock mu(classes_lock_);
1670 typedef Table::const_iterator It; // TODO: C++0x auto
1671 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001672 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001673 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001674 Class* klass = it->second;
1675 kh.ChangeClass(klass);
1676 if (descriptor == kh.GetDescriptor()) {
1677 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001678 }
1679 }
1680 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001681 Class* klass = it->second;
1682 kh.ChangeClass(klass);
1683 if (descriptor == kh.GetDescriptor()) {
1684 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001685 }
1686 }
1687}
1688
jeffhao98eacac2011-09-14 16:11:53 -07001689void ClassLinker::VerifyClass(Class* klass) {
1690 if (klass->IsVerified()) {
1691 return;
1692 }
1693
1694 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001695 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001696
Ian Rogersd81871c2011-10-03 13:57:23 -07001697 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001698 klass->SetStatus(Class::kStatusVerified);
1699 } else {
1700 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001701 Thread* self = Thread::Current();
1702 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1703 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001704 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001705 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001706 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001707 }
jeffhao98eacac2011-09-14 16:11:53 -07001708}
1709
Ian Rogersc2b44472011-12-14 21:17:17 -08001710static void CheckProxyConstructor(Method* constructor);
1711static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1712
Jesse Wilson95caa792011-10-12 18:14:17 -04001713Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001714 ClassLoader* loader, ObjectArray<Method>* methods,
1715 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001716 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001717 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001718 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001719 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001720 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001721 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001722 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001723 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001724 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001725 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001726
1727 klass->SetStatus(Class::kStatusIdx);
1728
1729 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1730
1731 // Create static field that holds throws, instance fields are inherited
1732 klass->SetSFields(AllocObjectArray<Field>(1));
1733 SirtRef<Field> sfield(AllocField());
1734 klass->SetStaticField(0, sfield.get());
1735 sfield->SetDexFieldIndex(-1);
1736 sfield->SetDeclaringClass(klass.get());
1737 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001738
Ian Rogers466bb252011-10-14 03:29:56 -07001739 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001740 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001741 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001742
Ian Rogers466bb252011-10-14 03:29:56 -07001743 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001744 size_t num_virtual_methods = methods->GetLength();
1745 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1746 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001747 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001748 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001749 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001750
1751 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1752 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1753 DCHECK(!Thread::Current()->IsExceptionPending());
1754
1755 // Link the fields and virtual methods, creating vtable and iftables
1756 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001757 DCHECK(Thread::Current()->IsExceptionPending());
1758 return NULL;
1759 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001760 sfield->SetObject(NULL, throws); // initialize throws field
1761 klass->SetStatus(Class::kStatusInitialized);
1762
1763 // sanity checks
1764#ifndef NDEBUG
1765 bool debug = true;
1766#else
1767 bool debug = false;
1768#endif
1769 if (debug) {
1770 CHECK(klass->GetIFields() == NULL);
1771 CheckProxyConstructor(klass->GetDirectMethod(0));
1772 for (size_t i = 0; i < num_virtual_methods; ++i) {
1773 SirtRef<Method> prototype(methods->Get(i));
1774 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1775 }
1776 std::string throws_field_name = "java.lang.Class[][] ";
1777 throws_field_name += name->ToModifiedUtf8();
1778 throws_field_name += ".throws";
1779 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1780
1781 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1782 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1783 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001784 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001785}
1786
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001787std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1788 DCHECK(proxy_class->IsProxyClass());
1789 String* name = proxy_class->GetName();
1790 DCHECK(name != NULL);
1791 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1792}
1793
1794
1795Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001796 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001797 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001798 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001799 Method* proxy_constructor = proxy_direct_methods->Get(2);
1800 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1801 // code_ too)
1802 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1803 // Make this constructor public and fix the class to be our Proxy version
1804 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001805 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001806 return constructor;
1807}
1808
1809static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001810 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001811 MethodHelper mh(constructor);
1812 CHECK_STREQ(mh.GetName(), "<init>");
1813 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001814 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001815}
1816
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001817Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1818 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1819 // prototype method
1820 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1821 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001822 // as necessary
1823 Method* method = down_cast<Method*>(prototype->Clone());
1824
1825 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1826 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001827 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001828 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001829
Ian Rogers466bb252011-10-14 03:29:56 -07001830 // At runtime the method looks like a reference and argument saving method, clone the code
1831 // related parameters from this method.
1832 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1833 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1834 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1835 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1836 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001837 return method;
1838}
Jesse Wilson95caa792011-10-12 18:14:17 -04001839
Ian Rogersc2b44472011-12-14 21:17:17 -08001840static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001841 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001842 CHECK(!prototype->IsFinal());
1843 CHECK(method->IsFinal());
1844 CHECK(!method->IsAbstract());
1845 MethodHelper mh(method);
1846 const char* method_name = mh.GetName();
1847 const char* method_shorty = mh.GetShorty();
1848 Class* method_return = mh.GetReturnType();
1849
1850 mh.ChangeMethod(prototype.get());
1851
1852 CHECK_STREQ(mh.GetName(), method_name);
1853 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001854
1855 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001856 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001857}
1858
Brian Carlstrom25c33252011-09-18 15:58:35 -07001859bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001860 CHECK(klass->IsResolved() || klass->IsErroneous())
1861 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001862
Carl Shapirob5573532011-07-12 18:22:59 -07001863 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001864
Brian Carlstrom25c33252011-09-18 15:58:35 -07001865 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001866 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001867 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001868 ObjectLock lock(klass);
1869
Brian Carlstromd1422f82011-09-28 11:37:09 -07001870 if (klass->GetStatus() == Class::kStatusInitialized) {
1871 return true;
1872 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001873
Brian Carlstromd1422f82011-09-28 11:37:09 -07001874 if (klass->IsErroneous()) {
1875 ThrowEarlierClassFailure(klass);
1876 return false;
1877 }
1878
1879 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001880 VerifyClass(klass);
1881 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001882 return false;
1883 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001884 }
1885
Brian Carlstrom25c33252011-09-18 15:58:35 -07001886 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1887 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001888 // if the class has a <clinit> but we can't run it during compilation,
1889 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001890 return false;
1891 }
1892
Brian Carlstromd1422f82011-09-28 11:37:09 -07001893 // If the class is kStatusInitializing, either this thread is
1894 // initializing higher up the stack or another thread has beat us
1895 // to initializing and we need to wait. Either way, this
1896 // invocation of InitializeClass will not be responsible for
1897 // running <clinit> and will return.
1898 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001899 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001900 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001901 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001902 return true;
1903 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001904 // No. That's fine. Wait for another thread to finish initializing.
1905 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001906 }
1907
1908 if (!ValidateSuperClassDescriptors(klass)) {
1909 klass->SetStatus(Class::kStatusError);
1910 return false;
1911 }
1912
Brian Carlstromd1422f82011-09-28 11:37:09 -07001913 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001914
Elliott Hughesdcc24742011-09-07 14:02:44 -07001915 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001916 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001917 }
1918
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001919 uint64_t t0 = NanoTime();
1920
Brian Carlstrom25c33252011-09-18 15:58:35 -07001921 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001922 return false;
1923 }
1924
1925 InitializeStaticFields(klass);
1926
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001927 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001928 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001929 }
1930
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001931 uint64_t t1 = NanoTime();
1932
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001933 {
1934 ObjectLock lock(klass);
1935
1936 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001937 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001938 klass->SetStatus(Class::kStatusError);
1939 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001940 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1941 RuntimeStats* thread_stats = self->GetStats();
1942 ++global_stats->class_init_count;
1943 ++thread_stats->class_init_count;
1944 global_stats->class_init_time_ns += (t1 - t0);
1945 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001946 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001947 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001948 ClassHelper kh(klass);
1949 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08001950 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001951 }
1952 lock.NotifyAll();
1953 }
1954
1955 return true;
1956}
1957
Brian Carlstromd1422f82011-09-28 11:37:09 -07001958bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1959 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001960 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001961 lock.Wait();
1962
1963 // When we wake up, repeat the test for init-in-progress. If
1964 // there's an exception pending (only possible if
1965 // "interruptShouldThrow" was set), bail out.
1966 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001967 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001968 klass->SetStatus(Class::kStatusError);
1969 return false;
1970 }
1971 // Spurious wakeup? Go back to waiting.
1972 if (klass->GetStatus() == Class::kStatusInitializing) {
1973 continue;
1974 }
1975 if (klass->IsErroneous()) {
1976 // The caller wants an exception, but it was thrown in a
1977 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001978 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001979 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001980 return false;
1981 }
1982 if (klass->IsInitialized()) {
1983 return true;
1984 }
1985 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1986 }
1987 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1988}
1989
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001990bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1991 if (klass->IsInterface()) {
1992 return true;
1993 }
1994 // begin with the methods local to the superclass
1995 if (klass->HasSuperClass() &&
1996 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1997 const Class* super = klass->GetSuperClass();
1998 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001999 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002000 if (method != super->GetVirtualMethod(i) &&
2001 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002002 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2003
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002004 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2005 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2006 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002007 return false;
2008 }
2009 }
2010 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002011 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2012 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2013 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002014 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2015 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002016 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002017 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002018 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002019 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2020
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002021 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2022 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2023 PrettyMethod(method).c_str(),
2024 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002025 return false;
2026 }
2027 }
2028 }
2029 }
2030 return true;
2031}
2032
2033bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002034 const Class* klass1,
2035 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002036 if (klass1 == klass2) {
2037 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002038 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002039 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002040 const DexFile::ProtoId& proto_id =
2041 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002042 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2043 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002044 if (descriptor == NULL) {
2045 break;
2046 }
2047 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2048 // Found a non-primitive type.
2049 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2050 return false;
2051 }
2052 }
2053 }
2054 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002055 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002056 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002057 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002058 return false;
2059 }
2060 }
2061 return true;
2062}
2063
2064// Returns true if classes referenced by the descriptor are the
2065// same classes in klass1 as they are in klass2.
2066bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002067 const Class* klass1,
2068 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002069 CHECK(descriptor != NULL);
2070 CHECK(klass1 != NULL);
2071 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002072 if (klass1 == klass2) {
2073 return true;
2074 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002075 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002076 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002077 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002078 // TODO: found2 == NULL
2079 // TODO: lookup found1 in initiating loader list
2080 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002081 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002082 return found1 == found2;
2083 } else {
2084 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002085 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002086}
2087
Brian Carlstrom25c33252011-09-18 15:58:35 -07002088bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002089 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002090 if (!klass->IsInterface() && klass->HasSuperClass()) {
2091 Class* super_class = klass->GetSuperClass();
2092 if (super_class->GetStatus() != Class::kStatusInitialized) {
2093 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002094 Thread* self = Thread::Current();
2095 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002096 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002097 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002098 // TODO: check for a pending exception
2099 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002100 if (!can_run_clinit) {
2101 // Don't set status to error when we can't run <clinit>.
2102 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2103 klass->SetStatus(Class::kStatusVerified);
2104 return false;
2105 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002106 klass->SetStatus(Class::kStatusError);
2107 klass->NotifyAll();
2108 return false;
2109 }
2110 }
2111 }
2112 return true;
2113}
2114
Brian Carlstrom25c33252011-09-18 15:58:35 -07002115bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002116 CHECK(c != NULL);
2117 if (c->IsInitialized()) {
2118 return true;
2119 }
2120
Elliott Hughes5f791332011-09-15 17:45:30 -07002121 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002122 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002123 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002124 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002125}
2126
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002127void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002128 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002129 const ClassLoader* cl = c->GetClassLoader();
2130 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002131 ClassDataItemIterator it(dex_file, class_data);
2132 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2133 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002134 }
2135}
2136
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002137void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002138 size_t num_static_fields = klass->NumStaticFields();
2139 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002140 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002141 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002142 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002143 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002144 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002145 return;
2146 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002147 ClassHelper kh(klass);
2148 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002149 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002150 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002151 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002152
Ian Rogers0571d352011-11-03 19:51:38 -07002153 if (it.HasNext()) {
2154 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2155 std::map<uint32_t, Field*> field_map;
2156 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2157 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2158 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002159 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002160 }
2161}
2162
Ian Rogersc2b44472011-12-14 21:17:17 -08002163bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002164 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002165 if (!LinkSuperClass(klass)) {
2166 return false;
2167 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002168 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002169 return false;
2170 }
2171 if (!LinkInstanceFields(klass)) {
2172 return false;
2173 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002174 if (!LinkStaticFields(klass)) {
2175 return false;
2176 }
2177 CreateReferenceInstanceOffsets(klass);
2178 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002179 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2180 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002181 return true;
2182}
2183
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002184bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002185 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002186 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2187 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2188 if (class_def == NULL) {
2189 return false;
2190 }
2191 uint16_t super_class_idx = class_def->superclass_idx_;
2192 if (super_class_idx != DexFile::kDexNoIndex16) {
2193 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002195 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002196 return false;
2197 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002198 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002199 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002200 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2201 if (interfaces != NULL) {
2202 for (size_t i = 0; i < interfaces->Size(); i++) {
2203 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2204 Class* interface = ResolveType(dex_file, idx, klass.get());
2205 if (interface == NULL) {
2206 DCHECK(Thread::Current()->IsExceptionPending());
2207 return false;
2208 }
2209 // Verify
2210 if (!klass->CanAccess(interface)) {
2211 // TODO: the RI seemed to ignore this in my testing.
2212 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2213 "Interface %s implemented by class %s is inaccessible",
2214 PrettyDescriptor(interface).c_str(),
2215 PrettyDescriptor(klass.get()).c_str());
2216 return false;
2217 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002218 }
2219 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002220 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002221 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002222 return true;
2223}
2224
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002225bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002226 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002227 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002228 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002229 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002230 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002231 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002232 return false;
2233 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002234 return true;
2235 }
2236 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002237 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002238 return false;
2239 }
2240 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002241 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002242 Thread* thread = Thread::Current();
2243 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002244 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002245 PrettyDescriptor(super).c_str(),
2246 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002247 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002248 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002249 return false;
2250 }
2251 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002252 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002253 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002254 PrettyDescriptor(super).c_str(),
2255 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002256 return false;
2257 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002258
2259 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2260 if (super->IsFinalizable()) {
2261 klass->SetFinalizable();
2262 }
2263
Elliott Hughes2da50362011-10-10 16:57:08 -07002264 // Inherit reference flags (if any) from the superclass.
2265 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2266 if (reference_flags != 0) {
2267 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2268 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002269 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002270 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002271 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002272 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002273 return false;
2274 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002275
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002276#ifndef NDEBUG
2277 // Ensure super classes are fully resolved prior to resolving fields..
2278 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002279 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002280 super = super->GetSuperClass();
2281 }
2282#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002283 return true;
2284}
2285
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002286// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002287bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288 if (klass->IsInterface()) {
2289 // No vtable.
2290 size_t count = klass->NumVirtualMethods();
2291 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002292 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002293 return false;
2294 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002295 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002296 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002297 }
jeffhaobdb76512011-09-07 11:43:16 -07002298 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002299 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002300 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002301 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002302 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002303 }
2304 return true;
2305}
2306
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002307bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002308 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002309 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2310 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002311 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002312 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002313 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002314 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002315 MethodHelper local_mh(NULL, this);
2316 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002317 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002318 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002319 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002320 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002321 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002322 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002323 super_mh.ChangeMethod(super_method);
2324 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002325 // Verify
2326 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002327 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002328 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002329 PrettyDescriptor(klass.get()).c_str(),
2330 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002331 return false;
2332 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002333 vtable->Set(j, local_method);
2334 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002335 break;
2336 }
2337 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002338 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002339 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002340 vtable->Set(actual_count, local_method);
2341 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002342 actual_count += 1;
2343 }
2344 }
2345 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002346 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002347 return false;
2348 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002349 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002350 CHECK_LE(actual_count, max_count);
2351 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002352 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002353 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002354 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002355 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002356 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002357 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002358 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002359 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002360 return false;
2361 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002362 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002363 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002364 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2365 vtable->Set(i, virtual_method);
2366 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002367 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002368 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002369 }
2370 return true;
2371}
2372
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002373bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002374 size_t super_ifcount;
2375 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002376 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002377 } else {
2378 super_ifcount = 0;
2379 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002380 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002381 ClassHelper kh(klass.get(), this);
2382 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2383 ifcount += num_interfaces;
2384 for (size_t i = 0; i < num_interfaces; i++) {
2385 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2386 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002387 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002388 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002389 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002390 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002391 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002392 return true;
2393 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002394 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002395 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002396 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2397 for (size_t i = 0; i < super_ifcount; i++) {
2398 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2399 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002400 }
2401 // Flatten the interface inheritance hierarchy.
2402 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002403 for (size_t i = 0; i < num_interfaces; i++) {
2404 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002405 DCHECK(interface != NULL);
2406 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002407 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002408 Thread* thread = Thread::Current();
2409 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002410 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002411 PrettyDescriptor(klass.get()).c_str(),
2412 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002413 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002414 return false;
2415 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002416 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002417 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002418 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002419 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2420 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002421 }
2422 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002423 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002424 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002425
2426 // If we're an interface, we don't need the vtable pointers, so we're done.
2427 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002428 return true;
2429 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002431 MethodHelper vtable_mh(NULL, this);
2432 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002433 for (size_t i = 0; i < ifcount; ++i) {
2434 InterfaceEntry* interface_entry = iftable->Get(i);
2435 Class* interface = interface_entry->GetInterface();
2436 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2437 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002438 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002439 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2440 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002441 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002442 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002443 // For each method listed in the interface's method list, find the
2444 // matching method in our class's method list. We want to favor the
2445 // subclass over the superclass, which just requires walking
2446 // back from the end of the vtable. (This only matters if the
2447 // superclass defines a private method and this class redefines
2448 // it -- otherwise it would use the same vtable slot. In .dex files
2449 // those don't end up in the virtual method table, so it shouldn't
2450 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002451 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2452 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002453 vtable_mh.ChangeMethod(vtable_method);
2454 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002455 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002456 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002457 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002458 return false;
2459 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002460 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002461 break;
2462 }
2463 }
2464 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002465 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002466 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002467 Method* mir_method = miranda_list[mir];
2468 vtable_mh.ChangeMethod(mir_method);
2469 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002470 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002471 break;
2472 }
2473 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002474 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002475 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002476 miranda_method.reset(AllocMethod());
2477 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2478 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002479 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002480 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002481 }
2482 }
2483 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002484 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002485 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002486 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002487 klass->SetVirtualMethods((old_method_count == 0)
2488 ? AllocObjectArray<Method>(new_method_count)
2489 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002490
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002491 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2492 CHECK(vtable != NULL);
2493 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002494 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002495 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002496 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002497 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002498 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002499 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2500 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2501 klass->SetVirtualMethod(old_method_count + i, method);
2502 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002503 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002504 // TODO: do not assign to the vtable field until it is fully constructed.
2505 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002506 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002507
2508 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2509 for (int i = 0; i < vtable->GetLength(); ++i) {
2510 CHECK(vtable->Get(i) != NULL);
2511 }
2512
2513// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2514
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002515 return true;
2516}
2517
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002518bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2519 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002520 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002521}
2522
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002523bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2524 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002525 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002526 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002527 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002528 return success;
2529}
2530
Brian Carlstromdbc05252011-09-09 01:59:59 -07002531struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002532 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002533 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002534 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002535 fh_->ChangeField(field1);
2536 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2537 fh_->ChangeField(field2);
2538 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002539 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2540 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2541 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2542 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002543 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2544 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2545 if (order1 != order2) {
2546 return order1 < order2;
2547 }
2548
2549 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002550 fh_->ChangeField(field1);
2551 StringPiece name1(fh_->GetName());
2552 fh_->ChangeField(field2);
2553 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002554 return name1 < name2;
2555 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002556
2557 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002558};
2559
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002560bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002561 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002562 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002563
2564 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002565 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002566
2567 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002568 size_t size;
2569 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002570 if (is_static) {
2571 size = klass->GetClassSize();
2572 field_offset = Class::FieldsOffset();
2573 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002574 Class* super_class = klass->GetSuperClass();
2575 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002576 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002578 }
2579 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002580 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002581
Brian Carlstromdbc05252011-09-09 01:59:59 -07002582 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002583
Brian Carlstromdbc05252011-09-09 01:59:59 -07002584 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002585 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002586 std::deque<Field*> grouped_and_sorted_fields;
2587 for (size_t i = 0; i < num_fields; i++) {
2588 grouped_and_sorted_fields.push_back(fields->Get(i));
2589 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002590 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002591 std::sort(grouped_and_sorted_fields.begin(),
2592 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002593 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002594
2595 // References should be at the front.
2596 size_t current_field = 0;
2597 size_t num_reference_fields = 0;
2598 for (; current_field < num_fields; current_field++) {
2599 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002600 fh.ChangeField(field);
2601 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002602 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002603 if (isPrimitive) {
2604 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002605 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002606 grouped_and_sorted_fields.pop_front();
2607 num_reference_fields++;
2608 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002609 field->SetOffset(field_offset);
2610 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002611 }
2612
2613 // Now we want to pack all of the double-wide fields together. If
2614 // we're not aligned, though, we want to shuffle one 32-bit field
2615 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002616 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002617 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2618 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002619 fh.ChangeField(field);
2620 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002621 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2622 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002623 continue;
2624 }
2625 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002626 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002627 // drop the consumed field
2628 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2629 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002630 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002631 // whether we found a 32-bit field for padding or not, we advance
2632 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002633 }
2634
2635 // Alignment is good, shuffle any double-wide fields forward, and
2636 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002637 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002638 while (!grouped_and_sorted_fields.empty()) {
2639 Field* field = grouped_and_sorted_fields.front();
2640 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002641 fh.ChangeField(field);
2642 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002643 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002644 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002645 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002646 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002647 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002648 ? sizeof(uint64_t)
2649 : sizeof(uint32_t)));
2650 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002651 }
2652
Elliott Hughesadb460d2011-10-05 17:02:34 -07002653 // 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 -08002654 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2655 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002656 // We know there are no non-reference fields in the Reference classes, and we know
2657 // that 'referent' is alphabetically last, so this is easy...
2658 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002659 fh.ChangeField(fields->Get(num_fields - 1));
2660 StringPiece name(fh.GetName());
2661 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002662 --num_reference_fields;
2663 }
2664
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002665#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002666 // Make sure that all reference fields appear before
2667 // non-reference fields, and all double-wide fields are aligned.
2668 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002669 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002670 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002671 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002672 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002673 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002674 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002675 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2676 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002677 fh.ChangeField(field);
2678 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002679 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002680 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002681 is_primitive = true; // We lied above, so we have to expect a lie here.
2682 }
2683 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002684 if (!seen_non_ref) {
2685 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002686 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002687 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002688 } else {
2689 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002690 }
2691 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002692 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002693 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002694 }
2695#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002696 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002697 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002698 if (is_static) {
2699 klass->SetNumReferenceStaticFields(num_reference_fields);
2700 klass->SetClassSize(size);
2701 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002702 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002703 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002704 klass->SetObjectSize(size);
2705 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002706 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002707 return true;
2708}
2709
2710// Set the bitmap of reference offsets, refOffsets, from the ifields
2711// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002712void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002713 uint32_t reference_offsets = 0;
2714 Class* super_class = klass->GetSuperClass();
2715 if (super_class != NULL) {
2716 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002717 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002718 if (reference_offsets == CLASS_WALK_SUPER) {
2719 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002720 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002721 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002722 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002723 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002724}
2725
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002726void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002727 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002728}
2729
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002730void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002731 uint32_t reference_offsets) {
2732 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002733 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2734 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002735 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002736 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002737 // All of the fields that contain object references are guaranteed
2738 // to be at the beginning of the fields list.
2739 for (size_t i = 0; i < num_reference_fields; ++i) {
2740 // Note that byte_offset is the offset from the beginning of
2741 // object, not the offset into instance data
2742 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002743 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002744 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2745 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2746 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002747 CHECK_NE(new_bit, 0U);
2748 reference_offsets |= new_bit;
2749 } else {
2750 reference_offsets = CLASS_WALK_SUPER;
2751 break;
2752 }
2753 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002754 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002755 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002756 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002757 } else {
2758 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002759 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002760}
2761
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002762String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002763 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002764 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002765 if (resolved != NULL) {
2766 return resolved;
2767 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002768 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2769 int32_t utf16_length = dex_file.GetStringLength(string_id);
2770 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002771 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002772 dex_cache->SetResolvedString(string_idx, string);
2773 return string;
2774}
2775
2776Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002777 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002778 DexCache* dex_cache,
2779 const ClassLoader* class_loader) {
2780 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002781 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002782 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002783 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002784 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002785 // TODO: we used to throw here if resolved's class loader was not the
2786 // boot class loader. This was to permit different classes with the
2787 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002788 dex_cache->SetResolvedType(type_idx, resolved);
2789 } else {
2790 DCHECK(Thread::Current()->IsExceptionPending());
2791 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002792 }
2793 return resolved;
2794}
2795
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002796Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2797 uint32_t method_idx,
2798 DexCache* dex_cache,
2799 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002800 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002801 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2802 if (resolved != NULL) {
2803 return resolved;
2804 }
2805 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2806 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2807 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002808 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002809 return NULL;
2810 }
2811
Ian Rogers0571d352011-11-03 19:51:38 -07002812 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2813 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002814 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002815 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002816 } else if (klass->IsInterface()) {
2817 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002818 } else {
2819 resolved = klass->FindVirtualMethod(name, signature);
2820 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002821 if (resolved != NULL) {
2822 dex_cache->SetResolvedMethod(method_idx, resolved);
2823 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002824 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002825 }
2826 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002827}
2828
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002829Field* ClassLinker::ResolveField(const DexFile& dex_file,
2830 uint32_t field_idx,
2831 DexCache* dex_cache,
2832 const ClassLoader* class_loader,
2833 bool is_static) {
2834 Field* resolved = dex_cache->GetResolvedField(field_idx);
2835 if (resolved != NULL) {
2836 return resolved;
2837 }
2838 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2839 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2840 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002841 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002842 return NULL;
2843 }
2844
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002845 const char* name = dex_file.GetFieldName(field_id);
2846 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002847 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002848 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002849 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002850 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002851 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002852 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002853 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002854 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002855 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2856 }
2857 return resolved;
2858}
2859
2860Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2861 uint32_t field_idx,
2862 DexCache* dex_cache,
2863 const ClassLoader* class_loader) {
2864 Field* resolved = dex_cache->GetResolvedField(field_idx);
2865 if (resolved != NULL) {
2866 return resolved;
2867 }
2868 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2869 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2870 if (klass == NULL) {
2871 DCHECK(Thread::Current()->IsExceptionPending());
2872 return NULL;
2873 }
2874
2875 const char* name = dex_file.GetFieldName(field_id);
2876 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
2877 resolved = klass->FindField(name, type);
2878 if (resolved != NULL) {
2879 dex_cache->SetResolvedField(field_idx, resolved);
2880 } else {
2881 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002882 }
2883 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002884}
2885
Ian Rogersad25ac52011-10-04 19:13:33 -07002886const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2887 Class* declaring_class = referrer->GetDeclaringClass();
2888 DexCache* dex_cache = declaring_class->GetDexCache();
2889 const DexFile& dex_file = FindDexFile(dex_cache);
2890 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2891 return dex_file.GetShorty(method_id.proto_idx_);
2892}
2893
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002894void ClassLinker::DumpAllClasses(int flags) const {
2895 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2896 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2897 std::vector<Class*> all_classes;
2898 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002899 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002900 typedef Table::const_iterator It; // TODO: C++0x auto
2901 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2902 all_classes.push_back(it->second);
2903 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002904 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2905 all_classes.push_back(it->second);
2906 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002907 }
2908
2909 for (size_t i = 0; i < all_classes.size(); ++i) {
2910 all_classes[i]->DumpClass(std::cerr, flags);
2911 }
2912}
2913
Elliott Hughescac6cc72011-11-03 20:31:21 -07002914void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2915 MutexLock mu(classes_lock_);
2916 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2917 << classes_.size() << " allocated classes\n";
2918}
2919
Elliott Hughese27955c2011-08-26 15:21:24 -07002920size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002921 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002922 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002923}
2924
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002925pid_t ClassLinker::GetClassesLockOwner() {
2926 return classes_lock_.GetOwner();
2927}
2928
2929pid_t ClassLinker::GetDexLockOwner() {
2930 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002931}
2932
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002933void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
2934 DCHECK(!init_done_);
2935
2936 DCHECK(klass != NULL);
2937 DCHECK(klass->GetClassLoader() == NULL);
2938
2939 DCHECK(class_roots_ != NULL);
2940 DCHECK(class_roots_->Get(class_root) == NULL);
2941 class_roots_->Set(class_root, klass);
2942}
2943
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002944} // namespace art