blob: afb6721d109053df4c3371cc0f02331ba85bfcd7 [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 Carlstromdbc05252011-09-09 01:59:59 -07005#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07006#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07007#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -07008#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07009
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070010#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070011#include "class_loader.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070012#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070013#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070014#include "dex_verifier.h"
15#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070016#include "intern_table.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070017#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070018#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070019#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070020#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070021#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070022#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070023#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070024#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070025#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070026#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070028#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070029#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070030
31namespace art {
32
Elliott Hughes4a2b4172011-09-20 17:08:25 -070033namespace {
34
Elliott Hughes362f9bc2011-10-17 18:56:41 -070035void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070036void ThrowNoClassDefFoundError(const char* fmt, ...) {
37 va_list args;
38 va_start(args, fmt);
39 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
40 va_end(args);
41}
42
Elliott Hughes362f9bc2011-10-17 18:56:41 -070043void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070044void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070045 va_list args;
46 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070047 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070048 va_end(args);
49}
50
Elliott Hughes362f9bc2011-10-17 18:56:41 -070051void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070052void ThrowLinkageError(const char* fmt, ...) {
53 va_list args;
54 va_start(args, fmt);
55 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
56 va_end(args);
57}
58
Elliott Hughescc5f9a92011-09-28 19:17:29 -070059void ThrowNoSuchMethodError(const char* kind,
60 Class* c, const StringPiece& name, const StringPiece& signature) {
61 DexCache* dex_cache = c->GetDexCache();
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070062 std::ostringstream msg;
Elliott Hughescc5f9a92011-09-28 19:17:29 -070063 msg << "no " << kind << " method " << name << "." << signature
64 << " in class " << c->GetDescriptor()->ToModifiedUtf8()
65 << " or its superclasses";
66 if (dex_cache) {
67 msg << " (defined in " << dex_cache->GetLocation()->ToModifiedUtf8() << ")";
68 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070069 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070070}
71
Elliott Hughes4a2b4172011-09-20 17:08:25 -070072void ThrowEarlierClassFailure(Class* c) {
73 /*
74 * The class failed to initialize on a previous attempt, so we want to throw
75 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
76 * failed in verification, in which case v2 5.4.1 says we need to re-throw
77 * the previous error.
78 */
79 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
80
81 if (c->GetVerifyErrorClass() != NULL) {
82 // TODO: change the verifier to store an _instance_, with a useful detail message?
83 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070084 Thread::Current()->ThrowNewException(error_descriptor.c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -070085 PrettyDescriptor(c->GetDescriptor()).c_str());
86 } else {
87 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
88 }
89}
90
Elliott Hughes4d0207c2011-10-03 19:14:34 -070091void WrapExceptionInInitializer() {
92 JNIEnv* env = Thread::Current()->GetJniEnv();
93
94 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
95 CHECK(cause.get() != NULL);
96
97 env->ExceptionClear();
98
99 // TODO: add java.lang.Error to JniConstants?
100 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
101 CHECK(error_class.get() != NULL);
102 if (env->IsInstanceOf(cause.get(), error_class.get())) {
103 // We only wrap non-Error exceptions; an Error can just be used as-is.
104 env->Throw(cause.get());
105 return;
106 }
107
108 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
109 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
110 CHECK(eiie_class.get() != NULL);
111
112 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
113 CHECK(mid != NULL);
114
115 ScopedLocalRef<jthrowable> eiie(env,
116 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
117 env->Throw(eiie.get());
118}
119
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700120} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700121
Elliott Hughes418d20f2011-09-22 14:00:39 -0700122const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700123 "Ljava/lang/Class;",
124 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700125 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700126 "[Ljava/lang/Object;",
127 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700128 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700129 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700130 "Ljava/lang/reflect/Field;",
131 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700132 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700133 "Ljava/lang/ClassLoader;",
134 "Ldalvik/system/BaseDexClassLoader;",
135 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700136 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700137 "Z",
138 "B",
139 "C",
140 "D",
141 "F",
142 "I",
143 "J",
144 "S",
145 "V",
146 "[Z",
147 "[B",
148 "[C",
149 "[D",
150 "[F",
151 "[I",
152 "[J",
153 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700154 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700155};
156
Elliott Hughes5f791332011-09-15 17:45:30 -0700157class ObjectLock {
158 public:
159 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
160 CHECK(object != NULL);
161 obj_->MonitorEnter(self_);
162 }
163
164 ~ObjectLock() {
165 obj_->MonitorExit(self_);
166 }
167
168 void Wait() {
169 return Monitor::Wait(self_, obj_, 0, 0, false);
170 }
171
172 void Notify() {
173 obj_->Notify();
174 }
175
176 void NotifyAll() {
177 obj_->NotifyAll();
178 }
179
180 private:
181 Thread* self_;
182 Object* obj_;
183 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
184};
185
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700186ClassLinker* ClassLinker::Create(const std::string& boot_class_path,
187 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700188 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700189 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700190 class_linker->Init(boot_class_path);
191 return class_linker.release();
192}
193
194ClassLinker* ClassLinker::Create(InternTable* intern_table) {
195 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
196 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700197 return class_linker.release();
198}
199
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700200ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700201 : dex_lock_("ClassLinker dex lock"),
202 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700203 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700204 array_interfaces_(NULL),
205 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700206 init_done_(false),
207 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700208 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700209}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700210
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700211void CreateClassPath(const std::string& class_path,
212 std::vector<const DexFile*>& class_path_vector) {
213 std::vector<std::string> parsed;
214 Split(class_path, ':', parsed);
215 for (size_t i = 0; i < parsed.size(); ++i) {
216 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
217 if (dex_file != NULL) {
218 class_path_vector.push_back(dex_file);
219 }
220 }
221}
222
223void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700224 const Runtime* runtime = Runtime::Current();
225 if (runtime->IsVerboseStartup()) {
226 LOG(INFO) << "ClassLinker::InitFrom entering";
227 }
228
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700229 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700230
Elliott Hughes30646832011-10-13 16:59:46 -0700231 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700232 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
233 CHECK(java_lang_Class.get() != NULL);
234 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700235 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700236 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700237
Elliott Hughes418d20f2011-09-22 14:00:39 -0700238 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700239 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
240 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700241
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700242 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700243 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
244 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700245 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700246 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700247 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700248
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700249 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700250 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
251 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700252
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700253 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700254 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700255
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700256 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700257 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
258 char_array_class->SetComponentType(char_class.get());
259 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700260
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700261 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700262 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
263 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700264 java_lang_String->SetObjectSize(sizeof(String));
265 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400266
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700267 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700268 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
269 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700270 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700271 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
272 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
273 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700274
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700275 // Create storage for root classes, save away our work so far (requires
276 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700277 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700278 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700279 SetClassRoot(kJavaLangClass, java_lang_Class.get());
280 SetClassRoot(kJavaLangObject, java_lang_Object.get());
281 SetClassRoot(kClassArrayClass, class_array_class.get());
282 SetClassRoot(kObjectArrayClass, object_array_class.get());
283 SetClassRoot(kCharArrayClass, char_array_class.get());
284 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700285
286 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700287 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
288 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
289 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
290 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
291 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
292 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
293 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
294 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700295
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700296 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700297 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700298 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299
300 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700301 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700302 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700303 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700304 IntArray::SetArrayClass(int_array_class.get());
305 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700307 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700308
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700309 // setup boot_class_path_ and register class_path now that we can
310 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700311 std::vector<const DexFile*> boot_class_path_vector;
312 CreateClassPath(boot_class_path, boot_class_path_vector);
313 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
314 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700315 CHECK(dex_file != NULL);
316 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700317 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700318
Elliott Hughes80609252011-09-23 17:24:51 -0700319 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700320 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Elliott Hughes80609252011-09-23 17:24:51 -0700321 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700322 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700323 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700324 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700325 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
326
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700327 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
328 CHECK(java_lang_reflect_Field.get() != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700329 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700330 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700335 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Elliott Hughes80609252011-09-23 17:24:51 -0700336 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700337 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700339 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700340 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700341 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342
343 // now we can use FindSystemClass
344
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700345 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700346 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700347 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700348
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700349 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700350 java_lang_Object->SetStatus(Class::kStatusNotReady);
351 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700352 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
354 java_lang_String->SetStatus(Class::kStatusNotReady);
355 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700356 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
358
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700359 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700360 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
361 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
362
363 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
364 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
365
366 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700367 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368
369 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
370 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
371
372 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700373 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700374
375 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
376 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
377
378 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
379 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
380
381 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
382 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
383
Elliott Hughes418d20f2011-09-22 14:00:39 -0700384 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700385 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700386
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700387 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700388 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389
390 // Setup the single, global copies of "interfaces" and "iftable"
391 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
392 CHECK(java_lang_Cloneable != NULL);
393 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
394 CHECK(java_io_Serializable != NULL);
395 CHECK(array_interfaces_ != NULL);
396 array_interfaces_->Set(0, java_lang_Cloneable);
397 array_interfaces_->Set(1, java_io_Serializable);
398 // We assume that Cloneable/Serializable don't have superinterfaces --
399 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700400 // supers as well.
401 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
402 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403
Elliott Hughes418d20f2011-09-22 14:00:39 -0700404 // Sanity check Class[] and Object[]'s interfaces
405 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
406 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
408 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700409
Elliott Hughes80609252011-09-23 17:24:51 -0700410 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700411 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700412 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700413 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414
Elliott Hughes80609252011-09-23 17:24:51 -0700415 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
416 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700417 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700418
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700419 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700420 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700421 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422
423 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700424 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700425 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700426
Ian Rogers466bb252011-10-14 03:29:56 -0700427 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
428
429 // Create java.lang.reflect.Proxy root
430 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
431 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
432
Brian Carlstrom1f870082011-08-23 16:02:11 -0700433 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700434 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
435 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700436 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700437 java_lang_ref_FinalizerReference->SetAccessFlags(
438 java_lang_ref_FinalizerReference->GetAccessFlags() |
439 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700440 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441 java_lang_ref_PhantomReference->SetAccessFlags(
442 java_lang_ref_PhantomReference->GetAccessFlags() |
443 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700444 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700445 java_lang_ref_SoftReference->SetAccessFlags(
446 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700447 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700448 java_lang_ref_WeakReference->SetAccessFlags(
449 java_lang_ref_WeakReference->GetAccessFlags() |
450 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700451
Brian Carlstromaded5f72011-10-07 17:15:04 -0700452 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700453 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700454 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700455 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
456
457 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
458 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
459 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
460
461 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
462 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
463 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
464 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
465
466 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700467 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
468 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700469 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700470
Brian Carlstroma663ea52011-08-19 23:33:41 -0700471 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700472
473 if (runtime->IsVerboseStartup()) {
474 LOG(INFO) << "ClassLinker::InitFrom exiting";
475 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700476}
477
478void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700479 const Runtime* runtime = Runtime::Current();
480 if (runtime->IsVerboseStartup()) {
481 LOG(INFO) << "ClassLinker::FinishInit entering";
482 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700483
484 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700485 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700486 // as the types of the field can't be resolved prior to the runtime being
487 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700488 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700489 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700490 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
491
Elliott Hughesadb460d2011-10-05 17:02:34 -0700492 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
493
Brian Carlstrom16192862011-09-12 17:50:06 -0700494 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
495 CHECK(pendingNext->GetName()->Equals("pendingNext"));
496 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
497
498 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
499 CHECK(queue->GetName()->Equals("queue"));
Elliott Hughesadb460d2011-10-05 17:02:34 -0700500 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue), java_lang_ref_ReferenceQueue);
Brian Carlstrom16192862011-09-12 17:50:06 -0700501
502 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
503 CHECK(queueNext->GetName()->Equals("queueNext"));
504 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
505
506 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
507 CHECK(referent->GetName()->Equals("referent"));
508 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
509
510 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
511 CHECK(zombie->GetName()->Equals("zombie"));
512 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
513
514 Heap::SetReferenceOffsets(referent->GetOffset(),
515 queue->GetOffset(),
516 queueNext->GetOffset(),
517 pendingNext->GetOffset(),
518 zombie->GetOffset());
519
Brian Carlstroma663ea52011-08-19 23:33:41 -0700520 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700521 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700522 ClassRoot class_root = static_cast<ClassRoot>(i);
523 Class* klass = GetClassRoot(class_root);
524 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700525 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700526 // note SetClassRoot does additional validation.
527 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700528 }
529
Elliott Hughes92f14b22011-10-06 12:29:54 -0700530 CHECK(array_iftable_ != NULL);
531 CHECK(array_interfaces_ != NULL);
532
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700533 // disable the slow paths in FindClass and CreatePrimitiveClass now
534 // that Object, Class, and Object[] are setup
535 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700536
537 if (runtime->IsVerboseStartup()) {
538 LOG(INFO) << "ClassLinker::FinishInit exiting";
539 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700540}
541
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700542void ClassLinker::RunRootClinits() {
543 Thread* self = Thread::Current();
544 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
545 Class* c = GetClassRoot(ClassRoot(i));
546 if (!c->IsArrayClass() && !c->IsPrimitive()) {
547 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700548 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700549 }
550 }
551}
552
jeffhao262bf462011-10-20 18:36:32 -0700553const OatFile* ClassLinker::GenerateOatFile(const std::string& filename) {
554 std::string oat_filename(GetArtCacheFilenameOrDie(OatFile::DexFilenameToOatFilename(filename)));
555
556 // fork and exec dex2oat
557 pid_t pid = fork();
558 if (pid == 0) {
559 std::string boot_image_option("--boot-image=");
560 boot_image_option += Heap::GetSpaces()[0]->GetImageFilename();
561
562 std::string dex_file_option("--dex-file=");
563 dex_file_option += filename;
564
565 std::string oat_file_option("--oat=");
566 oat_file_option += oat_filename;
567
568 execl("/system/bin/dex2oatd",
569 "/system/bin/dex2oatd",
570 "-Xms64m",
571 "-Xmx64m",
572 boot_image_option.c_str(),
573 dex_file_option.c_str(),
574 oat_file_option.c_str(),
575 NULL);
576
577 PLOG(FATAL) << "execl(dex2oatd) failed";
578 return NULL;
579 } else {
580 // wait for dex2oat to finish
581 int status;
582 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
583 if (got_pid != pid) {
584 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
585 return NULL;
586 }
587 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
588 LOG(ERROR) << "dex2oatd failed with dex-file=" << filename;
589 return NULL;
590 }
591 }
592 return OatFile::Open(oat_filename, "", NULL);
593}
594
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700595OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700596 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700597 const Runtime* runtime = Runtime::Current();
598 if (runtime->IsVerboseStartup()) {
599 LOG(INFO) << "ClassLinker::OpenOat entering";
600 }
601 const ImageHeader& image_header = space->GetImageHeader();
602 String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
603 std::string oat_filename;
604 oat_filename += runtime->GetHostPrefix();
605 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700606 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700607 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700608 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700609 return NULL;
610 }
611 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
612 uint32_t image_oat_checksum = image_header.GetOatChecksum();
613 if (oat_checksum != image_oat_checksum) {
614 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
615 << " to expected oat checksum " << std::hex << oat_checksum
616 << " in image";
617 return NULL;
618 }
619 oat_files_.push_back(oat_file);
620 if (runtime->IsVerboseStartup()) {
621 LOG(INFO) << "ClassLinker::OpenOat exiting";
622 }
623 return oat_file;
624}
625
Brian Carlstromaded5f72011-10-07 17:15:04 -0700626const OatFile* ClassLinker::FindOatFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700627 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700628 // TODO: check if dex_file matches an OatDexFile location and checksum
jeffhao262bf462011-10-20 18:36:32 -0700629 const OatFile* oat_file = FindOatFile(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
630 if (oat_file != NULL) {
631 return oat_file;
632 }
633 // generate oat file if it wasn't found
634 oat_file = GenerateOatFile(dex_file.GetLocation());
635 if (oat_file == NULL) {
636 LOG(ERROR) << "Failed to generate oat file from dex file " << dex_file.GetLocation();
637 return NULL;
638 }
639 oat_files_.push_back(oat_file);
640 return oat_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700641}
642
Brian Carlstromfad71432011-10-16 20:25:10 -0700643const OatFile* ClassLinker::FindOpenedOatFile(const std::string& location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700644 for (size_t i = 0; i < oat_files_.size(); i++) {
645 const OatFile* oat_file = oat_files_[i];
646 DCHECK(oat_file != NULL);
647 if (oat_file->GetLocation() == location) {
648 return oat_file;
649 }
650 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700651 return NULL;
652}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700653
Brian Carlstromfad71432011-10-16 20:25:10 -0700654const OatFile* ClassLinker::FindOatFile(const std::string& location) {
655 const OatFile* oat_file = FindOpenedOatFile(location);
656 if (oat_file != NULL) {
657 return oat_file;
658 }
659
660 oat_file = OatFile::Open(location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700661 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700662 if (location.empty() || location[0] != '/') {
663 LOG(ERROR) << "Failed to open oat file from " << location;
664 return NULL;
665 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700666
Brian Carlstroma9f19782011-10-13 00:14:47 -0700667 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
jeffhao262bf462011-10-20 18:36:32 -0700668 std::string cache_location = GetArtCacheFilenameOrDie(location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700669 oat_file = FindOpenedOatFile(cache_location);
670 if (oat_file != NULL) {
671 return oat_file;
672 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700673 oat_file = OatFile::Open(cache_location, "", NULL);
674 if (oat_file == NULL) {
jeffhao262bf462011-10-20 18:36:32 -0700675 LOG(INFO) << "Failed to open oat file from " << location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700676 return NULL;
677 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700678 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700679
680 CHECK(oat_file != NULL) << location;
681 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700682 return oat_file;
683}
684
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700685void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700686 const Runtime* runtime = Runtime::Current();
687 if (runtime->IsVerboseStartup()) {
688 LOG(INFO) << "ClassLinker::InitFromImage entering";
689 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700690 CHECK(!init_done_);
691
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700692 const std::vector<Space*>& spaces = Heap::GetSpaces();
693 for (size_t i = 0; i < spaces.size(); i++) {
694 Space* space = spaces[i] ;
695 if (space->IsImageSpace()) {
696 OatFile* oat_file = OpenOat(space);
697 CHECK(oat_file != NULL) << "Failed to open oat file for image";
698 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
699 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
700
701 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
702 static_cast<uint32_t>(dex_caches->GetLength()));
703 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700704 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700705 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
706
707 std::string dex_filename;
708 dex_filename += runtime->GetHostPrefix();
709 dex_filename += dex_file_location;
710 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
711 if (dex_file == NULL) {
712 LOG(FATAL) << "Failed to open dex file " << dex_filename
713 << " referenced from oat file as " << dex_file_location;
714 }
715
Brian Carlstromaded5f72011-10-07 17:15:04 -0700716 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
717 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700718
Brian Carlstromdf143242011-10-10 18:05:34 -0700719 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700720 }
721 }
722 }
723
Brian Carlstroma663ea52011-08-19 23:33:41 -0700724 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
725 DCHECK(heap_bitmap != NULL);
726
Brian Carlstroma663ea52011-08-19 23:33:41 -0700727 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700728 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700729
730 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700731 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
732 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700733
Elliott Hughes92f14b22011-10-06 12:29:54 -0700734 // reinit array_interfaces_ and array_iftable_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700735 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
736 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700737 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
738 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700739
Brian Carlstroma663ea52011-08-19 23:33:41 -0700740 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700741 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700742 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700743 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
744 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
745 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
746 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
747 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
748 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
749 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
750 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700751 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700752 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700753
754 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700755
756 if (runtime->IsVerboseStartup()) {
757 LOG(INFO) << "ClassLinker::InitFromImage exiting";
758 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700759}
760
Brian Carlstrom78128a62011-09-15 17:21:19 -0700761void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700762 DCHECK(obj != NULL);
763 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700764 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700765
Brian Carlstromc74255f2011-09-11 22:47:39 -0700766 if (obj->IsString()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700767 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700768 return;
769 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700770 if (obj->IsClass()) {
771 // restore class to ClassLinker::classes_ table
772 Class* klass = obj->AsClass();
773 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
774 class_linker->InsertClass(descriptor, klass);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700775 return;
776 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700777}
778
779// Keep in sync with InitCallback. Anything we visit, we need to
780// reinit references to when reinitializing a ClassLinker from a
781// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700782void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
783 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700784
785 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700786 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700787 }
788
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700789 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700790 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700791 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700792 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700793 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700794 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700795 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700796
Elliott Hughes410c0c82011-09-01 17:58:25 -0700797 visitor(array_interfaces_, arg);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700798 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700799}
800
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700801ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700802 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700803 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700804 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700805 BooleanArray::ResetArrayClass();
806 ByteArray::ResetArrayClass();
807 CharArray::ResetArrayClass();
808 DoubleArray::ResetArrayClass();
809 FloatArray::ResetArrayClass();
810 IntArray::ResetArrayClass();
811 LongArray::ResetArrayClass();
812 ShortArray::ResetArrayClass();
813 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700814 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700815 STLDeleteElements(&boot_class_path_);
816 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700817}
818
819DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700820 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
821 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700822 return NULL;
823 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700824 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
825 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700826 return NULL;
827 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700828 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
829 if (strings.get() == NULL) {
830 return NULL;
831 }
832 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
833 if (types.get() == NULL) {
834 return NULL;
835 }
836 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
837 if (methods.get() == NULL) {
838 return NULL;
839 }
840 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
841 if (fields.get() == NULL) {
842 return NULL;
843 }
844 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
845 if (code_and_direct_methods.get() == NULL) {
846 return NULL;
847 }
848 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
849 if (initialized_static_storage.get() == NULL) {
850 return NULL;
851 }
852
853 dex_cache->Init(location.get(),
854 strings.get(),
855 types.get(),
856 methods.get(),
857 fields.get(),
858 code_and_direct_methods.get(),
859 initialized_static_storage.get());
860 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700861}
862
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700863CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
864 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700865}
866
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700867InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
868 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700869 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
870 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700871 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700872 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700873}
874
Brian Carlstrom4873d462011-08-21 15:23:39 -0700875Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
876 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700877 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700878 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700879 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700880 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700881}
882
Brian Carlstrom4873d462011-08-21 15:23:39 -0700883Class* ClassLinker::AllocClass(size_t class_size) {
884 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700885}
886
Jesse Wilson35baaab2011-08-10 16:18:03 -0400887Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700888 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700889}
890
891Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700892 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700893}
894
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700895ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
896 return ObjectArray<StackTraceElement>::Alloc(
897 GetClassRoot(kJavaLangStackTraceElementArrayClass),
898 length);
899}
900
Brian Carlstromaded5f72011-10-07 17:15:04 -0700901Class* EnsureResolved(Class* klass) {
902 DCHECK(klass != NULL);
903 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700904 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700905 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700906 ObjectLock lock(klass);
907 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700908 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700909 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700910 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700911 return NULL;
912 }
913 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700914 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700915 lock.Wait();
916 }
917 }
918 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700919 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700920 return NULL;
921 }
922 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700923 CHECK(klass->IsResolved()) << PrettyClass(klass);
924 CHECK(!self->IsExceptionPending())
925 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
926 return klass;
927}
928
929Class* ClassLinker::FindClass(const std::string& descriptor,
930 const ClassLoader* class_loader) {
931 CHECK_NE(descriptor.size(), 0U);
932 Thread* self = Thread::Current();
933 DCHECK(self != NULL);
934 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
935 // Find the class in the loaded classes table.
936 Class* klass = LookupClass(descriptor, class_loader);
937 if (klass != NULL) {
938 return EnsureResolved(klass);
939 }
940 if (descriptor.size() == 1) {
941 // only the descriptors of primitive types should be 1 character long
942 return FindPrimitiveClass(descriptor[0]);
943 }
944 // Class is not yet loaded.
945 if (descriptor[0] == '[') {
946 return CreateArrayClass(descriptor, class_loader);
947 }
948 if (class_loader == NULL) {
949 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
950 if (pair.second == NULL) {
951 std::string name(PrintableString(descriptor));
952 ThrowNoClassDefFoundError("Class %s not found in boot class loader", name.c_str());
953 return NULL;
954 }
955 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
956 }
957
958 if (ClassLoader::UseCompileTimeClassPath()) {
959 const std::vector<const DexFile*>& class_path
960 = ClassLoader::GetCompileTimeClassPath(class_loader);
961 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
962 if (pair.second == NULL) {
963 return FindSystemClass(descriptor);
964 }
965 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
966 }
967
968 std::string class_name_string = DescriptorToDot(descriptor);
969 ScopedThreadStateChange(self, Thread::kNative);
970 JNIEnv* env = self->GetJniEnv();
Brian Carlstromdf143242011-10-10 18:05:34 -0700971 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
972 CHECK(c.get() != NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700973 // TODO: cache method?
Brian Carlstromdf143242011-10-10 18:05:34 -0700974 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700975 CHECK(mid != NULL);
Brian Carlstromdf143242011-10-10 18:05:34 -0700976 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -0700977 if (class_name_object.get() == NULL) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700978 return NULL;
979 }
Brian Carlstromdf143242011-10-10 18:05:34 -0700980 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
981 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
982 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700983}
984
985Class* ClassLinker::DefineClass(const std::string& descriptor,
986 const ClassLoader* class_loader,
987 const DexFile& dex_file,
988 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700989 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700990 // Load the class from the dex file.
991 if (!init_done_) {
992 // finish up init of hand crafted class_roots_
993 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700994 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700995 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700996 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700997 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700998 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -0700999 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001000 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001001 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001002 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001003 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001004 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001005 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001006 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001007 }
1008 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001009 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001010 }
1011 klass->SetDexCache(FindDexCache(dex_file));
1012 LoadClass(dex_file, dex_class_def, klass, class_loader);
1013 // Check for a pending exception during load
1014 Thread* self = Thread::Current();
1015 if (self->IsExceptionPending()) {
1016 return NULL;
1017 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001018 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001019 klass->SetClinitThreadId(self->GetTid());
1020 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001021 bool success = InsertClass(descriptor, klass.get()); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001022 if (!success) {
1023 // We may fail to insert if we raced with another thread.
1024 klass->SetClinitThreadId(0);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001025 klass.reset(LookupClass(descriptor, class_loader));
1026 CHECK(klass.get() != NULL);
1027 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001028 }
1029 // Finish loading (if necessary) by finding parents
1030 CHECK(!klass->IsLoaded());
1031 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1032 // Loading failed.
1033 CHECK(self->IsExceptionPending());
1034 lock.NotifyAll();
1035 return NULL;
1036 }
1037 CHECK(klass->IsLoaded());
1038 // Link the class (if necessary)
1039 CHECK(!klass->IsResolved());
1040 if (!LinkClass(klass)) {
1041 // Linking failed.
1042 CHECK(self->IsExceptionPending());
1043 lock.NotifyAll();
1044 return NULL;
1045 }
1046 CHECK(klass->IsResolved());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001047 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001048}
1049
Brian Carlstrom4873d462011-08-21 15:23:39 -07001050// Precomputes size that will be needed for Class, matching LinkStaticFields
1051size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1052 const DexFile::ClassDef& dex_class_def) {
1053 const byte* class_data = dex_file.GetClassData(dex_class_def);
1054 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1055 size_t num_static_fields = header.static_fields_size_;
1056 size_t num_ref = 0;
1057 size_t num_32 = 0;
1058 size_t num_64 = 0;
1059 if (num_static_fields != 0) {
1060 uint32_t last_idx = 0;
1061 for (size_t i = 0; i < num_static_fields; ++i) {
1062 DexFile::Field dex_field;
1063 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1064 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001065 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001066 char c = descriptor[0];
1067 if (c == 'L' || c == '[') {
1068 num_ref++;
1069 } else if (c == 'J' || c == 'D') {
1070 num_64++;
1071 } else {
1072 num_32++;
1073 }
1074 }
1075 }
1076
1077 // start with generic class data
1078 size_t size = sizeof(Class);
1079 // follow with reference fields which must be contiguous at start
1080 size += (num_ref * sizeof(uint32_t));
1081 // if there are 64-bit fields to add, make sure they are aligned
1082 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1083 if (num_32 != 0) {
1084 // use an available 32-bit field for padding
1085 num_32--;
1086 }
1087 size += sizeof(uint32_t); // either way, we are adding a word
1088 DCHECK_EQ(size, RoundUp(size, 8));
1089 }
1090 // tack on any 64-bit fields now that alignment is assured
1091 size += (num_64 * sizeof(uint64_t));
1092 // tack on any remaining 32-bit fields
1093 size += (num_32 * sizeof(uint32_t));
1094 return size;
1095}
1096
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001097void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001098 // Every kind of method should at least get an invoke stub from the oat_method.
1099 // non-abstract methods also get their code pointers.
1100 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001101 oat_method.LinkMethod(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001102
1103 if (method->IsAbstract()) {
1104 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1105 return;
1106 }
1107 if (method->IsNative()) {
1108 // unregistering restores the dlsym lookup stub
1109 method->UnregisterNative();
1110 return;
1111 }
1112}
1113
Brian Carlstromf615a612011-07-23 12:50:34 -07001114void ClassLinker::LoadClass(const DexFile& dex_file,
1115 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001116 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001117 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001118 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001119 CHECK(klass->GetDexCache() != NULL);
1120 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001121 const byte* class_data = dex_file.GetClassData(dex_class_def);
1122 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001123
Brian Carlstromf615a612011-07-23 12:50:34 -07001124 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001125 CHECK(descriptor != NULL);
1126
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001127 klass->SetClass(GetClassRoot(kJavaLangClass));
1128 if (klass->GetDescriptor() != NULL) {
1129 DCHECK(klass->GetDescriptor()->Equals(descriptor));
1130 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001131 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001132 if (klass->GetDescriptor() == NULL) {
1133 return;
1134 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001135 }
1136 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001137 // Make sure that none of our runtime-only flags are set.
1138 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001139 klass->SetAccessFlags(access_flags);
1140 klass->SetClassLoader(class_loader);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001141 DCHECK(klass->GetPrimitiveType() == Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001142 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001143
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001144 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001145
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001146 size_t num_static_fields = header.static_fields_size_;
1147 size_t num_instance_fields = header.instance_fields_size_;
1148 size_t num_direct_methods = header.direct_methods_size_;
1149 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001150
Jesse Wilson6384f642011-10-07 18:08:35 -04001151 const char* source_file = dex_file.dexGetSourceFile(dex_class_def);
1152 if (source_file != NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001153 String* source_file_string = intern_table_->InternStrong(source_file);
1154 if (source_file_string == NULL) {
1155 return;
1156 }
1157 klass->SetSourceFile(source_file_string);
Jesse Wilson6384f642011-10-07 18:08:35 -04001158 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001159
1160 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -07001161 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001162
1163 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001164 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001165 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001166 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001167 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001168 DexFile::Field dex_field;
1169 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001170 SirtRef<Field> sfield(AllocField());
1171 klass->SetStaticField(i, sfield.get());
Brian Carlstromf615a612011-07-23 12:50:34 -07001172 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001173 }
1174 }
1175
1176 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001177 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001178 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001179 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001180 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001181 DexFile::Field dex_field;
1182 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001183 SirtRef<Field> ifield(AllocField());
1184 klass->SetInstanceField(i, ifield.get());
Brian Carlstromf615a612011-07-23 12:50:34 -07001185 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001186 }
1187 }
1188
Brian Carlstromaded5f72011-10-07 17:15:04 -07001189 UniquePtr<const OatFile::OatClass> oat_class;
1190 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
1191 const OatFile* oat_file = FindOatFile(dex_file);
1192 if (oat_file != NULL) {
1193 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1194 if (oat_dex_file != NULL) {
1195 uint32_t class_def_index;
1196 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1197 CHECK(found) << descriptor;
1198 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001199 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001200 }
1201 }
1202 }
1203 size_t method_index = 0;
1204
Brian Carlstrom934486c2011-07-12 23:42:50 -07001205 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001206 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001207 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001208 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001209 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001210 for (size_t i = 0; i < num_direct_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001211 DexFile::Method dex_method;
1212 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001213 SirtRef<Method> method(AllocMethod());
1214 klass->SetDirectMethod(i, method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001215 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001216 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001217 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001218 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001219 }
1220 }
1221
1222 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001223 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001224 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001225 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001226 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001227 for (size_t i = 0; i < num_virtual_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001228 DexFile::Method dex_method;
1229 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001230 SirtRef<Method> method(AllocMethod());
1231 klass->SetVirtualMethod(i, method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001232 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001233 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001234 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001235 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001236 }
1237 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001238}
1239
Brian Carlstromf615a612011-07-23 12:50:34 -07001240void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1241 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001242 SirtRef<Class>& klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001243 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001244 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001245 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001246 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1247 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001248 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001249 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001250 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001251 }
1252 }
1253}
1254
Brian Carlstromf615a612011-07-23 12:50:34 -07001255void ClassLinker::LoadField(const DexFile& dex_file,
1256 const DexFile::Field& src,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001257 SirtRef<Class>& klass,
1258 SirtRef<Field>& dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001259 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001260 dst->SetDeclaringClass(klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001261 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1262 dst->SetTypeIdx(field_id.type_idx_);
1263 dst->SetAccessFlags(src.access_flags_);
1264
1265 // In order to access primitive types using GetTypeDuringLinking we need to
1266 // ensure they are resolved into the dex cache
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001267 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001268 if (descriptor[1] == '\0') {
1269 // only the descriptors of primitive types should be 1 character long
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001270 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001271 DCHECK(resolved->IsPrimitive());
1272 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001273}
1274
Brian Carlstromf615a612011-07-23 12:50:34 -07001275void ClassLinker::LoadMethod(const DexFile& dex_file,
1276 const DexFile::Method& src,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001277 SirtRef<Class>& klass,
1278 SirtRef<Method>& dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001279 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001280 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001281
Elliott Hughes80609252011-09-23 17:24:51 -07001282 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Elliott Hughes30646832011-10-13 16:59:46 -07001283 if (method_name == NULL) {
1284 return;
1285 }
Elliott Hughes80609252011-09-23 17:24:51 -07001286 dst->SetName(method_name);
1287 if (method_name->Equals("<init>")) {
1288 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1289 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001290
1291 int32_t utf16_length;
1292 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Elliott Hughes30646832011-10-13 16:59:46 -07001293 String* signature_string = intern_table_->InternStrong(utf16_length, signature.c_str());
1294 if (signature_string == NULL) {
1295 return;
1296 }
1297 dst->SetSignature(signature_string);
Elliott Hughes20cde902011-10-04 17:37:27 -07001298
1299 if (method_name->Equals("finalize") && signature == "()V") {
1300 /*
1301 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1302 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1303 * exclude it here.
1304 *
1305 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1306 */
1307 if (klass->GetClassLoader() != NULL ||
1308 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1309 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1310 klass->SetFinalizable();
1311 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001312 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001313
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001314 dst->SetProtoIdx(method_id.proto_idx_);
1315 dst->SetCodeItemOffset(src.code_off_);
1316 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Elliott Hughes30646832011-10-13 16:59:46 -07001317 String* shorty_string = intern_table_->InternStrong(shorty);
1318 dst->SetShorty(shorty_string);
1319 if (shorty_string == NULL) {
1320 return;
1321 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001322 dst->SetAccessFlags(src.access_flags_);
1323 dst->SetReturnTypeIdx(dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001324
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001325 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1326 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1327 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1328 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1329 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1330 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001331
Brian Carlstrom934486c2011-07-12 23:42:50 -07001332 // TODO: check for finalize method
1333
Brian Carlstromf615a612011-07-23 12:50:34 -07001334 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001335 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001336 dst->SetNumRegisters(code_item->registers_size_);
1337 dst->SetNumIns(code_item->ins_size_);
1338 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001339 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001340 uint16_t num_args = Method::NumArgRegisters(shorty);
1341 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001342 ++num_args;
1343 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001344 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001345 // TODO: native methods
1346 }
1347}
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);
1437 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001438 CHECK(primitive_class->GetDescriptor() != NULL);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001439 primitive_class->SetPrimitiveType(type);
1440 primitive_class->SetStatus(Class::kStatusInitialized);
1441 bool success = InsertClass(descriptor, primitive_class);
1442 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1443 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001444}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001445
Brian Carlstrombe977852011-07-19 14:54:54 -07001446// Create an array class (i.e. the class object for the array, not the
1447// array itself). "descriptor" looks like "[C" or "[[[[B" or
1448// "[Ljava/lang/String;".
1449//
1450// If "descriptor" refers to an array of primitives, look up the
1451// primitive type's internally-generated class object.
1452//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001453// "class_loader" is the class loader of the class that's referring to
1454// us. It's used to ensure that we're looking for the element type in
1455// the right context. It does NOT become the class loader for the
1456// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001457//
1458// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001459Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001460 const ClassLoader* class_loader) {
1461 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001462
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001463 // Identify the underlying component type
1464 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001465 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001466 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001467 return NULL;
1468 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001469
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001470 // See if the component type is already loaded. Array classes are
1471 // always associated with the class loader of their underlying
1472 // element type -- an array of Strings goes with the loader for
1473 // java/lang/String -- so we need to look for it there. (The
1474 // caller should have checked for the existence of the class
1475 // before calling here, but they did so with *their* class loader,
1476 // not the component type's loader.)
1477 //
1478 // If we find it, the caller adds "loader" to the class' initiating
1479 // loader list, which should prevent us from going through this again.
1480 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001481 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001482 // are the same, because our caller (FindClass) just did the
1483 // lookup. (Even if we get this wrong we still have correct behavior,
1484 // because we effectively do this lookup again when we add the new
1485 // class to the hash table --- necessary because of possible races with
1486 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001487 if (class_loader != component_type->GetClassLoader()) {
1488 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001489 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001490 return new_class;
1491 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001492 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001493
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001494 // Fill out the fields in the Class.
1495 //
1496 // It is possible to execute some methods against arrays, because
1497 // all arrays are subclasses of java_lang_Object_, so we need to set
1498 // up a vtable. We can just point at the one in java_lang_Object_.
1499 //
1500 // Array classes are simple enough that we don't need to do a full
1501 // link step.
1502
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001503 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001504 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001505 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001506 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001507 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001508 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001509 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001510 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001511 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001512 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001513 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001514 }
1515 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001516 if (new_class.get() == NULL) {
1517 new_class.reset(AllocClass(sizeof(Class)));
1518 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001519 return NULL;
1520 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001521 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001522 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001523 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001524 if (new_class->GetDescriptor() != NULL) {
1525 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1526 } else {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001527 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001528 if (new_class->GetDescriptor() == NULL) {
1529 return NULL;
1530 }
Brian Carlstrom693267a2011-09-06 09:25:34 -07001531 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001532 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001533 new_class->SetSuperClass(java_lang_Object);
1534 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001535 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001536 new_class->SetClassLoader(component_type->GetClassLoader());
1537 new_class->SetStatus(Class::kStatusInitialized);
1538 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001539 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001540
1541
1542 // All arrays have java/lang/Cloneable and java/io/Serializable as
1543 // interfaces. We need to set that up here, so that stuff like
1544 // "instanceof" works right.
1545 //
1546 // Note: The GC could run during the call to FindSystemClass,
1547 // so we need to make sure the class object is GC-valid while we're in
1548 // there. Do this by clearing the interface list so the GC will just
1549 // think that the entries are null.
1550
1551
1552 // Use the single, global copies of "interfaces" and "iftable"
1553 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001554 CHECK(array_interfaces_ != NULL);
1555 CHECK(array_iftable_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001556 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001557 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001558
1559 // Inherit access flags from the component type. Arrays can't be
1560 // used as a superclass or interface, so we want to add "final"
1561 // and remove "interface".
1562 //
1563 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001564 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001565 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001566 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1567 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001568
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001569 if (InsertClass(descriptor, new_class.get())) {
1570 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001571 }
1572 // Another thread must have loaded the class after we
1573 // started but before we finished. Abandon what we've
1574 // done.
1575 //
1576 // (Yes, this happens.)
1577
1578 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001579 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001580 DCHECK(other_class != NULL);
1581 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001582}
1583
1584Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001585 switch (Primitive::GetType(type)) {
1586 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001587 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001588 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001589 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001590 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001591 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001592 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001593 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001594 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001595 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001596 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001597 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001598 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001599 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001600 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001601 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001602 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001603 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001604 case Primitive::kPrimNot:
1605 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001606 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001607 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001608 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001609 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001610}
1611
Brian Carlstromaded5f72011-10-07 17:15:04 -07001612bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001613 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001614 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001615 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001616 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001617}
1618
Brian Carlstromaded5f72011-10-07 17:15:04 -07001619Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001620 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001621 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001622 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001623 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001624 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001625 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001626 return klass;
1627 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001628 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001629 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001630}
1631
jeffhao98eacac2011-09-14 16:11:53 -07001632void ClassLinker::VerifyClass(Class* klass) {
1633 if (klass->IsVerified()) {
1634 return;
1635 }
1636
1637 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001638 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001639
Ian Rogersd81871c2011-10-03 13:57:23 -07001640 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001641 klass->SetStatus(Class::kStatusVerified);
1642 } else {
1643 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001644 Thread* self = Thread::Current();
1645 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1646 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
1647 PrettyDescriptor(klass->GetDescriptor()).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001648 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001649 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001650 }
jeffhao98eacac2011-09-14 16:11:53 -07001651}
1652
Jesse Wilson95caa792011-10-12 18:14:17 -04001653Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers466bb252011-10-14 03:29:56 -07001654 ClassLoader* loader, ObjectArray<Method>* methods, ObjectArray<ObjectArray<Class> >* throws) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001655 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass)));
1656 CHECK(klass.get() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001657 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers466bb252011-10-14 03:29:56 -07001658 const char* descriptor = DotToDescriptor(name->ToModifiedUtf8().c_str()).c_str();;
1659 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Jesse Wilson95caa792011-10-12 18:14:17 -04001660 klass->SetAccessFlags(kAccPublic | kAccFinal);
1661 klass->SetClassLoader(loader);
Ian Rogers466bb252011-10-14 03:29:56 -07001662 klass->SetStatus(Class::kStatusInitialized); // no loading or initializing necessary
1663 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1664 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1665 klass->SetInterfaces(interfaces); // The interfaces are the array of interfaces specified
Jesse Wilson95caa792011-10-12 18:14:17 -04001666
Ian Rogers466bb252011-10-14 03:29:56 -07001667 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001668 klass->SetDirectMethods(AllocObjectArray<Method>(1));
1669 klass->SetDirectMethod(0, CreateProxyConstructor(klass));
1670
Ian Rogers466bb252011-10-14 03:29:56 -07001671 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001672 size_t num_virtual_methods = methods->GetLength();
1673 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1674 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001675 SirtRef<Method> prototype(methods->Get(i));
Jesse Wilson95caa792011-10-12 18:14:17 -04001676 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype, throws->Get(i)));
1677 }
Ian Rogers466bb252011-10-14 03:29:56 -07001678 // Link the virtual methods, creating vtable and iftables
Jesse Wilson95caa792011-10-12 18:14:17 -04001679 if (!LinkMethods(klass)) {
1680 DCHECK(Thread::Current()->IsExceptionPending());
1681 return NULL;
1682 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001683 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001684}
1685
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001686Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass) {
Ian Rogers466bb252011-10-14 03:29:56 -07001687 // Create constructor for Proxy that must initialize h
1688 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1689 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001690 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001691 Method* proxy_constructor = proxy_direct_methods->Get(2);
1692 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1693 // code_ too)
1694 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1695 // Make this constructor public and fix the class to be our Proxy version
1696 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001697 constructor->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001698 // Sanity checks
1699 CHECK(constructor->IsConstructor());
1700 CHECK(constructor->GetName()->Equals("<init>"));
1701 CHECK(constructor->GetSignature()->Equals("(Ljava/lang/reflect/InvocationHandler;)V"));
1702 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001703 return constructor;
1704}
1705
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001706Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype,
Ian Rogers466bb252011-10-14 03:29:56 -07001707 ObjectArray<Class>* throws) {
1708 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialise
1709 // as necessary
1710 Method* method = down_cast<Method*>(prototype->Clone());
1711
1712 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1713 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001714 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001715 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001716 method->SetExceptionTypes(throws);
1717
Ian Rogers466bb252011-10-14 03:29:56 -07001718 // At runtime the method looks like a reference and argument saving method, clone the code
1719 // related parameters from this method.
1720 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1721 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1722 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1723 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1724 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Jesse Wilson95caa792011-10-12 18:14:17 -04001725
Ian Rogers466bb252011-10-14 03:29:56 -07001726 // Basic sanity
1727 DCHECK(method->GetName()->Equals(prototype->GetName()));
1728 DCHECK(method->GetSignature()->Equals(prototype->GetSignature()));
1729 DCHECK(method->GetShorty()->Equals(prototype->GetShorty()));
1730
1731 // More complex sanity - via dex cache
1732 CHECK_EQ(method->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04001733
1734 return method;
1735}
1736
Brian Carlstrom25c33252011-09-18 15:58:35 -07001737bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001738 CHECK(klass->IsResolved() || klass->IsErroneous())
1739 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001740
Carl Shapirob5573532011-07-12 18:22:59 -07001741 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001742
Brian Carlstrom25c33252011-09-18 15:58:35 -07001743 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001744 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001745 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001746 ObjectLock lock(klass);
1747
Brian Carlstromd1422f82011-09-28 11:37:09 -07001748 if (klass->GetStatus() == Class::kStatusInitialized) {
1749 return true;
1750 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001751
Brian Carlstromd1422f82011-09-28 11:37:09 -07001752 if (klass->IsErroneous()) {
1753 ThrowEarlierClassFailure(klass);
1754 return false;
1755 }
1756
1757 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001758 VerifyClass(klass);
1759 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001760 return false;
1761 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001762 }
1763
Brian Carlstrom25c33252011-09-18 15:58:35 -07001764 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1765 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001766 // if the class has a <clinit> but we can't run it during compilation,
1767 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001768 return false;
1769 }
1770
Brian Carlstromd1422f82011-09-28 11:37:09 -07001771 // If the class is kStatusInitializing, either this thread is
1772 // initializing higher up the stack or another thread has beat us
1773 // to initializing and we need to wait. Either way, this
1774 // invocation of InitializeClass will not be responsible for
1775 // running <clinit> and will return.
1776 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001777 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001778 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001779 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001780 return true;
1781 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001782 // No. That's fine. Wait for another thread to finish initializing.
1783 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001784 }
1785
1786 if (!ValidateSuperClassDescriptors(klass)) {
1787 klass->SetStatus(Class::kStatusError);
1788 return false;
1789 }
1790
Brian Carlstromd1422f82011-09-28 11:37:09 -07001791 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001792
Elliott Hughesdcc24742011-09-07 14:02:44 -07001793 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001794 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795 }
1796
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001797 uint64_t t0 = NanoTime();
1798
Brian Carlstrom25c33252011-09-18 15:58:35 -07001799 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001800 return false;
1801 }
1802
1803 InitializeStaticFields(klass);
1804
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001805 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001806 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001807 }
1808
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001809 uint64_t t1 = NanoTime();
1810
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001811 {
1812 ObjectLock lock(klass);
1813
1814 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001815 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001816 klass->SetStatus(Class::kStatusError);
1817 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001818 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1819 RuntimeStats* thread_stats = self->GetStats();
1820 ++global_stats->class_init_count;
1821 ++thread_stats->class_init_count;
1822 global_stats->class_init_time_ns += (t1 - t0);
1823 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001824 klass->SetStatus(Class::kStatusInitialized);
1825 }
1826 lock.NotifyAll();
1827 }
1828
1829 return true;
1830}
1831
Brian Carlstromd1422f82011-09-28 11:37:09 -07001832bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1833 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001834 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001835 lock.Wait();
1836
1837 // When we wake up, repeat the test for init-in-progress. If
1838 // there's an exception pending (only possible if
1839 // "interruptShouldThrow" was set), bail out.
1840 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001841 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001842 klass->SetStatus(Class::kStatusError);
1843 return false;
1844 }
1845 // Spurious wakeup? Go back to waiting.
1846 if (klass->GetStatus() == Class::kStatusInitializing) {
1847 continue;
1848 }
1849 if (klass->IsErroneous()) {
1850 // The caller wants an exception, but it was thrown in a
1851 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001852 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
1853 PrettyDescriptor(klass->GetDescriptor()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001854 return false;
1855 }
1856 if (klass->IsInitialized()) {
1857 return true;
1858 }
1859 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1860 }
1861 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1862}
1863
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001864bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1865 if (klass->IsInterface()) {
1866 return true;
1867 }
1868 // begin with the methods local to the superclass
1869 if (klass->HasSuperClass() &&
1870 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1871 const Class* super = klass->GetSuperClass();
1872 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001873 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001874 if (method != super->GetVirtualMethod(i) &&
1875 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001876 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1877
1878 ThrowLinkageError("Class %s method %s resolves differently in superclass %s", PrettyDescriptor(klass->GetDescriptor()).c_str(), PrettyMethod(method).c_str(), PrettyDescriptor(super->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001879 return false;
1880 }
1881 }
1882 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001883 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1884 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1885 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001886 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1887 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001888 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001889 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001890 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001891 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1892
1893 ThrowLinkageError("Class %s method %s resolves differently in interface %s", PrettyDescriptor(method->GetDeclaringClass()->GetDescriptor()).c_str(), PrettyMethod(method).c_str(), PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001894 return false;
1895 }
1896 }
1897 }
1898 }
1899 return true;
1900}
1901
1902bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001903 const Class* klass1,
1904 const Class* klass2) {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001905 if (method->IsMiranda()) {
1906 return true;
1907 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001908 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001909 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001910 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001911 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001912 const char* descriptor = it->GetDescriptor();
1913 if (descriptor == NULL) {
1914 break;
1915 }
1916 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1917 // Found a non-primitive type.
1918 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1919 return false;
1920 }
1921 }
1922 }
1923 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001924 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001925 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001926 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001927 return false;
1928 }
1929 }
1930 return true;
1931}
1932
1933// Returns true if classes referenced by the descriptor are the
1934// same classes in klass1 as they are in klass2.
1935bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001936 const Class* klass1,
1937 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001938 CHECK(descriptor != NULL);
1939 CHECK(klass1 != NULL);
1940 CHECK(klass2 != NULL);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001941 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001942 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001943 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001944 // TODO: found2 == NULL
1945 // TODO: lookup found1 in initiating loader list
1946 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001947 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001948 if (found1 == found2) {
1949 return true;
1950 } else {
1951 return false;
1952 }
1953 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001954 return true;
1955}
1956
Brian Carlstrom25c33252011-09-18 15:58:35 -07001957bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001958 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001959 if (!klass->IsInterface() && klass->HasSuperClass()) {
1960 Class* super_class = klass->GetSuperClass();
1961 if (super_class->GetStatus() != Class::kStatusInitialized) {
1962 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001963 Thread* self = Thread::Current();
1964 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001965 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001966 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967 // TODO: check for a pending exception
1968 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001969 if (!can_run_clinit) {
1970 // Don't set status to error when we can't run <clinit>.
1971 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1972 klass->SetStatus(Class::kStatusVerified);
1973 return false;
1974 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001975 klass->SetStatus(Class::kStatusError);
1976 klass->NotifyAll();
1977 return false;
1978 }
1979 }
1980 }
1981 return true;
1982}
1983
Brian Carlstrom25c33252011-09-18 15:58:35 -07001984bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001985 CHECK(c != NULL);
1986 if (c->IsInitialized()) {
1987 return true;
1988 }
1989
Elliott Hughes5f791332011-09-15 17:45:30 -07001990 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07001991 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001992 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001993 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001994}
1995
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001996void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
1997 Class* c, std::map<int, Field*>& field_map) {
1998 const ClassLoader* cl = c->GetClassLoader();
1999 const byte* class_data = dex_file.GetClassData(dex_class_def);
2000 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
2001 uint32_t last_idx = 0;
2002 for (size_t i = 0; i < header.static_fields_size_; ++i) {
2003 DexFile::Field dex_field;
2004 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
2005 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
2006 }
2007}
2008
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002009void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002010 size_t num_static_fields = klass->NumStaticFields();
2011 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002012 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002013 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002014 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002015 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002016 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002017 return;
2018 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002019 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002020 const DexFile& dex_file = FindDexFile(dex_cache);
2021 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07002022 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002023
2024 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2025 std::map<int, Field*> field_map;
2026 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2027
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002028 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002029 if (addr == NULL) {
2030 // All this class' static fields have default values.
2031 return;
2032 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002033 size_t array_size = DecodeUnsignedLeb128(&addr);
2034 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002035 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002036 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002037 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002038 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07002039 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002040 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002041 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002042 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002043 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002044 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002045 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002046 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002047 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002048 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002049 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002050 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002051 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002052 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002053 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002054 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002055 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002056 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002057 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002058 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002059 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002060 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002061 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002062 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002063 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002064 break;
2065 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002066 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002067 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002068 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002069 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002070 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002071 break;
2072 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07002073 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002074 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002075 }
2076}
2077
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002078bool ClassLinker::LinkClass(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002079 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002080 if (!LinkSuperClass(klass)) {
2081 return false;
2082 }
2083 if (!LinkMethods(klass)) {
2084 return false;
2085 }
2086 if (!LinkInstanceFields(klass)) {
2087 return false;
2088 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002089 if (!LinkStaticFields(klass)) {
2090 return false;
2091 }
2092 CreateReferenceInstanceOffsets(klass);
2093 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002094 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2095 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002096 return true;
2097}
2098
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002099bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002100 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
2101 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002102 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002103 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002104 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002105 return false;
2106 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002107 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002108 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002109 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
2110 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002111 Class* interface = ResolveType(dex_file, idx, klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002112 klass->SetInterface(i, interface);
2113 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002114 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002115 return false;
2116 }
2117 // Verify
2118 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002119 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002120 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002121 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002122 PrettyDescriptor(interface->GetDescriptor()).c_str(),
2123 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002124 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002125 }
2126 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002127 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002128 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002129 return true;
2130}
2131
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002132bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002133 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002134 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002135 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002136 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002137 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002138 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002139 return false;
2140 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002141 return true;
2142 }
2143 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002144 ThrowLinkageError("No superclass defined for class %s",
2145 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002146 return false;
2147 }
2148 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002149 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002150 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002151 "Superclass %s of %s is %s",
2152 PrettyDescriptor(super->GetDescriptor()).c_str(),
2153 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002154 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002155 return false;
2156 }
2157 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002158 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002159 "Superclass %s is inaccessible by %s",
2160 PrettyDescriptor(super->GetDescriptor()).c_str(),
2161 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002162 return false;
2163 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002164
2165 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2166 if (super->IsFinalizable()) {
2167 klass->SetFinalizable();
2168 }
2169
Elliott Hughes2da50362011-10-10 16:57:08 -07002170 // Inherit reference flags (if any) from the superclass.
2171 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2172 if (reference_flags != 0) {
2173 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2174 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002175 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002176 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002177 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
2178 PrettyDescriptor(klass->GetDescriptor()).c_str());
2179 return false;
2180 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002181
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002182#ifndef NDEBUG
2183 // Ensure super classes are fully resolved prior to resolving fields..
2184 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002185 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002186 super = super->GetSuperClass();
2187 }
2188#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002189 return true;
2190}
2191
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002192// Populate the class vtable and itable. Compute return type indices.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002193bool ClassLinker::LinkMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194 if (klass->IsInterface()) {
2195 // No vtable.
2196 size_t count = klass->NumVirtualMethods();
2197 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002198 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002199 return false;
2200 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002201 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002202 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002203 }
jeffhaobdb76512011-09-07 11:43:16 -07002204 // Link interface method tables
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002205 return LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002206 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002207 // Link virtual and interface method tables
2208 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002209 }
2210 return true;
2211}
2212
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002213bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002214 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002215 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2216 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002217 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002218 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002219 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002220 // See if any of our virtual methods override the superclass.
2221 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002222 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002223 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002224 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002225 Method* super_method = vtable->Get(j);
Ian Rogers466bb252011-10-14 03:29:56 -07002226 if (local_method->HasSameNameAndSignature(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002227 // Verify
2228 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002229 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002230 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2231 local_method->GetName()->ToModifiedUtf8().c_str(),
2232 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002233 return false;
2234 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002235 vtable->Set(j, local_method);
2236 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002237 break;
2238 }
2239 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002240 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002241 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002242 vtable->Set(actual_count, local_method);
2243 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002244 actual_count += 1;
2245 }
2246 }
2247 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002248 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002249 return false;
2250 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002251 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002252 CHECK_LE(actual_count, max_count);
2253 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002254 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002255 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002256 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002257 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002258 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002259 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002260 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002261 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002262 return false;
2263 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002264 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002265 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002266 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2267 vtable->Set(i, virtual_method);
2268 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002269 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002270 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002271 }
2272 return true;
2273}
2274
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002275bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002276 size_t super_ifcount;
2277 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002278 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002279 } else {
2280 super_ifcount = 0;
2281 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002282 size_t ifcount = super_ifcount;
2283 ifcount += klass->NumInterfaces();
2284 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002285 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002286 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002287 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002288 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002289 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002290 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002291 return true;
2292 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002293 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002295 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2296 for (size_t i = 0; i < super_ifcount; i++) {
2297 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2298 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299 }
2300 // Flatten the interface inheritance hierarchy.
2301 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002302 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002303 Class* interface = klass->GetInterface(i);
2304 DCHECK(interface != NULL);
2305 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002306 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002307 "Class %s implements non-interface class %s",
2308 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2309 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002310 return false;
2311 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002312 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002313 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002314 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002315 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2316 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002317 }
2318 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002319 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002320 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002321
2322 // If we're an interface, we don't need the vtable pointers, so we're done.
2323 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002324 return true;
2325 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002326 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002327 for (size_t i = 0; i < ifcount; ++i) {
2328 InterfaceEntry* interface_entry = iftable->Get(i);
2329 Class* interface = interface_entry->GetInterface();
2330 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2331 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002332 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002333 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2334 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002335 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002336 // For each method listed in the interface's method list, find the
2337 // matching method in our class's method list. We want to favor the
2338 // subclass over the superclass, which just requires walking
2339 // back from the end of the vtable. (This only matters if the
2340 // superclass defines a private method and this class redefines
2341 // it -- otherwise it would use the same vtable slot. In .dex files
2342 // those don't end up in the virtual method table, so it shouldn't
2343 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002344 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2345 Method* vtable_method = vtable->Get(k);
Ian Rogers466bb252011-10-14 03:29:56 -07002346 if (interface_method->HasSameNameAndSignature(vtable_method)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002347 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002348 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002349 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002350 return false;
2351 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002352 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002353 break;
2354 }
2355 }
2356 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002357 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002358 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers466bb252011-10-14 03:29:56 -07002359 if (miranda_list[mir]->HasSameNameAndSignature(interface_method)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002360 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002361 break;
2362 }
2363 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002364 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002365 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002366 miranda_method.reset(AllocMethod());
2367 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2368 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002369 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002370 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002371 }
2372 }
2373 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002374 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002375 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002376 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002377 klass->SetVirtualMethods((old_method_count == 0)
2378 ? AllocObjectArray<Method>(new_method_count)
2379 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002380
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002381 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2382 CHECK(vtable != NULL);
2383 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002384 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002385 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002386 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002387 Method* method = miranda_list[i];
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002388 method->SetDeclaringClass(klass.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07002389 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2390 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2391 klass->SetVirtualMethod(old_method_count + i, method);
2392 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002393 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002394 // TODO: do not assign to the vtable field until it is fully constructed.
2395 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002396 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002397
2398 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2399 for (int i = 0; i < vtable->GetLength(); ++i) {
2400 CHECK(vtable->Get(i) != NULL);
2401 }
2402
2403// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2404
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002405 return true;
2406}
2407
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002408bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2409 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002410 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002411}
2412
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002413bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2414 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002415 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002416 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002417 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002418 return success;
2419}
2420
Brian Carlstromdbc05252011-09-09 01:59:59 -07002421struct LinkFieldsComparator {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002422 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002423 // First come reference fields, then 64-bit, and finally 32-bit
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002424 Primitive::Type type1 = field1->GetPrimitiveType();
2425 Primitive::Type type2 = field2->GetPrimitiveType();
2426 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2427 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2428 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2429 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002430 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2431 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2432 if (order1 != order2) {
2433 return order1 < order2;
2434 }
2435
2436 // same basic group? then sort by string.
2437 std::string name1 = field1->GetName()->ToModifiedUtf8();
2438 std::string name2 = field2->GetName()->ToModifiedUtf8();
2439 return name1 < name2;
2440 }
2441};
2442
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002443bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002444 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002445 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002446
2447 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002448 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002449
2450 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002451 size_t size;
2452 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002453 if (is_static) {
2454 size = klass->GetClassSize();
2455 field_offset = Class::FieldsOffset();
2456 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002457 Class* super_class = klass->GetSuperClass();
2458 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002459 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002460 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002461 }
2462 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002463 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002464
Brian Carlstromdbc05252011-09-09 01:59:59 -07002465 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002466
Brian Carlstromdbc05252011-09-09 01:59:59 -07002467 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002468 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002469 std::deque<Field*> grouped_and_sorted_fields;
2470 for (size_t i = 0; i < num_fields; i++) {
2471 grouped_and_sorted_fields.push_back(fields->Get(i));
2472 }
2473 std::sort(grouped_and_sorted_fields.begin(),
2474 grouped_and_sorted_fields.end(),
2475 LinkFieldsComparator());
2476
2477 // References should be at the front.
2478 size_t current_field = 0;
2479 size_t num_reference_fields = 0;
2480 for (; current_field < num_fields; current_field++) {
2481 Field* field = grouped_and_sorted_fields.front();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002482 Primitive::Type type = field->GetPrimitiveType();
2483 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002484 if (isPrimitive) {
2485 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002486 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002487 grouped_and_sorted_fields.pop_front();
2488 num_reference_fields++;
2489 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002490 field->SetOffset(field_offset);
2491 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002492 }
2493
2494 // Now we want to pack all of the double-wide fields together. If
2495 // we're not aligned, though, we want to shuffle one 32-bit field
2496 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002497 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002498 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2499 Field* field = grouped_and_sorted_fields[i];
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002500 Primitive::Type type = field->GetPrimitiveType();
2501 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2502 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002503 continue;
2504 }
2505 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002506 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002507 // drop the consumed field
2508 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2509 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002510 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002511 // whether we found a 32-bit field for padding or not, we advance
2512 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002513 }
2514
2515 // Alignment is good, shuffle any double-wide fields forward, and
2516 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002517 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002518 while (!grouped_and_sorted_fields.empty()) {
2519 Field* field = grouped_and_sorted_fields.front();
2520 grouped_and_sorted_fields.pop_front();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002521 Primitive::Type type = field->GetPrimitiveType();
2522 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002523 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002524 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002525 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002526 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002527 ? sizeof(uint64_t)
2528 : sizeof(uint32_t)));
2529 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002530 }
2531
Elliott Hughesadb460d2011-10-05 17:02:34 -07002532 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002533 if (!is_static && klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002534 // We know there are no non-reference fields in the Reference classes, and we know
2535 // that 'referent' is alphabetically last, so this is easy...
2536 CHECK_EQ(num_reference_fields, num_fields);
2537 CHECK(fields->Get(num_fields - 1)->GetName()->Equals("referent"));
2538 --num_reference_fields;
2539 }
2540
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002541#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002542 // Make sure that all reference fields appear before
2543 // non-reference fields, and all double-wide fields are aligned.
2544 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002545 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002546 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002547 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002548 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002549 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002550 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002551 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2552 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002553 Primitive::Type type = field->GetPrimitiveType();
2554 bool is_primitive = type != Primitive::kPrimNot;
Elliott Hughesadb460d2011-10-05 17:02:34 -07002555 if (klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;") && field->GetName()->Equals("referent")) {
2556 is_primitive = true; // We lied above, so we have to expect a lie here.
2557 }
2558 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002559 if (!seen_non_ref) {
2560 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002561 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002562 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002563 } else {
2564 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002565 }
2566 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002567 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002568 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002569 }
2570#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002571 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002572 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002573 if (is_static) {
2574 klass->SetNumReferenceStaticFields(num_reference_fields);
2575 klass->SetClassSize(size);
2576 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002578 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002579 klass->SetObjectSize(size);
2580 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002581 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002582 return true;
2583}
2584
2585// Set the bitmap of reference offsets, refOffsets, from the ifields
2586// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002587void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002588 uint32_t reference_offsets = 0;
2589 Class* super_class = klass->GetSuperClass();
2590 if (super_class != NULL) {
2591 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002592 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002593 if (reference_offsets == CLASS_WALK_SUPER) {
2594 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002595 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002596 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002598 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002599}
2600
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002601void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002602 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002603}
2604
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002605void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002606 uint32_t reference_offsets) {
2607 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002608 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2609 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002610 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002611 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002612 // All of the fields that contain object references are guaranteed
2613 // to be at the beginning of the fields list.
2614 for (size_t i = 0; i < num_reference_fields; ++i) {
2615 // Note that byte_offset is the offset from the beginning of
2616 // object, not the offset into instance data
2617 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002618 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002619 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2620 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2621 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002622 CHECK_NE(new_bit, 0U);
2623 reference_offsets |= new_bit;
2624 } else {
2625 reference_offsets = CLASS_WALK_SUPER;
2626 break;
2627 }
2628 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002629 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002630 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002631 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002632 } else {
2633 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002634 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002635}
2636
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002637String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002638 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002639 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002640 if (resolved != NULL) {
2641 return resolved;
2642 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002643 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2644 int32_t utf16_length = dex_file.GetStringLength(string_id);
2645 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002646 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002647 dex_cache->SetResolvedString(string_idx, string);
2648 return string;
2649}
2650
2651Class* ClassLinker::ResolveType(const DexFile& dex_file,
2652 uint32_t type_idx,
2653 DexCache* dex_cache,
2654 const ClassLoader* class_loader) {
2655 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002656 if (resolved == NULL) {
2657 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002658 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002659 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002660 Class* check = resolved;
2661 while (check->IsArrayClass()) {
2662 check = check->GetComponentType();
2663 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002664 if (dex_cache != check->GetDexCache()) {
2665 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002666 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002667 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002668 resolved = NULL;
2669 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002670 }
2671 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002672 if (resolved != NULL) {
2673 dex_cache->SetResolvedType(type_idx, resolved);
2674 } else {
2675 DCHECK(Thread::Current()->IsExceptionPending());
2676 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002677 }
2678 return resolved;
2679}
2680
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002681Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2682 uint32_t method_idx,
2683 DexCache* dex_cache,
2684 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002685 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002686 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2687 if (resolved != NULL) {
2688 return resolved;
2689 }
2690 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2691 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2692 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002693 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002694 return NULL;
2695 }
2696
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002697 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002698 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002699 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002700 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002701 } else if (klass->IsInterface()) {
2702 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002703 } else {
2704 resolved = klass->FindVirtualMethod(name, signature);
2705 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002706 if (resolved != NULL) {
2707 dex_cache->SetResolvedMethod(method_idx, resolved);
2708 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002709 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002710 }
2711 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002712}
2713
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002714Field* ClassLinker::ResolveField(const DexFile& dex_file,
2715 uint32_t field_idx,
2716 DexCache* dex_cache,
2717 const ClassLoader* class_loader,
2718 bool is_static) {
2719 Field* resolved = dex_cache->GetResolvedField(field_idx);
2720 if (resolved != NULL) {
2721 return resolved;
2722 }
2723 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2724 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2725 if (klass == NULL) {
2726 return NULL;
2727 }
2728
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002729 const char* name = dex_file.GetFieldName(field_id);
2730 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002731 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002732 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002733 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002734 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002735 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002736 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002737 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002738 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002739 DCHECK(Thread::Current()->IsExceptionPending())
2740 << PrettyClass(klass) << " " << name << " " << type << " " << is_static;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002741 }
2742 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002743}
2744
Ian Rogersad25ac52011-10-04 19:13:33 -07002745const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2746 Class* declaring_class = referrer->GetDeclaringClass();
2747 DexCache* dex_cache = declaring_class->GetDexCache();
2748 const DexFile& dex_file = FindDexFile(dex_cache);
2749 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2750 return dex_file.GetShorty(method_id.proto_idx_);
2751}
2752
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002753void ClassLinker::DumpAllClasses(int flags) const {
2754 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2755 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2756 std::vector<Class*> all_classes;
2757 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002758 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002759 typedef Table::const_iterator It; // TODO: C++0x auto
2760 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2761 all_classes.push_back(it->second);
2762 }
2763 }
2764
2765 for (size_t i = 0; i < all_classes.size(); ++i) {
2766 all_classes[i]->DumpClass(std::cerr, flags);
2767 }
2768}
2769
Elliott Hughese27955c2011-08-26 15:21:24 -07002770size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002771 MutexLock mu(classes_lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002772 return classes_.size();
2773}
2774
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002775pid_t ClassLinker::GetClassesLockOwner() {
2776 return classes_lock_.GetOwner();
2777}
2778
2779pid_t ClassLinker::GetDexLockOwner() {
2780 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002781}
2782
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002783} // namespace art