blob: e922d4c0576fdfd1d6593002151d0c28829e623b [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()));
Ian Rogers6b0870d2011-12-15 19:38:12 -08001045 if (!env->ExceptionOccurred()) {
1046 return Decode<Class*>(env, result.get());
1047 } else {
1048 env->ExceptionClear(); // Failed to find class fall-through to NCDFE
1049 // TODO: initialize the cause of the NCDFE to this exception
1050 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001051 }
1052
Jesse Wilson47daf872011-11-23 11:42:45 -05001053 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
1054 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001055}
1056
1057Class* ClassLinker::DefineClass(const std::string& descriptor,
1058 const ClassLoader* class_loader,
1059 const DexFile& dex_file,
1060 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001061 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001062 // Load the class from the dex file.
1063 if (!init_done_) {
1064 // finish up init of hand crafted class_roots_
1065 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001066 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001067 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001068 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001069 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001070 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001071 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001072 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001073 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001074 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001075 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001076 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001077 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001078 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001079 }
1080 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001081 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001082 }
1083 klass->SetDexCache(FindDexCache(dex_file));
1084 LoadClass(dex_file, dex_class_def, klass, class_loader);
1085 // Check for a pending exception during load
1086 Thread* self = Thread::Current();
1087 if (self->IsExceptionPending()) {
1088 return NULL;
1089 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001090 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001091 klass->SetClinitThreadId(self->GetTid());
1092 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001093 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001094 if (!success) {
1095 // We may fail to insert if we raced with another thread.
1096 klass->SetClinitThreadId(0);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001097 klass.reset(LookupClass(descriptor, class_loader));
1098 CHECK(klass.get() != NULL);
1099 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001100 }
1101 // Finish loading (if necessary) by finding parents
1102 CHECK(!klass->IsLoaded());
1103 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1104 // Loading failed.
1105 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001106 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001107 lock.NotifyAll();
1108 return NULL;
1109 }
1110 CHECK(klass->IsLoaded());
1111 // Link the class (if necessary)
1112 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001113 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001114 // Linking failed.
1115 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001116 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001117 lock.NotifyAll();
1118 return NULL;
1119 }
1120 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001121
1122 /*
1123 * We send CLASS_PREPARE events to the debugger from here. The
1124 * definition of "preparation" is creating the static fields for a
1125 * class and initializing them to the standard default values, but not
1126 * executing any code (that comes later, during "initialization").
1127 *
1128 * We did the static preparation in LinkClass.
1129 *
1130 * The class has been prepared and resolved but possibly not yet verified
1131 * at this point.
1132 */
1133 Dbg::PostClassPrepare(klass.get());
1134
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001135 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001136}
1137
Brian Carlstrom4873d462011-08-21 15:23:39 -07001138// Precomputes size that will be needed for Class, matching LinkStaticFields
1139size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1140 const DexFile::ClassDef& dex_class_def) {
1141 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001142 size_t num_ref = 0;
1143 size_t num_32 = 0;
1144 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001145 if (class_data != NULL) {
1146 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1147 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001148 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001149 char c = descriptor[0];
1150 if (c == 'L' || c == '[') {
1151 num_ref++;
1152 } else if (c == 'J' || c == 'D') {
1153 num_64++;
1154 } else {
1155 num_32++;
1156 }
1157 }
1158 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001159 // start with generic class data
1160 size_t size = sizeof(Class);
1161 // follow with reference fields which must be contiguous at start
1162 size += (num_ref * sizeof(uint32_t));
1163 // if there are 64-bit fields to add, make sure they are aligned
1164 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1165 if (num_32 != 0) {
1166 // use an available 32-bit field for padding
1167 num_32--;
1168 }
1169 size += sizeof(uint32_t); // either way, we are adding a word
1170 DCHECK_EQ(size, RoundUp(size, 8));
1171 }
1172 // tack on any 64-bit fields now that alignment is assured
1173 size += (num_64 * sizeof(uint64_t));
1174 // tack on any remaining 32-bit fields
1175 size += (num_32 * sizeof(uint32_t));
1176 return size;
1177}
1178
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001179void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001180 // Every kind of method should at least get an invoke stub from the oat_method.
1181 // non-abstract methods also get their code pointers.
1182 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001183 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001184
1185 if (method->IsAbstract()) {
1186 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1187 return;
1188 }
1189 if (method->IsNative()) {
1190 // unregistering restores the dlsym lookup stub
1191 method->UnregisterNative();
1192 return;
1193 }
1194}
1195
Brian Carlstromf615a612011-07-23 12:50:34 -07001196void ClassLinker::LoadClass(const DexFile& dex_file,
1197 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001198 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001199 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001200 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001201 CHECK(klass->GetDexCache() != NULL);
1202 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001203 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001204 CHECK(descriptor != NULL);
1205
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001206 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001207 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001208 // Make sure that none of our runtime-only flags are set.
1209 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001210 klass->SetAccessFlags(access_flags);
1211 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001212 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001213 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001214
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001215 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001216
Ian Rogers0571d352011-11-03 19:51:38 -07001217 // Load fields fields.
1218 const byte* class_data = dex_file.GetClassData(dex_class_def);
1219 if (class_data == NULL) {
1220 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001221 }
Ian Rogers0571d352011-11-03 19:51:38 -07001222 ClassDataItemIterator it(dex_file, class_data);
1223 if (it.NumStaticFields() != 0) {
1224 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1225 }
1226 if (it.NumInstanceFields() != 0) {
1227 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1228 }
1229 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1230 SirtRef<Field> sfield(AllocField());
1231 klass->SetStaticField(i, sfield.get());
1232 LoadField(dex_file, it, klass, sfield);
1233 }
1234 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1235 SirtRef<Field> ifield(AllocField());
1236 klass->SetInstanceField(i, ifield.get());
1237 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001238 }
1239
Brian Carlstromaded5f72011-10-07 17:15:04 -07001240 UniquePtr<const OatFile::OatClass> oat_class;
1241 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001242 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001243 if (oat_file != NULL) {
1244 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1245 if (oat_dex_file != NULL) {
1246 uint32_t class_def_index;
1247 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1248 CHECK(found) << descriptor;
1249 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001250 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001251 }
1252 }
1253 }
Ian Rogers0571d352011-11-03 19:51:38 -07001254 // Load methods.
1255 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001256 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001257 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001258 }
Ian Rogers0571d352011-11-03 19:51:38 -07001259 if (it.NumVirtualMethods() != 0) {
1260 // TODO: append direct methods to class object
1261 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001262 }
Ian Rogers0571d352011-11-03 19:51:38 -07001263 size_t method_index = 0;
1264 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1265 SirtRef<Method> method(AllocMethod());
1266 klass->SetDirectMethod(i, method.get());
1267 LoadMethod(dex_file, it, klass, method);
1268 if (oat_class.get() != NULL) {
1269 LinkCode(method, oat_class.get(), method_index);
1270 }
1271 method_index++;
1272 }
1273 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1274 SirtRef<Method> method(AllocMethod());
1275 klass->SetVirtualMethod(i, method.get());
1276 LoadMethod(dex_file, it, klass, method);
1277 if (oat_class.get() != NULL) {
1278 LinkCode(method, oat_class.get(), method_index);
1279 }
1280 method_index++;
1281 }
1282 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001283}
1284
Ian Rogers0571d352011-11-03 19:51:38 -07001285void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1286 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001287 uint32_t field_idx = it.GetMemberIndex();
1288 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001289 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001290 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001291}
1292
Ian Rogers0571d352011-11-03 19:51:38 -07001293void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1294 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001295 uint32_t method_idx = it.GetMemberIndex();
1296 dst->SetDexMethodIndex(method_idx);
1297 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001298 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001299
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001300
1301 StringPiece method_name(dex_file.GetMethodName(method_id));
1302 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001303 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1304 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001305
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001306 if (method_name == "finalize") {
1307 // Create the prototype for a signature of "()V"
1308 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1309 if (void_string_id != NULL) {
1310 const DexFile::TypeId* void_type_id =
1311 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1312 if (void_type_id != NULL) {
1313 std::vector<uint16_t> no_args;
1314 const DexFile::ProtoId* finalizer_proto =
1315 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1316 if (finalizer_proto != NULL) {
1317 // We have the prototype in the dex file
1318 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1319 klass->SetFinalizable();
1320 } else {
1321 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1322 // The Enum class declares a "final" finalize() method to prevent subclasses from
1323 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1324 // subclasses, so we exclude it here.
1325 // We also want to avoid setting the flag on Object, where we know that finalize() is
1326 // empty.
1327 if (klass_descriptor != "Ljava/lang/Object;" &&
1328 klass_descriptor != "Ljava/lang/Enum;") {
1329 klass->SetFinalizable();
1330 }
1331 }
1332 }
1333 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001334 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001335 }
Ian Rogers0571d352011-11-03 19:51:38 -07001336 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001337 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001338
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001339 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1340 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1341 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1342 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1343 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1344 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001345
Brian Carlstrom934486c2011-07-12 23:42:50 -07001346 // TODO: check for finalize method
Brian Carlstrom934486c2011-07-12 23:42:50 -07001347}
1348
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001349void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001350 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1351 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001352}
1353
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001354void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1355 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001356 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001357 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001358}
1359
Brian Carlstromaded5f72011-10-07 17:15:04 -07001360bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001361 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001362 for (size_t i = 0; i != dex_files_.size(); ++i) {
1363 if (dex_files_[i] == &dex_file) {
1364 return true;
1365 }
1366 }
1367 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001368}
1369
Brian Carlstromaded5f72011-10-07 17:15:04 -07001370bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001371 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001372 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001373}
1374
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001375void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001376 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001377 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001378 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001379 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001380 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001381}
1382
Brian Carlstromaded5f72011-10-07 17:15:04 -07001383void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001384 {
1385 MutexLock mu(dex_lock_);
1386 if (IsDexFileRegisteredLocked(dex_file)) {
1387 return;
1388 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001389 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001390 // Don't alloc while holding the lock, since allocation may need to
1391 // suspend all threads and another thread may need the dex_lock_ to
1392 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001393 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001394 {
1395 MutexLock mu(dex_lock_);
1396 if (IsDexFileRegisteredLocked(dex_file)) {
1397 return;
1398 }
1399 RegisterDexFileLocked(dex_file, dex_cache);
1400 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001401}
1402
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001403void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001404 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001405 RegisterDexFileLocked(dex_file, dex_cache);
1406}
1407
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001408const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001409 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001410 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001411 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1412 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001413 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001414 }
1415 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001416 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001417 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001418}
1419
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001420DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001421 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001422 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001423 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001424 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001425 }
1426 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001427 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001428 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001429}
1430
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001431Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1432 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001433 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001434 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001435 CHECK(primitive_class != NULL);
1436 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001437 primitive_class->SetPrimitiveType(type);
1438 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001439 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001440 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1441 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001442}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001443
Brian Carlstrombe977852011-07-19 14:54:54 -07001444// Create an array class (i.e. the class object for the array, not the
1445// array itself). "descriptor" looks like "[C" or "[[[[B" or
1446// "[Ljava/lang/String;".
1447//
1448// If "descriptor" refers to an array of primitives, look up the
1449// primitive type's internally-generated class object.
1450//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001451// "class_loader" is the class loader of the class that's referring to
1452// us. It's used to ensure that we're looking for the element type in
1453// the right context. It does NOT become the class loader for the
1454// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001455//
1456// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001457Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001458 const ClassLoader* class_loader) {
1459 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001460
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001461 // Identify the underlying component type
1462 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001463 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001464 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001465 return NULL;
1466 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001467
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001468 // See if the component type is already loaded. Array classes are
1469 // always associated with the class loader of their underlying
1470 // element type -- an array of Strings goes with the loader for
1471 // java/lang/String -- so we need to look for it there. (The
1472 // caller should have checked for the existence of the class
1473 // before calling here, but they did so with *their* class loader,
1474 // not the component type's loader.)
1475 //
1476 // If we find it, the caller adds "loader" to the class' initiating
1477 // loader list, which should prevent us from going through this again.
1478 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001479 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001480 // are the same, because our caller (FindClass) just did the
1481 // lookup. (Even if we get this wrong we still have correct behavior,
1482 // because we effectively do this lookup again when we add the new
1483 // class to the hash table --- necessary because of possible races with
1484 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001485 if (class_loader != component_type->GetClassLoader()) {
1486 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001487 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001488 return new_class;
1489 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001490 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001491
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001492 // Fill out the fields in the Class.
1493 //
1494 // It is possible to execute some methods against arrays, because
1495 // all arrays are subclasses of java_lang_Object_, so we need to set
1496 // up a vtable. We can just point at the one in java_lang_Object_.
1497 //
1498 // Array classes are simple enough that we don't need to do a full
1499 // link step.
1500
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001501 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001502 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001503 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001504 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001505 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001506 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001507 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001508 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001509 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001510 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001511 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001512 }
1513 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001514 if (new_class.get() == NULL) {
1515 new_class.reset(AllocClass(sizeof(Class)));
1516 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001517 return NULL;
1518 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001519 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001520 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001521 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001522 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001523 new_class->SetSuperClass(java_lang_Object);
1524 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001525 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001526 new_class->SetClassLoader(component_type->GetClassLoader());
1527 new_class->SetStatus(Class::kStatusInitialized);
1528 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001529 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001530
1531
1532 // All arrays have java/lang/Cloneable and java/io/Serializable as
1533 // interfaces. We need to set that up here, so that stuff like
1534 // "instanceof" works right.
1535 //
1536 // Note: The GC could run during the call to FindSystemClass,
1537 // so we need to make sure the class object is GC-valid while we're in
1538 // there. Do this by clearing the interface list so the GC will just
1539 // think that the entries are null.
1540
1541
1542 // Use the single, global copies of "interfaces" and "iftable"
1543 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001544 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001545 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001546
1547 // Inherit access flags from the component type. Arrays can't be
1548 // used as a superclass or interface, so we want to add "final"
1549 // and remove "interface".
1550 //
1551 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001552 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001553 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001554 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1555 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001556
Ian Rogers5d76c432011-10-31 21:42:49 -07001557 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001558 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001559 }
1560 // Another thread must have loaded the class after we
1561 // started but before we finished. Abandon what we've
1562 // done.
1563 //
1564 // (Yes, this happens.)
1565
1566 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001567 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001568 DCHECK(other_class != NULL);
1569 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001570}
1571
1572Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001573 switch (Primitive::GetType(type)) {
1574 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001575 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001576 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001577 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001578 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001579 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001580 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001581 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001582 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001583 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001584 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001585 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001586 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001587 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001588 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001589 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001590 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001591 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001592 case Primitive::kPrimNot:
1593 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001594 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001595 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001596 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001597 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001598}
1599
Ian Rogers5d76c432011-10-31 21:42:49 -07001600bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001601 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001602 DexCache* dex_cache = klass->GetDexCache();
1603 std::string source;
1604 if (dex_cache != NULL) {
1605 source += " from ";
1606 source += dex_cache->GetLocation()->ToModifiedUtf8();
1607 }
1608 LOG(INFO) << "Loaded class " << descriptor << source;
1609 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001610 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001611 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001612 Table::iterator it;
1613 if (image_class) {
1614 // TODO: sanity check there's no match in classes_
1615 it = image_classes_.insert(std::make_pair(hash, klass));
1616 } else {
1617 // TODO: sanity check there's no match in image_classes_
1618 it = classes_.insert(std::make_pair(hash, klass));
1619 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001620 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001621}
1622
Brian Carlstromae826982011-11-09 01:33:42 -08001623bool ClassLinker::RemoveClass(const std::string& descriptor, const ClassLoader* class_loader) {
1624 size_t hash = StringPieceHash()(descriptor);
1625 MutexLock mu(classes_lock_);
1626 typedef Table::const_iterator It; // TODO: C++0x auto
1627 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001628 ClassHelper kh;
Brian Carlstromae826982011-11-09 01:33:42 -08001629 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
1630 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001631 kh.ChangeClass(klass);
1632 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001633 classes_.erase(it);
1634 return true;
1635 }
1636 }
1637 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1638 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001639 kh.ChangeClass(klass);
1640 if (kh.GetDescriptor() == descriptor && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001641 image_classes_.erase(it);
1642 return true;
1643 }
1644 }
1645 return false;
1646}
1647
Brian Carlstromaded5f72011-10-07 17:15:04 -07001648Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001649 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001650 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001651 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001652 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001653 ClassHelper kh(NULL, this);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001654 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001655 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001656 kh.ChangeClass(klass);
1657 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001658 return klass;
1659 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001660 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001661 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1662 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001663 kh.ChangeClass(klass);
1664 if (descriptor == kh.GetDescriptor() && klass->GetClassLoader() == class_loader) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001665 return klass;
1666 }
1667 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001668 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001669}
1670
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001671void ClassLinker::LookupClasses(const std::string& descriptor, std::vector<Class*>& classes) {
1672 classes.clear();
1673 size_t hash = StringPieceHash()(descriptor);
1674 MutexLock mu(classes_lock_);
1675 typedef Table::const_iterator It; // TODO: C++0x auto
1676 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001677 ClassHelper kh(NULL, this);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001678 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001679 Class* klass = it->second;
1680 kh.ChangeClass(klass);
1681 if (descriptor == kh.GetDescriptor()) {
1682 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001683 }
1684 }
1685 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001686 Class* klass = it->second;
1687 kh.ChangeClass(klass);
1688 if (descriptor == kh.GetDescriptor()) {
1689 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001690 }
1691 }
1692}
1693
jeffhao98eacac2011-09-14 16:11:53 -07001694void ClassLinker::VerifyClass(Class* klass) {
1695 if (klass->IsVerified()) {
1696 return;
1697 }
1698
1699 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001700 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001701
Ian Rogersd81871c2011-10-03 13:57:23 -07001702 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001703 klass->SetStatus(Class::kStatusVerified);
1704 } else {
1705 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001706 Thread* self = Thread::Current();
1707 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1708 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001709 PrettyDescriptor(klass).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001710 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001711 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001712 }
jeffhao98eacac2011-09-14 16:11:53 -07001713}
1714
Ian Rogersc2b44472011-12-14 21:17:17 -08001715static void CheckProxyConstructor(Method* constructor);
1716static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1717
Jesse Wilson95caa792011-10-12 18:14:17 -04001718Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001719 ClassLoader* loader, ObjectArray<Method>* methods,
1720 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001721 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001722 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001723 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001724 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001725 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001726 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001727 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001728 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001729 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001730 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001731
1732 klass->SetStatus(Class::kStatusIdx);
1733
1734 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1735
1736 // Create static field that holds throws, instance fields are inherited
1737 klass->SetSFields(AllocObjectArray<Field>(1));
1738 SirtRef<Field> sfield(AllocField());
1739 klass->SetStaticField(0, sfield.get());
1740 sfield->SetDexFieldIndex(-1);
1741 sfield->SetDeclaringClass(klass.get());
1742 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001743
Ian Rogers466bb252011-10-14 03:29:56 -07001744 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001745 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001746 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001747
Ian Rogers466bb252011-10-14 03:29:56 -07001748 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001749 size_t num_virtual_methods = methods->GetLength();
1750 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1751 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001752 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001753 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001754 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001755
1756 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1757 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1758 DCHECK(!Thread::Current()->IsExceptionPending());
1759
1760 // Link the fields and virtual methods, creating vtable and iftables
1761 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001762 DCHECK(Thread::Current()->IsExceptionPending());
1763 return NULL;
1764 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001765 sfield->SetObject(NULL, throws); // initialize throws field
1766 klass->SetStatus(Class::kStatusInitialized);
1767
1768 // sanity checks
1769#ifndef NDEBUG
1770 bool debug = true;
1771#else
1772 bool debug = false;
1773#endif
1774 if (debug) {
1775 CHECK(klass->GetIFields() == NULL);
1776 CheckProxyConstructor(klass->GetDirectMethod(0));
1777 for (size_t i = 0; i < num_virtual_methods; ++i) {
1778 SirtRef<Method> prototype(methods->Get(i));
1779 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
1780 }
1781 std::string throws_field_name = "java.lang.Class[][] ";
1782 throws_field_name += name->ToModifiedUtf8();
1783 throws_field_name += ".throws";
1784 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
1785
1786 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
1787 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
1788 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001789 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001790}
1791
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001792std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
1793 DCHECK(proxy_class->IsProxyClass());
1794 String* name = proxy_class->GetName();
1795 DCHECK(name != NULL);
1796 return DotToDescriptor(name->ToModifiedUtf8().c_str());
1797}
1798
1799
1800Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07001801 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07001802 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001803 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001804 Method* proxy_constructor = proxy_direct_methods->Get(2);
1805 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1806 // code_ too)
1807 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1808 // Make this constructor public and fix the class to be our Proxy version
1809 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001810 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08001811 return constructor;
1812}
1813
1814static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07001815 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001816 MethodHelper mh(constructor);
1817 CHECK_STREQ(mh.GetName(), "<init>");
1818 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07001819 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001820}
1821
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001822Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
1823 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
1824 // prototype method
1825 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
1826 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07001827 // as necessary
1828 Method* method = down_cast<Method*>(prototype->Clone());
1829
1830 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1831 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001832 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001833 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001834
Ian Rogers466bb252011-10-14 03:29:56 -07001835 // At runtime the method looks like a reference and argument saving method, clone the code
1836 // related parameters from this method.
1837 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1838 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1839 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1840 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1841 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08001842 return method;
1843}
Jesse Wilson95caa792011-10-12 18:14:17 -04001844
Ian Rogersc2b44472011-12-14 21:17:17 -08001845static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07001846 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001847 CHECK(!prototype->IsFinal());
1848 CHECK(method->IsFinal());
1849 CHECK(!method->IsAbstract());
1850 MethodHelper mh(method);
1851 const char* method_name = mh.GetName();
1852 const char* method_shorty = mh.GetShorty();
1853 Class* method_return = mh.GetReturnType();
1854
1855 mh.ChangeMethod(prototype.get());
1856
1857 CHECK_STREQ(mh.GetName(), method_name);
1858 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07001859
1860 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001861 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04001862}
1863
Brian Carlstrom25c33252011-09-18 15:58:35 -07001864bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001865 CHECK(klass->IsResolved() || klass->IsErroneous())
1866 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001867
Carl Shapirob5573532011-07-12 18:22:59 -07001868 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001869
Brian Carlstrom25c33252011-09-18 15:58:35 -07001870 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001871 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001872 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001873 ObjectLock lock(klass);
1874
Brian Carlstromd1422f82011-09-28 11:37:09 -07001875 if (klass->GetStatus() == Class::kStatusInitialized) {
1876 return true;
1877 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001878
Brian Carlstromd1422f82011-09-28 11:37:09 -07001879 if (klass->IsErroneous()) {
1880 ThrowEarlierClassFailure(klass);
1881 return false;
1882 }
1883
1884 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001885 VerifyClass(klass);
1886 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001887 return false;
1888 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001889 }
1890
Brian Carlstrom25c33252011-09-18 15:58:35 -07001891 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1892 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001893 // if the class has a <clinit> but we can't run it during compilation,
1894 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001895 return false;
1896 }
1897
Brian Carlstromd1422f82011-09-28 11:37:09 -07001898 // If the class is kStatusInitializing, either this thread is
1899 // initializing higher up the stack or another thread has beat us
1900 // to initializing and we need to wait. Either way, this
1901 // invocation of InitializeClass will not be responsible for
1902 // running <clinit> and will return.
1903 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001904 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001905 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001906 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001907 return true;
1908 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001909 // No. That's fine. Wait for another thread to finish initializing.
1910 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001911 }
1912
1913 if (!ValidateSuperClassDescriptors(klass)) {
1914 klass->SetStatus(Class::kStatusError);
1915 return false;
1916 }
1917
Brian Carlstromd1422f82011-09-28 11:37:09 -07001918 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001919
Elliott Hughesdcc24742011-09-07 14:02:44 -07001920 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001921 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001922 }
1923
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001924 uint64_t t0 = NanoTime();
1925
Brian Carlstrom25c33252011-09-18 15:58:35 -07001926 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001927 return false;
1928 }
1929
1930 InitializeStaticFields(klass);
1931
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001932 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001933 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001934 }
1935
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001936 uint64_t t1 = NanoTime();
1937
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001938 {
1939 ObjectLock lock(klass);
1940
1941 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001942 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001943 klass->SetStatus(Class::kStatusError);
1944 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001945 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1946 RuntimeStats* thread_stats = self->GetStats();
1947 ++global_stats->class_init_count;
1948 ++thread_stats->class_init_count;
1949 global_stats->class_init_time_ns += (t1 - t0);
1950 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001951 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001952 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001953 ClassHelper kh(klass);
1954 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08001955 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001956 }
1957 lock.NotifyAll();
1958 }
1959
1960 return true;
1961}
1962
Brian Carlstromd1422f82011-09-28 11:37:09 -07001963bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1964 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001965 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001966 lock.Wait();
1967
1968 // When we wake up, repeat the test for init-in-progress. If
1969 // there's an exception pending (only possible if
1970 // "interruptShouldThrow" was set), bail out.
1971 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001972 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001973 klass->SetStatus(Class::kStatusError);
1974 return false;
1975 }
1976 // Spurious wakeup? Go back to waiting.
1977 if (klass->GetStatus() == Class::kStatusInitializing) {
1978 continue;
1979 }
1980 if (klass->IsErroneous()) {
1981 // The caller wants an exception, but it was thrown in a
1982 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001983 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001984 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001985 return false;
1986 }
1987 if (klass->IsInitialized()) {
1988 return true;
1989 }
1990 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1991 }
1992 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1993}
1994
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001995bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1996 if (klass->IsInterface()) {
1997 return true;
1998 }
1999 // begin with the methods local to the superclass
2000 if (klass->HasSuperClass() &&
2001 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2002 const Class* super = klass->GetSuperClass();
2003 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002004 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002005 if (method != super->GetVirtualMethod(i) &&
2006 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002007 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2008
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002009 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2010 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2011 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002012 return false;
2013 }
2014 }
2015 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002016 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2017 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2018 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002019 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2020 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002021 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002022 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002023 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002024 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2025
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002026 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2027 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2028 PrettyMethod(method).c_str(),
2029 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002030 return false;
2031 }
2032 }
2033 }
2034 }
2035 return true;
2036}
2037
2038bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002039 const Class* klass1,
2040 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002041 if (klass1 == klass2) {
2042 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002043 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002044 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002045 const DexFile::ProtoId& proto_id =
2046 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002047 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2048 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002049 if (descriptor == NULL) {
2050 break;
2051 }
2052 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2053 // Found a non-primitive type.
2054 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
2055 return false;
2056 }
2057 }
2058 }
2059 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002060 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002061 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07002062 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002063 return false;
2064 }
2065 }
2066 return true;
2067}
2068
2069// Returns true if classes referenced by the descriptor are the
2070// same classes in klass1 as they are in klass2.
2071bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07002072 const Class* klass1,
2073 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002074 CHECK(descriptor != NULL);
2075 CHECK(klass1 != NULL);
2076 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002077 if (klass1 == klass2) {
2078 return true;
2079 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002080 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002081 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002082 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002083 // TODO: found2 == NULL
2084 // TODO: lookup found1 in initiating loader list
2085 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002086 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07002087 return found1 == found2;
2088 } else {
2089 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002090 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002091}
2092
Brian Carlstrom25c33252011-09-18 15:58:35 -07002093bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002094 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002095 if (!klass->IsInterface() && klass->HasSuperClass()) {
2096 Class* super_class = klass->GetSuperClass();
2097 if (super_class->GetStatus() != Class::kStatusInitialized) {
2098 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002099 Thread* self = Thread::Current();
2100 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002101 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002102 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002103 // TODO: check for a pending exception
2104 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002105 if (!can_run_clinit) {
2106 // Don't set status to error when we can't run <clinit>.
2107 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2108 klass->SetStatus(Class::kStatusVerified);
2109 return false;
2110 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002111 klass->SetStatus(Class::kStatusError);
2112 klass->NotifyAll();
2113 return false;
2114 }
2115 }
2116 }
2117 return true;
2118}
2119
Brian Carlstrom25c33252011-09-18 15:58:35 -07002120bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002121 CHECK(c != NULL);
2122 if (c->IsInitialized()) {
2123 return true;
2124 }
2125
Elliott Hughes5f791332011-09-15 17:45:30 -07002126 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002127 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002128 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002129 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002130}
2131
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002132void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002133 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002134 const ClassLoader* cl = c->GetClassLoader();
2135 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002136 ClassDataItemIterator it(dex_file, class_data);
2137 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2138 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002139 }
2140}
2141
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002142void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002143 size_t num_static_fields = klass->NumStaticFields();
2144 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002145 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002146 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002147 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002148 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002149 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002150 return;
2151 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002152 ClassHelper kh(klass);
2153 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002154 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002155 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002156 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002157
Ian Rogers0571d352011-11-03 19:51:38 -07002158 if (it.HasNext()) {
2159 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2160 std::map<uint32_t, Field*> field_map;
2161 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2162 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2163 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002164 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002165 }
2166}
2167
Ian Rogersc2b44472011-12-14 21:17:17 -08002168bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002169 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002170 if (!LinkSuperClass(klass)) {
2171 return false;
2172 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002173 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002174 return false;
2175 }
2176 if (!LinkInstanceFields(klass)) {
2177 return false;
2178 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002179 if (!LinkStaticFields(klass)) {
2180 return false;
2181 }
2182 CreateReferenceInstanceOffsets(klass);
2183 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002184 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2185 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002186 return true;
2187}
2188
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002189bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002190 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002191 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2192 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
2193 if (class_def == NULL) {
2194 return false;
2195 }
2196 uint16_t super_class_idx = class_def->superclass_idx_;
2197 if (super_class_idx != DexFile::kDexNoIndex16) {
2198 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002199 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002200 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002201 return false;
2202 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002203 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002204 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002205 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2206 if (interfaces != NULL) {
2207 for (size_t i = 0; i < interfaces->Size(); i++) {
2208 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2209 Class* interface = ResolveType(dex_file, idx, klass.get());
2210 if (interface == NULL) {
2211 DCHECK(Thread::Current()->IsExceptionPending());
2212 return false;
2213 }
2214 // Verify
2215 if (!klass->CanAccess(interface)) {
2216 // TODO: the RI seemed to ignore this in my testing.
2217 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2218 "Interface %s implemented by class %s is inaccessible",
2219 PrettyDescriptor(interface).c_str(),
2220 PrettyDescriptor(klass.get()).c_str());
2221 return false;
2222 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002223 }
2224 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002225 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002226 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002227 return true;
2228}
2229
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002230bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002231 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002232 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002233 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002234 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002235 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002236 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002237 return false;
2238 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002239 return true;
2240 }
2241 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002242 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002243 return false;
2244 }
2245 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002246 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002247 Thread* thread = Thread::Current();
2248 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002249 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002250 PrettyDescriptor(super).c_str(),
2251 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002252 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002253 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002254 return false;
2255 }
2256 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002257 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002258 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002259 PrettyDescriptor(super).c_str(),
2260 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002261 return false;
2262 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002263
2264 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2265 if (super->IsFinalizable()) {
2266 klass->SetFinalizable();
2267 }
2268
Elliott Hughes2da50362011-10-10 16:57:08 -07002269 // Inherit reference flags (if any) from the superclass.
2270 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2271 if (reference_flags != 0) {
2272 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2273 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002274 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002275 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002276 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002277 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002278 return false;
2279 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002280
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002281#ifndef NDEBUG
2282 // Ensure super classes are fully resolved prior to resolving fields..
2283 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002284 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002285 super = super->GetSuperClass();
2286 }
2287#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288 return true;
2289}
2290
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002291// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002292bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002293 if (klass->IsInterface()) {
2294 // No vtable.
2295 size_t count = klass->NumVirtualMethods();
2296 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002297 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002298 return false;
2299 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002300 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002301 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002302 }
jeffhaobdb76512011-09-07 11:43:16 -07002303 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002304 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002305 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002306 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002307 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002308 }
2309 return true;
2310}
2311
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002312bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002313 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002314 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2315 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002316 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002317 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002318 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002319 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002320 MethodHelper local_mh(NULL, this);
2321 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002322 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002323 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002324 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002325 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002326 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002327 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002328 super_mh.ChangeMethod(super_method);
2329 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002330 // Verify
2331 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002332 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002333 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002334 PrettyDescriptor(klass.get()).c_str(),
2335 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002336 return false;
2337 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002338 vtable->Set(j, local_method);
2339 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002340 break;
2341 }
2342 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002343 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002344 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002345 vtable->Set(actual_count, local_method);
2346 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002347 actual_count += 1;
2348 }
2349 }
2350 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002351 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002352 return false;
2353 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002354 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002355 CHECK_LE(actual_count, max_count);
2356 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002357 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002359 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002360 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002361 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002362 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002363 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002364 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002365 return false;
2366 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002367 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002368 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002369 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2370 vtable->Set(i, virtual_method);
2371 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002372 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002373 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002374 }
2375 return true;
2376}
2377
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002378bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002379 size_t super_ifcount;
2380 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002381 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002382 } else {
2383 super_ifcount = 0;
2384 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002385 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002386 ClassHelper kh(klass.get(), this);
2387 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2388 ifcount += num_interfaces;
2389 for (size_t i = 0; i < num_interfaces; i++) {
2390 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2391 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002392 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002393 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002394 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002395 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002396 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002397 return true;
2398 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002399 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002400 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002401 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2402 for (size_t i = 0; i < super_ifcount; i++) {
2403 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2404 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002405 }
2406 // Flatten the interface inheritance hierarchy.
2407 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002408 for (size_t i = 0; i < num_interfaces; i++) {
2409 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002410 DCHECK(interface != NULL);
2411 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002412 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002413 Thread* thread = Thread::Current();
2414 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002415 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002416 PrettyDescriptor(klass.get()).c_str(),
2417 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002418 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002419 return false;
2420 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002421 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002422 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002423 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002424 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2425 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002426 }
2427 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002428 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002429 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002430
2431 // If we're an interface, we don't need the vtable pointers, so we're done.
2432 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002433 return true;
2434 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002435 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002436 MethodHelper vtable_mh(NULL, this);
2437 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002438 for (size_t i = 0; i < ifcount; ++i) {
2439 InterfaceEntry* interface_entry = iftable->Get(i);
2440 Class* interface = interface_entry->GetInterface();
2441 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2442 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002443 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002444 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2445 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002446 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002447 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002448 // For each method listed in the interface's method list, find the
2449 // matching method in our class's method list. We want to favor the
2450 // subclass over the superclass, which just requires walking
2451 // back from the end of the vtable. (This only matters if the
2452 // superclass defines a private method and this class redefines
2453 // it -- otherwise it would use the same vtable slot. In .dex files
2454 // those don't end up in the virtual method table, so it shouldn't
2455 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002456 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2457 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002458 vtable_mh.ChangeMethod(vtable_method);
2459 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002460 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002461 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002462 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002463 return false;
2464 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002465 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002466 break;
2467 }
2468 }
2469 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002470 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002471 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002472 Method* mir_method = miranda_list[mir];
2473 vtable_mh.ChangeMethod(mir_method);
2474 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002475 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002476 break;
2477 }
2478 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002479 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002480 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002481 miranda_method.reset(AllocMethod());
2482 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2483 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002484 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002485 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002486 }
2487 }
2488 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002489 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002490 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002491 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002492 klass->SetVirtualMethods((old_method_count == 0)
2493 ? AllocObjectArray<Method>(new_method_count)
2494 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002495
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002496 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2497 CHECK(vtable != NULL);
2498 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002499 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002500 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002501 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002502 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002503 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002504 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2505 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2506 klass->SetVirtualMethod(old_method_count + i, method);
2507 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002508 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002509 // TODO: do not assign to the vtable field until it is fully constructed.
2510 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002511 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002512
2513 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2514 for (int i = 0; i < vtable->GetLength(); ++i) {
2515 CHECK(vtable->Get(i) != NULL);
2516 }
2517
2518// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2519
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002520 return true;
2521}
2522
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002523bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2524 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002525 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002526}
2527
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002528bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2529 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002530 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002531 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002532 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002533 return success;
2534}
2535
Brian Carlstromdbc05252011-09-09 01:59:59 -07002536struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002537 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002538 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002539 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002540 fh_->ChangeField(field1);
2541 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2542 fh_->ChangeField(field2);
2543 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002544 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2545 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2546 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2547 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002548 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2549 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2550 if (order1 != order2) {
2551 return order1 < order2;
2552 }
2553
2554 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002555 fh_->ChangeField(field1);
2556 StringPiece name1(fh_->GetName());
2557 fh_->ChangeField(field2);
2558 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002559 return name1 < name2;
2560 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002561
2562 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002563};
2564
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002565bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002566 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002567 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002568
2569 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002570 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002571
2572 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002573 size_t size;
2574 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002575 if (is_static) {
2576 size = klass->GetClassSize();
2577 field_offset = Class::FieldsOffset();
2578 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002579 Class* super_class = klass->GetSuperClass();
2580 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002581 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002582 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002583 }
2584 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002585 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002586
Brian Carlstromdbc05252011-09-09 01:59:59 -07002587 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002588
Brian Carlstromdbc05252011-09-09 01:59:59 -07002589 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002590 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002591 std::deque<Field*> grouped_and_sorted_fields;
2592 for (size_t i = 0; i < num_fields; i++) {
2593 grouped_and_sorted_fields.push_back(fields->Get(i));
2594 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002595 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002596 std::sort(grouped_and_sorted_fields.begin(),
2597 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002598 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002599
2600 // References should be at the front.
2601 size_t current_field = 0;
2602 size_t num_reference_fields = 0;
2603 for (; current_field < num_fields; current_field++) {
2604 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002605 fh.ChangeField(field);
2606 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002607 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002608 if (isPrimitive) {
2609 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002610 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002611 grouped_and_sorted_fields.pop_front();
2612 num_reference_fields++;
2613 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002614 field->SetOffset(field_offset);
2615 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002616 }
2617
2618 // Now we want to pack all of the double-wide fields together. If
2619 // we're not aligned, though, we want to shuffle one 32-bit field
2620 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002621 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002622 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2623 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002624 fh.ChangeField(field);
2625 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002626 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2627 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002628 continue;
2629 }
2630 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002631 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002632 // drop the consumed field
2633 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2634 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002635 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002636 // whether we found a 32-bit field for padding or not, we advance
2637 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002638 }
2639
2640 // Alignment is good, shuffle any double-wide fields forward, and
2641 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002642 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002643 while (!grouped_and_sorted_fields.empty()) {
2644 Field* field = grouped_and_sorted_fields.front();
2645 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002646 fh.ChangeField(field);
2647 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002648 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002649 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002650 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002651 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002652 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002653 ? sizeof(uint64_t)
2654 : sizeof(uint32_t)));
2655 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002656 }
2657
Elliott Hughesadb460d2011-10-05 17:02:34 -07002658 // 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 -08002659 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2660 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002661 // We know there are no non-reference fields in the Reference classes, and we know
2662 // that 'referent' is alphabetically last, so this is easy...
2663 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002664 fh.ChangeField(fields->Get(num_fields - 1));
2665 StringPiece name(fh.GetName());
2666 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002667 --num_reference_fields;
2668 }
2669
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002670#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002671 // Make sure that all reference fields appear before
2672 // non-reference fields, and all double-wide fields are aligned.
2673 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002674 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002675 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002676 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002677 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002678 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002679 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002680 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2681 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002682 fh.ChangeField(field);
2683 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002684 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002685 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002686 is_primitive = true; // We lied above, so we have to expect a lie here.
2687 }
2688 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002689 if (!seen_non_ref) {
2690 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002691 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002692 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002693 } else {
2694 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002695 }
2696 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002697 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002698 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002699 }
2700#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002701 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002702 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002703 if (is_static) {
2704 klass->SetNumReferenceStaticFields(num_reference_fields);
2705 klass->SetClassSize(size);
2706 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002707 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002708 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002709 klass->SetObjectSize(size);
2710 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002711 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002712 return true;
2713}
2714
2715// Set the bitmap of reference offsets, refOffsets, from the ifields
2716// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002717void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002718 uint32_t reference_offsets = 0;
2719 Class* super_class = klass->GetSuperClass();
2720 if (super_class != NULL) {
2721 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002722 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002723 if (reference_offsets == CLASS_WALK_SUPER) {
2724 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002725 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002726 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002727 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002728 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002729}
2730
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002731void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002732 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002733}
2734
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002735void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002736 uint32_t reference_offsets) {
2737 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002738 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2739 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002740 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002741 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002742 // All of the fields that contain object references are guaranteed
2743 // to be at the beginning of the fields list.
2744 for (size_t i = 0; i < num_reference_fields; ++i) {
2745 // Note that byte_offset is the offset from the beginning of
2746 // object, not the offset into instance data
2747 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002748 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002749 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2750 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2751 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002752 CHECK_NE(new_bit, 0U);
2753 reference_offsets |= new_bit;
2754 } else {
2755 reference_offsets = CLASS_WALK_SUPER;
2756 break;
2757 }
2758 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002759 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002760 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002761 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002762 } else {
2763 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002764 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002765}
2766
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002767String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002768 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002769 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002770 if (resolved != NULL) {
2771 return resolved;
2772 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002773 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2774 int32_t utf16_length = dex_file.GetStringLength(string_id);
2775 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002776 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002777 dex_cache->SetResolvedString(string_idx, string);
2778 return string;
2779}
2780
2781Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002782 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002783 DexCache* dex_cache,
2784 const ClassLoader* class_loader) {
2785 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002786 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002787 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002788 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002789 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002790 // TODO: we used to throw here if resolved's class loader was not the
2791 // boot class loader. This was to permit different classes with the
2792 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002793 dex_cache->SetResolvedType(type_idx, resolved);
2794 } else {
2795 DCHECK(Thread::Current()->IsExceptionPending());
2796 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002797 }
2798 return resolved;
2799}
2800
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002801Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2802 uint32_t method_idx,
2803 DexCache* dex_cache,
2804 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002805 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002806 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2807 if (resolved != NULL) {
2808 return resolved;
2809 }
2810 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2811 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2812 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002813 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002814 return NULL;
2815 }
2816
Ian Rogers0571d352011-11-03 19:51:38 -07002817 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2818 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002819 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002820 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002821 } else if (klass->IsInterface()) {
2822 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002823 } else {
2824 resolved = klass->FindVirtualMethod(name, signature);
2825 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002826 if (resolved != NULL) {
2827 dex_cache->SetResolvedMethod(method_idx, resolved);
2828 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002829 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002830 }
2831 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002832}
2833
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002834Field* ClassLinker::ResolveField(const DexFile& dex_file,
2835 uint32_t field_idx,
2836 DexCache* dex_cache,
2837 const ClassLoader* class_loader,
2838 bool is_static) {
2839 Field* resolved = dex_cache->GetResolvedField(field_idx);
2840 if (resolved != NULL) {
2841 return resolved;
2842 }
2843 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2844 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2845 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08002846 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002847 return NULL;
2848 }
2849
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002850 const char* name = dex_file.GetFieldName(field_id);
2851 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002852 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002853 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002854 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002855 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002856 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002857 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002858 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002859 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08002860 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
2861 }
2862 return resolved;
2863}
2864
2865Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
2866 uint32_t field_idx,
2867 DexCache* dex_cache,
2868 const ClassLoader* class_loader) {
2869 Field* resolved = dex_cache->GetResolvedField(field_idx);
2870 if (resolved != NULL) {
2871 return resolved;
2872 }
2873 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2874 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2875 if (klass == NULL) {
2876 DCHECK(Thread::Current()->IsExceptionPending());
2877 return NULL;
2878 }
2879
2880 const char* name = dex_file.GetFieldName(field_id);
2881 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
2882 resolved = klass->FindField(name, type);
2883 if (resolved != NULL) {
2884 dex_cache->SetResolvedField(field_idx, resolved);
2885 } else {
2886 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002887 }
2888 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002889}
2890
Ian Rogersad25ac52011-10-04 19:13:33 -07002891const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2892 Class* declaring_class = referrer->GetDeclaringClass();
2893 DexCache* dex_cache = declaring_class->GetDexCache();
2894 const DexFile& dex_file = FindDexFile(dex_cache);
2895 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2896 return dex_file.GetShorty(method_id.proto_idx_);
2897}
2898
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002899void ClassLinker::DumpAllClasses(int flags) const {
2900 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2901 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2902 std::vector<Class*> all_classes;
2903 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002904 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002905 typedef Table::const_iterator It; // TODO: C++0x auto
2906 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2907 all_classes.push_back(it->second);
2908 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002909 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2910 all_classes.push_back(it->second);
2911 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002912 }
2913
2914 for (size_t i = 0; i < all_classes.size(); ++i) {
2915 all_classes[i]->DumpClass(std::cerr, flags);
2916 }
2917}
2918
Elliott Hughescac6cc72011-11-03 20:31:21 -07002919void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2920 MutexLock mu(classes_lock_);
2921 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2922 << classes_.size() << " allocated classes\n";
2923}
2924
Elliott Hughese27955c2011-08-26 15:21:24 -07002925size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002926 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002927 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002928}
2929
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002930pid_t ClassLinker::GetClassesLockOwner() {
2931 return classes_lock_.GetOwner();
2932}
2933
2934pid_t ClassLinker::GetDexLockOwner() {
2935 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002936}
2937
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002938void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
2939 DCHECK(!init_done_);
2940
2941 DCHECK(klass != NULL);
2942 DCHECK(klass->GetClassLoader() == NULL);
2943
2944 DCHECK(class_roots_ != NULL);
2945 DCHECK(class_roots_->Get(class_root) == NULL);
2946 class_roots_->Set(class_root, klass);
2947}
2948
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002949} // namespace art