blob: 8f4029a354ea1009c079e1784411ed0dd0b45ca3 [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());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700217 if (dex_file == NULL) {
218 LOG(WARNING) << "Failed to open dex file " << parsed[i];
219 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700220 class_path_vector.push_back(dex_file);
221 }
222 }
223}
224
225void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700226 const Runtime* runtime = Runtime::Current();
227 if (runtime->IsVerboseStartup()) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700228 LOG(INFO) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700229 }
230
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700231 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700232
Elliott Hughes30646832011-10-13 16:59:46 -0700233 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700234 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
235 CHECK(java_lang_Class.get() != NULL);
236 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700237 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700238 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700239
Elliott Hughes418d20f2011-09-22 14:00:39 -0700240 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700241 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
242 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700243
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700244 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700245 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
246 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700247 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700248 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700249 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700250
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700251 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700252 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
253 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700254
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700255 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700256 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700257
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700258 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700259 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
260 char_array_class->SetComponentType(char_class.get());
261 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700262
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700263 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700264 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
265 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700266 java_lang_String->SetObjectSize(sizeof(String));
267 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400268
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700269 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700270 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
271 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700272 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700273 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
274 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
275 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700276
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700277 // Create storage for root classes, save away our work so far (requires
278 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700279 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700280 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700281 SetClassRoot(kJavaLangClass, java_lang_Class.get());
282 SetClassRoot(kJavaLangObject, java_lang_Object.get());
283 SetClassRoot(kClassArrayClass, class_array_class.get());
284 SetClassRoot(kObjectArrayClass, object_array_class.get());
285 SetClassRoot(kCharArrayClass, char_array_class.get());
286 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700287
288 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700289 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
290 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
291 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
292 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
293 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
294 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
295 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
296 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700297
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700299 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700300 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700301
302 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700303 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700304 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700305 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700306 IntArray::SetArrayClass(int_array_class.get());
307 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700308
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700309 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700310
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700311 // setup boot_class_path_ and register class_path now that we can
312 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700313 std::vector<const DexFile*> boot_class_path_vector;
314 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700315 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700316 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
317 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700318 CHECK(dex_file != NULL);
319 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700320 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700321
Elliott Hughes80609252011-09-23 17:24:51 -0700322 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700323 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Elliott Hughes80609252011-09-23 17:24:51 -0700324 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700325 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700326 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700327 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700328 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
329
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
331 CHECK(java_lang_reflect_Field.get() != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700332 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700333 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700334 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700335 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700336 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700337
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700338 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Elliott Hughes80609252011-09-23 17:24:51 -0700339 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700340 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700341 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700342 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700343 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700344 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700345
346 // now we can use FindSystemClass
347
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700348 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700349 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700351
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700352 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700353 java_lang_Object->SetStatus(Class::kStatusNotReady);
354 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700355 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700356 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
357 java_lang_String->SetStatus(Class::kStatusNotReady);
358 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700359 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700360 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
361
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700362 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
364 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
365
366 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
367 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
368
369 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700370 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700371
372 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
373 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
374
375 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700376 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700377
378 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
379 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
380
381 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
382 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
383
384 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
385 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
386
Elliott Hughes418d20f2011-09-22 14:00:39 -0700387 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700388 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700389
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700390 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700391 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392
393 // Setup the single, global copies of "interfaces" and "iftable"
394 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
395 CHECK(java_lang_Cloneable != NULL);
396 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
397 CHECK(java_io_Serializable != NULL);
398 CHECK(array_interfaces_ != NULL);
399 array_interfaces_->Set(0, java_lang_Cloneable);
400 array_interfaces_->Set(1, java_io_Serializable);
401 // We assume that Cloneable/Serializable don't have superinterfaces --
402 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700403 // supers as well.
404 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
405 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406
Elliott Hughes418d20f2011-09-22 14:00:39 -0700407 // Sanity check Class[] and Object[]'s interfaces
408 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
409 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700410 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
411 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700412
Elliott Hughes80609252011-09-23 17:24:51 -0700413 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700414 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700415 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700416 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700417
Elliott Hughes80609252011-09-23 17:24:51 -0700418 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
419 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700420 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700421
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700423 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700424 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700425
426 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700427 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700428 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700429
Ian Rogers466bb252011-10-14 03:29:56 -0700430 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
431
432 // Create java.lang.reflect.Proxy root
433 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
434 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
435
Brian Carlstrom1f870082011-08-23 16:02:11 -0700436 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700437 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
438 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700439 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440 java_lang_ref_FinalizerReference->SetAccessFlags(
441 java_lang_ref_FinalizerReference->GetAccessFlags() |
442 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700443 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700444 java_lang_ref_PhantomReference->SetAccessFlags(
445 java_lang_ref_PhantomReference->GetAccessFlags() |
446 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700447 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700448 java_lang_ref_SoftReference->SetAccessFlags(
449 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700450 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700451 java_lang_ref_WeakReference->SetAccessFlags(
452 java_lang_ref_WeakReference->GetAccessFlags() |
453 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700454
Brian Carlstromaded5f72011-10-07 17:15:04 -0700455 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700456 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700457 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700458 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
459
460 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
461 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
462 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
463
464 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
465 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
466 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
467 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
468
469 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700470 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
471 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700472 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700473
Brian Carlstroma663ea52011-08-19 23:33:41 -0700474 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700475
476 if (runtime->IsVerboseStartup()) {
477 LOG(INFO) << "ClassLinker::InitFrom exiting";
478 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700479}
480
481void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700482 const Runtime* runtime = Runtime::Current();
483 if (runtime->IsVerboseStartup()) {
484 LOG(INFO) << "ClassLinker::FinishInit entering";
485 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700486
487 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700488 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700489 // as the types of the field can't be resolved prior to the runtime being
490 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700491 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700492 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700493 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
494
Elliott Hughesadb460d2011-10-05 17:02:34 -0700495 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
496
Brian Carlstrom16192862011-09-12 17:50:06 -0700497 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
498 CHECK(pendingNext->GetName()->Equals("pendingNext"));
499 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
500
501 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
502 CHECK(queue->GetName()->Equals("queue"));
Elliott Hughesadb460d2011-10-05 17:02:34 -0700503 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue), java_lang_ref_ReferenceQueue);
Brian Carlstrom16192862011-09-12 17:50:06 -0700504
505 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
506 CHECK(queueNext->GetName()->Equals("queueNext"));
507 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
508
509 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
510 CHECK(referent->GetName()->Equals("referent"));
511 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
512
513 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
514 CHECK(zombie->GetName()->Equals("zombie"));
515 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
516
517 Heap::SetReferenceOffsets(referent->GetOffset(),
518 queue->GetOffset(),
519 queueNext->GetOffset(),
520 pendingNext->GetOffset(),
521 zombie->GetOffset());
522
Brian Carlstroma663ea52011-08-19 23:33:41 -0700523 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700524 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700525 ClassRoot class_root = static_cast<ClassRoot>(i);
526 Class* klass = GetClassRoot(class_root);
527 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700528 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700529 // note SetClassRoot does additional validation.
530 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700531 }
532
Elliott Hughes92f14b22011-10-06 12:29:54 -0700533 CHECK(array_iftable_ != NULL);
534 CHECK(array_interfaces_ != NULL);
535
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700536 // disable the slow paths in FindClass and CreatePrimitiveClass now
537 // that Object, Class, and Object[] are setup
538 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700539
540 if (runtime->IsVerboseStartup()) {
541 LOG(INFO) << "ClassLinker::FinishInit exiting";
542 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700543}
544
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700545void ClassLinker::RunRootClinits() {
546 Thread* self = Thread::Current();
547 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
548 Class* c = GetClassRoot(ClassRoot(i));
549 if (!c->IsArrayClass() && !c->IsPrimitive()) {
550 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700551 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700552 }
553 }
554}
555
jeffhao262bf462011-10-20 18:36:32 -0700556const OatFile* ClassLinker::GenerateOatFile(const std::string& filename) {
557 std::string oat_filename(GetArtCacheFilenameOrDie(OatFile::DexFilenameToOatFilename(filename)));
558
559 // fork and exec dex2oat
560 pid_t pid = fork();
561 if (pid == 0) {
562 std::string boot_image_option("--boot-image=");
563 boot_image_option += Heap::GetSpaces()[0]->GetImageFilename();
564
565 std::string dex_file_option("--dex-file=");
566 dex_file_option += filename;
567
568 std::string oat_file_option("--oat=");
569 oat_file_option += oat_filename;
570
571 execl("/system/bin/dex2oatd",
572 "/system/bin/dex2oatd",
jeffhao5d840402011-10-24 17:09:45 -0700573 "--runtime-arg", "-Xms64m",
574 "--runtime-arg", "-Xmx64m",
jeffhao262bf462011-10-20 18:36:32 -0700575 boot_image_option.c_str(),
576 dex_file_option.c_str(),
577 oat_file_option.c_str(),
578 NULL);
579
580 PLOG(FATAL) << "execl(dex2oatd) failed";
581 return NULL;
582 } else {
583 // wait for dex2oat to finish
584 int status;
585 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
586 if (got_pid != pid) {
587 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
588 return NULL;
589 }
590 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
591 LOG(ERROR) << "dex2oatd failed with dex-file=" << filename;
592 return NULL;
593 }
594 }
595 return OatFile::Open(oat_filename, "", NULL);
596}
597
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700598OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700599 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700600 const Runtime* runtime = Runtime::Current();
601 if (runtime->IsVerboseStartup()) {
602 LOG(INFO) << "ClassLinker::OpenOat entering";
603 }
604 const ImageHeader& image_header = space->GetImageHeader();
605 String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
606 std::string oat_filename;
607 oat_filename += runtime->GetHostPrefix();
608 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700609 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700610 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700611 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700612 return NULL;
613 }
614 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
615 uint32_t image_oat_checksum = image_header.GetOatChecksum();
616 if (oat_checksum != image_oat_checksum) {
617 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
618 << " to expected oat checksum " << std::hex << oat_checksum
619 << " in image";
620 return NULL;
621 }
622 oat_files_.push_back(oat_file);
623 if (runtime->IsVerboseStartup()) {
624 LOG(INFO) << "ClassLinker::OpenOat exiting";
625 }
626 return oat_file;
627}
628
Brian Carlstromaded5f72011-10-07 17:15:04 -0700629const OatFile* ClassLinker::FindOatFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700630 MutexLock mu(dex_lock_);
jeffhao262bf462011-10-20 18:36:32 -0700631 const OatFile* oat_file = FindOatFile(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
632 if (oat_file != NULL) {
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700633 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
634 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
635 return oat_file;
636 }
637 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
638 << " is older than " << dex_file.GetLocation() << " --- regenerating";
639 // Fall through...
jeffhao262bf462011-10-20 18:36:32 -0700640 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700641 // Generate oat file if it wasn't found or was obsolete.
jeffhao262bf462011-10-20 18:36:32 -0700642 oat_file = GenerateOatFile(dex_file.GetLocation());
643 if (oat_file == NULL) {
644 LOG(ERROR) << "Failed to generate oat file from dex file " << dex_file.GetLocation();
645 return NULL;
646 }
647 oat_files_.push_back(oat_file);
648 return oat_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700649}
650
Brian Carlstromfad71432011-10-16 20:25:10 -0700651const OatFile* ClassLinker::FindOpenedOatFile(const std::string& location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700652 for (size_t i = 0; i < oat_files_.size(); i++) {
653 const OatFile* oat_file = oat_files_[i];
654 DCHECK(oat_file != NULL);
655 if (oat_file->GetLocation() == location) {
656 return oat_file;
657 }
658 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700659 return NULL;
660}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700661
Brian Carlstromfad71432011-10-16 20:25:10 -0700662const OatFile* ClassLinker::FindOatFile(const std::string& location) {
663 const OatFile* oat_file = FindOpenedOatFile(location);
664 if (oat_file != NULL) {
665 return oat_file;
666 }
667
668 oat_file = OatFile::Open(location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700669 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700670 if (location.empty() || location[0] != '/') {
671 LOG(ERROR) << "Failed to open oat file from " << location;
672 return NULL;
673 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700674
Brian Carlstroma9f19782011-10-13 00:14:47 -0700675 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
jeffhao262bf462011-10-20 18:36:32 -0700676 std::string cache_location = GetArtCacheFilenameOrDie(location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700677 oat_file = FindOpenedOatFile(cache_location);
678 if (oat_file != NULL) {
679 return oat_file;
680 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700681 oat_file = OatFile::Open(cache_location, "", NULL);
682 if (oat_file == NULL) {
jeffhao262bf462011-10-20 18:36:32 -0700683 LOG(INFO) << "Failed to open oat file from " << location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700684 return NULL;
685 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700686 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700687
688 CHECK(oat_file != NULL) << location;
689 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700690 return oat_file;
691}
692
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700693void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700694 const Runtime* runtime = Runtime::Current();
695 if (runtime->IsVerboseStartup()) {
696 LOG(INFO) << "ClassLinker::InitFromImage entering";
697 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700698 CHECK(!init_done_);
699
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700700 const std::vector<Space*>& spaces = Heap::GetSpaces();
701 for (size_t i = 0; i < spaces.size(); i++) {
702 Space* space = spaces[i] ;
703 if (space->IsImageSpace()) {
704 OatFile* oat_file = OpenOat(space);
705 CHECK(oat_file != NULL) << "Failed to open oat file for image";
706 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
707 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
708
709 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
710 static_cast<uint32_t>(dex_caches->GetLength()));
711 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700712 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700713 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
714
715 std::string dex_filename;
716 dex_filename += runtime->GetHostPrefix();
717 dex_filename += dex_file_location;
718 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
719 if (dex_file == NULL) {
720 LOG(FATAL) << "Failed to open dex file " << dex_filename
721 << " referenced from oat file as " << dex_file_location;
722 }
723
Brian Carlstromaded5f72011-10-07 17:15:04 -0700724 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
725 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700726
Brian Carlstromdf143242011-10-10 18:05:34 -0700727 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700728 }
729 }
730 }
731
Brian Carlstroma663ea52011-08-19 23:33:41 -0700732 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
733 DCHECK(heap_bitmap != NULL);
734
Brian Carlstroma663ea52011-08-19 23:33:41 -0700735 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700736 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700737
738 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700739 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
740 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700741
Elliott Hughes92f14b22011-10-06 12:29:54 -0700742 // reinit array_interfaces_ and array_iftable_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700743 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
744 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700745 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
746 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700747
Brian Carlstroma663ea52011-08-19 23:33:41 -0700748 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700749 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700750 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700751 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
752 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
753 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
754 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
755 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
756 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
757 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
758 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700759 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700760 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700761
762 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700763
764 if (runtime->IsVerboseStartup()) {
765 LOG(INFO) << "ClassLinker::InitFromImage exiting";
766 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700767}
768
Brian Carlstrom78128a62011-09-15 17:21:19 -0700769void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700770 DCHECK(obj != NULL);
771 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700772 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700773
Brian Carlstromc74255f2011-09-11 22:47:39 -0700774 if (obj->IsString()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700775 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700776 return;
777 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700778 if (obj->IsClass()) {
779 // restore class to ClassLinker::classes_ table
780 Class* klass = obj->AsClass();
781 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
782 class_linker->InsertClass(descriptor, klass);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700783 return;
784 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700785}
786
787// Keep in sync with InitCallback. Anything we visit, we need to
788// reinit references to when reinitializing a ClassLinker from a
789// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700790void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
791 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700792
793 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700794 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700795 }
796
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700797 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700798 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700799 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700800 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700801 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700802 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700803 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700804
Elliott Hughes410c0c82011-09-01 17:58:25 -0700805 visitor(array_interfaces_, arg);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700806 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700807}
808
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700809ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700810 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700811 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700812 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700813 BooleanArray::ResetArrayClass();
814 ByteArray::ResetArrayClass();
815 CharArray::ResetArrayClass();
816 DoubleArray::ResetArrayClass();
817 FloatArray::ResetArrayClass();
818 IntArray::ResetArrayClass();
819 LongArray::ResetArrayClass();
820 ShortArray::ResetArrayClass();
821 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700822 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700823 STLDeleteElements(&boot_class_path_);
824 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700825}
826
827DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700828 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
829 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700830 return NULL;
831 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700832 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
833 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700834 return NULL;
835 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700836 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
837 if (strings.get() == NULL) {
838 return NULL;
839 }
840 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
841 if (types.get() == NULL) {
842 return NULL;
843 }
844 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
845 if (methods.get() == NULL) {
846 return NULL;
847 }
848 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
849 if (fields.get() == NULL) {
850 return NULL;
851 }
852 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
853 if (code_and_direct_methods.get() == NULL) {
854 return NULL;
855 }
856 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
857 if (initialized_static_storage.get() == NULL) {
858 return NULL;
859 }
860
861 dex_cache->Init(location.get(),
862 strings.get(),
863 types.get(),
864 methods.get(),
865 fields.get(),
866 code_and_direct_methods.get(),
867 initialized_static_storage.get());
868 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700869}
870
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700871CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
872 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700873}
874
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700875InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
876 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700877 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
878 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700879 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700880 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700881}
882
Brian Carlstrom4873d462011-08-21 15:23:39 -0700883Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
884 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700885 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700886 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700887 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700888 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700889}
890
Brian Carlstrom4873d462011-08-21 15:23:39 -0700891Class* ClassLinker::AllocClass(size_t class_size) {
892 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700893}
894
Jesse Wilson35baaab2011-08-10 16:18:03 -0400895Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700896 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700897}
898
899Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700900 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700901}
902
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700903ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
904 return ObjectArray<StackTraceElement>::Alloc(
905 GetClassRoot(kJavaLangStackTraceElementArrayClass),
906 length);
907}
908
Brian Carlstromaded5f72011-10-07 17:15:04 -0700909Class* EnsureResolved(Class* klass) {
910 DCHECK(klass != NULL);
911 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700912 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700913 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700914 ObjectLock lock(klass);
915 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700916 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700917 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700918 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700919 return NULL;
920 }
921 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700922 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700923 lock.Wait();
924 }
925 }
926 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700927 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700928 return NULL;
929 }
930 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700931 CHECK(klass->IsResolved()) << PrettyClass(klass);
932 CHECK(!self->IsExceptionPending())
933 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
934 return klass;
935}
936
937Class* ClassLinker::FindClass(const std::string& descriptor,
938 const ClassLoader* class_loader) {
939 CHECK_NE(descriptor.size(), 0U);
940 Thread* self = Thread::Current();
941 DCHECK(self != NULL);
942 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
943 // Find the class in the loaded classes table.
944 Class* klass = LookupClass(descriptor, class_loader);
945 if (klass != NULL) {
946 return EnsureResolved(klass);
947 }
948 if (descriptor.size() == 1) {
949 // only the descriptors of primitive types should be 1 character long
950 return FindPrimitiveClass(descriptor[0]);
951 }
952 // Class is not yet loaded.
953 if (descriptor[0] == '[') {
954 return CreateArrayClass(descriptor, class_loader);
955 }
956 if (class_loader == NULL) {
957 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
958 if (pair.second == NULL) {
959 std::string name(PrintableString(descriptor));
960 ThrowNoClassDefFoundError("Class %s not found in boot class loader", name.c_str());
961 return NULL;
962 }
963 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
964 }
965
966 if (ClassLoader::UseCompileTimeClassPath()) {
967 const std::vector<const DexFile*>& class_path
968 = ClassLoader::GetCompileTimeClassPath(class_loader);
969 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
970 if (pair.second == NULL) {
971 return FindSystemClass(descriptor);
972 }
973 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
974 }
975
976 std::string class_name_string = DescriptorToDot(descriptor);
977 ScopedThreadStateChange(self, Thread::kNative);
978 JNIEnv* env = self->GetJniEnv();
Brian Carlstromdf143242011-10-10 18:05:34 -0700979 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
980 CHECK(c.get() != NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700981 // TODO: cache method?
Brian Carlstromdf143242011-10-10 18:05:34 -0700982 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700983 CHECK(mid != NULL);
Brian Carlstromdf143242011-10-10 18:05:34 -0700984 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -0700985 if (class_name_object.get() == NULL) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700986 return NULL;
987 }
Brian Carlstromdf143242011-10-10 18:05:34 -0700988 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
989 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
990 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -0700991}
992
993Class* ClassLinker::DefineClass(const std::string& descriptor,
994 const ClassLoader* class_loader,
995 const DexFile& dex_file,
996 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700997 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700998 // Load the class from the dex file.
999 if (!init_done_) {
1000 // finish up init of hand crafted class_roots_
1001 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001002 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001003 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001004 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001005 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001006 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001007 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001008 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001009 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001010 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001011 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001012 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001013 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001014 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001015 }
1016 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001017 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001018 }
1019 klass->SetDexCache(FindDexCache(dex_file));
1020 LoadClass(dex_file, dex_class_def, klass, class_loader);
1021 // Check for a pending exception during load
1022 Thread* self = Thread::Current();
1023 if (self->IsExceptionPending()) {
1024 return NULL;
1025 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001026 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001027 klass->SetClinitThreadId(self->GetTid());
1028 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001029 bool success = InsertClass(descriptor, klass.get()); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001030 if (!success) {
1031 // We may fail to insert if we raced with another thread.
1032 klass->SetClinitThreadId(0);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001033 klass.reset(LookupClass(descriptor, class_loader));
1034 CHECK(klass.get() != NULL);
1035 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001036 }
1037 // Finish loading (if necessary) by finding parents
1038 CHECK(!klass->IsLoaded());
1039 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1040 // Loading failed.
1041 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001042 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001043 lock.NotifyAll();
1044 return NULL;
1045 }
1046 CHECK(klass->IsLoaded());
1047 // Link the class (if necessary)
1048 CHECK(!klass->IsResolved());
1049 if (!LinkClass(klass)) {
1050 // Linking failed.
1051 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001052 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001053 lock.NotifyAll();
1054 return NULL;
1055 }
1056 CHECK(klass->IsResolved());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001057 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001058}
1059
Brian Carlstrom4873d462011-08-21 15:23:39 -07001060// Precomputes size that will be needed for Class, matching LinkStaticFields
1061size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1062 const DexFile::ClassDef& dex_class_def) {
1063 const byte* class_data = dex_file.GetClassData(dex_class_def);
1064 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
1065 size_t num_static_fields = header.static_fields_size_;
1066 size_t num_ref = 0;
1067 size_t num_32 = 0;
1068 size_t num_64 = 0;
1069 if (num_static_fields != 0) {
1070 uint32_t last_idx = 0;
1071 for (size_t i = 0; i < num_static_fields; ++i) {
1072 DexFile::Field dex_field;
1073 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
1074 const DexFile::FieldId& field_id = dex_file.GetFieldId(dex_field.field_idx_);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001075 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001076 char c = descriptor[0];
1077 if (c == 'L' || c == '[') {
1078 num_ref++;
1079 } else if (c == 'J' || c == 'D') {
1080 num_64++;
1081 } else {
1082 num_32++;
1083 }
1084 }
1085 }
1086
1087 // start with generic class data
1088 size_t size = sizeof(Class);
1089 // follow with reference fields which must be contiguous at start
1090 size += (num_ref * sizeof(uint32_t));
1091 // if there are 64-bit fields to add, make sure they are aligned
1092 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1093 if (num_32 != 0) {
1094 // use an available 32-bit field for padding
1095 num_32--;
1096 }
1097 size += sizeof(uint32_t); // either way, we are adding a word
1098 DCHECK_EQ(size, RoundUp(size, 8));
1099 }
1100 // tack on any 64-bit fields now that alignment is assured
1101 size += (num_64 * sizeof(uint64_t));
1102 // tack on any remaining 32-bit fields
1103 size += (num_32 * sizeof(uint32_t));
1104 return size;
1105}
1106
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001107void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001108 // Every kind of method should at least get an invoke stub from the oat_method.
1109 // non-abstract methods also get their code pointers.
1110 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001111 oat_method.LinkMethod(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001112
1113 if (method->IsAbstract()) {
1114 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1115 return;
1116 }
1117 if (method->IsNative()) {
1118 // unregistering restores the dlsym lookup stub
1119 method->UnregisterNative();
1120 return;
1121 }
1122}
1123
Brian Carlstromf615a612011-07-23 12:50:34 -07001124void ClassLinker::LoadClass(const DexFile& dex_file,
1125 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001126 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001127 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001128 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001129 CHECK(klass->GetDexCache() != NULL);
1130 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001131 const byte* class_data = dex_file.GetClassData(dex_class_def);
1132 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001133
Brian Carlstromf615a612011-07-23 12:50:34 -07001134 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001135 CHECK(descriptor != NULL);
1136
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001137 klass->SetClass(GetClassRoot(kJavaLangClass));
1138 if (klass->GetDescriptor() != NULL) {
1139 DCHECK(klass->GetDescriptor()->Equals(descriptor));
1140 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001141 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001142 if (klass->GetDescriptor() == NULL) {
1143 return;
1144 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001145 }
1146 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001147 // Make sure that none of our runtime-only flags are set.
1148 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001149 klass->SetAccessFlags(access_flags);
1150 klass->SetClassLoader(class_loader);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001151 DCHECK(klass->GetPrimitiveType() == Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001152 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001153
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001154 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001155
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001156 size_t num_static_fields = header.static_fields_size_;
1157 size_t num_instance_fields = header.instance_fields_size_;
1158 size_t num_direct_methods = header.direct_methods_size_;
1159 size_t num_virtual_methods = header.virtual_methods_size_;
Brian Carlstrom934486c2011-07-12 23:42:50 -07001160
Jesse Wilson6384f642011-10-07 18:08:35 -04001161 const char* source_file = dex_file.dexGetSourceFile(dex_class_def);
1162 if (source_file != NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001163 String* source_file_string = intern_table_->InternStrong(source_file);
1164 if (source_file_string == NULL) {
1165 return;
1166 }
1167 klass->SetSourceFile(source_file_string);
Jesse Wilson6384f642011-10-07 18:08:35 -04001168 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001169
1170 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -07001171 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001172
1173 // Load static fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001174 if (num_static_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001175 klass->SetSFields(AllocObjectArray<Field>(num_static_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001176 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001177 for (size_t i = 0; i < num_static_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001178 DexFile::Field dex_field;
1179 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001180 SirtRef<Field> sfield(AllocField());
1181 klass->SetStaticField(i, sfield.get());
Brian Carlstromf615a612011-07-23 12:50:34 -07001182 LoadField(dex_file, dex_field, klass, sfield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001183 }
1184 }
1185
1186 // Load instance fields.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001187 if (num_instance_fields != 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001188 klass->SetIFields(AllocObjectArray<Field>(num_instance_fields));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001189 uint32_t last_idx = 0;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001190 for (size_t i = 0; i < num_instance_fields; ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001191 DexFile::Field dex_field;
1192 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001193 SirtRef<Field> ifield(AllocField());
1194 klass->SetInstanceField(i, ifield.get());
Brian Carlstromf615a612011-07-23 12:50:34 -07001195 LoadField(dex_file, dex_field, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001196 }
1197 }
1198
Brian Carlstromaded5f72011-10-07 17:15:04 -07001199 UniquePtr<const OatFile::OatClass> oat_class;
1200 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
1201 const OatFile* oat_file = FindOatFile(dex_file);
1202 if (oat_file != NULL) {
1203 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1204 if (oat_dex_file != NULL) {
1205 uint32_t class_def_index;
1206 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1207 CHECK(found) << descriptor;
1208 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001209 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001210 }
1211 }
1212 }
1213 size_t method_index = 0;
1214
Brian Carlstrom934486c2011-07-12 23:42:50 -07001215 // Load direct methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001216 if (num_direct_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001217 // TODO: append direct methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001218 klass->SetDirectMethods(AllocObjectArray<Method>(num_direct_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001219 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001220 for (size_t i = 0; i < num_direct_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001221 DexFile::Method dex_method;
1222 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001223 SirtRef<Method> method(AllocMethod());
1224 klass->SetDirectMethod(i, method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001225 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001226 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001227 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001228 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001229 }
1230 }
1231
1232 // Load virtual methods.
Brian Carlstrom913af1b2011-07-23 21:41:13 -07001233 if (num_virtual_methods != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001234 // TODO: append virtual methods to class object
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001235 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001236 uint32_t last_idx = 0;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001237 for (size_t i = 0; i < num_virtual_methods; ++i, ++method_index) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001238 DexFile::Method dex_method;
1239 dex_file.dexReadClassDataMethod(&class_data, &dex_method, &last_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001240 SirtRef<Method> method(AllocMethod());
1241 klass->SetVirtualMethod(i, method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001242 LoadMethod(dex_file, dex_method, klass, method);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001243 if (oat_class.get() != NULL) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001244 LinkCode(method, oat_class.get(), method_index);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001245 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001246 }
1247 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001248}
1249
Brian Carlstromf615a612011-07-23 12:50:34 -07001250void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1251 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001252 SirtRef<Class>& klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001253 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001254 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001255 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001256 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1257 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001258 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001259 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001260 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001261 }
1262 }
1263}
1264
Brian Carlstromf615a612011-07-23 12:50:34 -07001265void ClassLinker::LoadField(const DexFile& dex_file,
1266 const DexFile::Field& src,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001267 SirtRef<Class>& klass,
1268 SirtRef<Field>& dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001269 const DexFile::FieldId& field_id = dex_file.GetFieldId(src.field_idx_);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001270 dst->SetDeclaringClass(klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001271 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1272 dst->SetTypeIdx(field_id.type_idx_);
1273 dst->SetAccessFlags(src.access_flags_);
1274
1275 // In order to access primitive types using GetTypeDuringLinking we need to
1276 // ensure they are resolved into the dex cache
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001277 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001278 if (descriptor[1] == '\0') {
1279 // only the descriptors of primitive types should be 1 character long
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001280 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001281 DCHECK(resolved->IsPrimitive());
1282 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001283}
1284
Brian Carlstromf615a612011-07-23 12:50:34 -07001285void ClassLinker::LoadMethod(const DexFile& dex_file,
1286 const DexFile::Method& src,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001287 SirtRef<Class>& klass,
1288 SirtRef<Method>& dst) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001289 const DexFile::MethodId& method_id = dex_file.GetMethodId(src.method_idx_);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001290 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001291
Elliott Hughes80609252011-09-23 17:24:51 -07001292 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Elliott Hughes30646832011-10-13 16:59:46 -07001293 if (method_name == NULL) {
1294 return;
1295 }
Elliott Hughes80609252011-09-23 17:24:51 -07001296 dst->SetName(method_name);
1297 if (method_name->Equals("<init>")) {
1298 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1299 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001300
1301 int32_t utf16_length;
1302 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, &utf16_length));
Elliott Hughes30646832011-10-13 16:59:46 -07001303 String* signature_string = intern_table_->InternStrong(utf16_length, signature.c_str());
1304 if (signature_string == NULL) {
1305 return;
1306 }
1307 dst->SetSignature(signature_string);
Elliott Hughes20cde902011-10-04 17:37:27 -07001308
1309 if (method_name->Equals("finalize") && signature == "()V") {
1310 /*
1311 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1312 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1313 * exclude it here.
1314 *
1315 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1316 */
1317 if (klass->GetClassLoader() != NULL ||
1318 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1319 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1320 klass->SetFinalizable();
1321 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001322 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001323
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001324 dst->SetProtoIdx(method_id.proto_idx_);
1325 dst->SetCodeItemOffset(src.code_off_);
1326 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Elliott Hughes30646832011-10-13 16:59:46 -07001327 String* shorty_string = intern_table_->InternStrong(shorty);
1328 dst->SetShorty(shorty_string);
1329 if (shorty_string == NULL) {
1330 return;
1331 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001332 dst->SetAccessFlags(src.access_flags_);
Ian Rogers9074b992011-10-26 17:41:55 -07001333 uint32_t return_type_idx = dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_;
1334 DCHECK_LT(return_type_idx, dex_file.NumTypeIds());
1335 dst->SetReturnTypeIdx(return_type_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001336
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001337 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1338 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1339 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1340 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1341 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1342 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001343
Brian Carlstrom934486c2011-07-12 23:42:50 -07001344 // TODO: check for finalize method
1345
Brian Carlstromf615a612011-07-23 12:50:34 -07001346 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(src);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001347 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001348 dst->SetNumRegisters(code_item->registers_size_);
1349 dst->SetNumIns(code_item->ins_size_);
1350 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001351 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001352 uint16_t num_args = Method::NumArgRegisters(shorty);
1353 if ((src.access_flags_ & kAccStatic) != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001354 ++num_args;
1355 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001356 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001357 // TODO: native methods
1358 }
1359}
1360
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001361void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001362 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1363 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001364}
1365
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001366void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1367 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001368 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001369 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001370}
1371
Brian Carlstromaded5f72011-10-07 17:15:04 -07001372bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001373 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001374 for (size_t i = 0; i != dex_files_.size(); ++i) {
1375 if (dex_files_[i] == &dex_file) {
1376 return true;
1377 }
1378 }
1379 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001380}
1381
Brian Carlstromaded5f72011-10-07 17:15:04 -07001382bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001383 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001384 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001385}
1386
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001387void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001388 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001389 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001390 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001391 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001392 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001393}
1394
Brian Carlstromaded5f72011-10-07 17:15:04 -07001395void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001396 {
1397 MutexLock mu(dex_lock_);
1398 if (IsDexFileRegisteredLocked(dex_file)) {
1399 return;
1400 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001401 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001402 // Don't alloc while holding the lock, since allocation may need to
1403 // suspend all threads and another thread may need the dex_lock_ to
1404 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001405 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001406 {
1407 MutexLock mu(dex_lock_);
1408 if (IsDexFileRegisteredLocked(dex_file)) {
1409 return;
1410 }
1411 RegisterDexFileLocked(dex_file, dex_cache);
1412 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001413}
1414
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001415void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001416 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001417 RegisterDexFileLocked(dex_file, dex_cache);
1418}
1419
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001420const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001421 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001422 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001423 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1424 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001425 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001426 }
1427 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001428 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001429 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001430}
1431
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001432DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001433 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001434 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001435 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001436 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001437 }
1438 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001439 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001440 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001441}
1442
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001443Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1444 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001445 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001446 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001447 CHECK(primitive_class != NULL);
1448 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1449 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001450 CHECK(primitive_class->GetDescriptor() != NULL);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001451 primitive_class->SetPrimitiveType(type);
1452 primitive_class->SetStatus(Class::kStatusInitialized);
1453 bool success = InsertClass(descriptor, primitive_class);
1454 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1455 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001456}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001457
Brian Carlstrombe977852011-07-19 14:54:54 -07001458// Create an array class (i.e. the class object for the array, not the
1459// array itself). "descriptor" looks like "[C" or "[[[[B" or
1460// "[Ljava/lang/String;".
1461//
1462// If "descriptor" refers to an array of primitives, look up the
1463// primitive type's internally-generated class object.
1464//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001465// "class_loader" is the class loader of the class that's referring to
1466// us. It's used to ensure that we're looking for the element type in
1467// the right context. It does NOT become the class loader for the
1468// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001469//
1470// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001471Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001472 const ClassLoader* class_loader) {
1473 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001474
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001475 // Identify the underlying component type
1476 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001477 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001478 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001479 return NULL;
1480 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001481
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001482 // See if the component type is already loaded. Array classes are
1483 // always associated with the class loader of their underlying
1484 // element type -- an array of Strings goes with the loader for
1485 // java/lang/String -- so we need to look for it there. (The
1486 // caller should have checked for the existence of the class
1487 // before calling here, but they did so with *their* class loader,
1488 // not the component type's loader.)
1489 //
1490 // If we find it, the caller adds "loader" to the class' initiating
1491 // loader list, which should prevent us from going through this again.
1492 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001493 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001494 // are the same, because our caller (FindClass) just did the
1495 // lookup. (Even if we get this wrong we still have correct behavior,
1496 // because we effectively do this lookup again when we add the new
1497 // class to the hash table --- necessary because of possible races with
1498 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001499 if (class_loader != component_type->GetClassLoader()) {
1500 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001501 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001502 return new_class;
1503 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001504 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001505
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001506 // Fill out the fields in the Class.
1507 //
1508 // It is possible to execute some methods against arrays, because
1509 // all arrays are subclasses of java_lang_Object_, so we need to set
1510 // up a vtable. We can just point at the one in java_lang_Object_.
1511 //
1512 // Array classes are simple enough that we don't need to do a full
1513 // link step.
1514
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001515 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001516 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001517 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001518 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001519 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001520 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001521 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001522 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001523 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001524 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001525 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001526 }
1527 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001528 if (new_class.get() == NULL) {
1529 new_class.reset(AllocClass(sizeof(Class)));
1530 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001531 return NULL;
1532 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001533 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001534 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001535 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001536 if (new_class->GetDescriptor() != NULL) {
1537 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1538 } else {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001539 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001540 if (new_class->GetDescriptor() == NULL) {
1541 return NULL;
1542 }
Brian Carlstrom693267a2011-09-06 09:25:34 -07001543 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001544 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001545 new_class->SetSuperClass(java_lang_Object);
1546 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001547 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001548 new_class->SetClassLoader(component_type->GetClassLoader());
1549 new_class->SetStatus(Class::kStatusInitialized);
1550 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001551 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001552
1553
1554 // All arrays have java/lang/Cloneable and java/io/Serializable as
1555 // interfaces. We need to set that up here, so that stuff like
1556 // "instanceof" works right.
1557 //
1558 // Note: The GC could run during the call to FindSystemClass,
1559 // so we need to make sure the class object is GC-valid while we're in
1560 // there. Do this by clearing the interface list so the GC will just
1561 // think that the entries are null.
1562
1563
1564 // Use the single, global copies of "interfaces" and "iftable"
1565 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001566 CHECK(array_interfaces_ != NULL);
1567 CHECK(array_iftable_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001568 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001569 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001570
1571 // Inherit access flags from the component type. Arrays can't be
1572 // used as a superclass or interface, so we want to add "final"
1573 // and remove "interface".
1574 //
1575 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001576 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001577 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001578 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1579 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001580
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001581 if (InsertClass(descriptor, new_class.get())) {
1582 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001583 }
1584 // Another thread must have loaded the class after we
1585 // started but before we finished. Abandon what we've
1586 // done.
1587 //
1588 // (Yes, this happens.)
1589
1590 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001591 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001592 DCHECK(other_class != NULL);
1593 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001594}
1595
1596Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001597 switch (Primitive::GetType(type)) {
1598 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001599 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001600 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001601 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001602 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001603 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001604 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001605 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001606 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001607 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001608 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001609 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001610 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001611 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001612 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001613 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001614 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001615 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001616 case Primitive::kPrimNot:
1617 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001618 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001619 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001620 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001621 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001622}
1623
Brian Carlstromaded5f72011-10-07 17:15:04 -07001624bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001625 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001626 MutexLock mu(classes_lock_);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001627 Table::iterator it = classes_.insert(std::make_pair(hash, klass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001628 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001629}
1630
Brian Carlstromaded5f72011-10-07 17:15:04 -07001631Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001632 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001633 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001634 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001635 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001636 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001637 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001638 return klass;
1639 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001640 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001641 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001642}
1643
jeffhao98eacac2011-09-14 16:11:53 -07001644void ClassLinker::VerifyClass(Class* klass) {
1645 if (klass->IsVerified()) {
1646 return;
1647 }
1648
1649 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001650 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001651
Ian Rogersd81871c2011-10-03 13:57:23 -07001652 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001653 klass->SetStatus(Class::kStatusVerified);
1654 } else {
1655 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001656 Thread* self = Thread::Current();
1657 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1658 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
1659 PrettyDescriptor(klass->GetDescriptor()).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001660 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001661 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001662 }
jeffhao98eacac2011-09-14 16:11:53 -07001663}
1664
Jesse Wilson95caa792011-10-12 18:14:17 -04001665Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers466bb252011-10-14 03:29:56 -07001666 ClassLoader* loader, ObjectArray<Method>* methods, ObjectArray<ObjectArray<Class> >* throws) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001667 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass)));
1668 CHECK(klass.get() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001669 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers466bb252011-10-14 03:29:56 -07001670 const char* descriptor = DotToDescriptor(name->ToModifiedUtf8().c_str()).c_str();;
1671 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Jesse Wilson95caa792011-10-12 18:14:17 -04001672 klass->SetAccessFlags(kAccPublic | kAccFinal);
1673 klass->SetClassLoader(loader);
Ian Rogers466bb252011-10-14 03:29:56 -07001674 klass->SetStatus(Class::kStatusInitialized); // no loading or initializing necessary
1675 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1676 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1677 klass->SetInterfaces(interfaces); // The interfaces are the array of interfaces specified
Jesse Wilson95caa792011-10-12 18:14:17 -04001678
Ian Rogers466bb252011-10-14 03:29:56 -07001679 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001680 klass->SetDirectMethods(AllocObjectArray<Method>(1));
1681 klass->SetDirectMethod(0, CreateProxyConstructor(klass));
1682
Ian Rogers466bb252011-10-14 03:29:56 -07001683 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001684 size_t num_virtual_methods = methods->GetLength();
1685 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1686 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001687 SirtRef<Method> prototype(methods->Get(i));
Jesse Wilson95caa792011-10-12 18:14:17 -04001688 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype, throws->Get(i)));
1689 }
Ian Rogers466bb252011-10-14 03:29:56 -07001690 // Link the virtual methods, creating vtable and iftables
Jesse Wilson95caa792011-10-12 18:14:17 -04001691 if (!LinkMethods(klass)) {
1692 DCHECK(Thread::Current()->IsExceptionPending());
1693 return NULL;
1694 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001695 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001696}
1697
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001698Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass) {
Ian Rogers466bb252011-10-14 03:29:56 -07001699 // Create constructor for Proxy that must initialize h
1700 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1701 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001702 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001703 Method* proxy_constructor = proxy_direct_methods->Get(2);
1704 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1705 // code_ too)
1706 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1707 // Make this constructor public and fix the class to be our Proxy version
1708 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001709 constructor->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001710 // Sanity checks
1711 CHECK(constructor->IsConstructor());
1712 CHECK(constructor->GetName()->Equals("<init>"));
1713 CHECK(constructor->GetSignature()->Equals("(Ljava/lang/reflect/InvocationHandler;)V"));
1714 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001715 return constructor;
1716}
1717
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001718Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype,
Ian Rogers466bb252011-10-14 03:29:56 -07001719 ObjectArray<Class>* throws) {
1720 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialise
1721 // as necessary
1722 Method* method = down_cast<Method*>(prototype->Clone());
1723
1724 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1725 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001726 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001727 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001728 method->SetExceptionTypes(throws);
1729
Ian Rogers466bb252011-10-14 03:29:56 -07001730 // At runtime the method looks like a reference and argument saving method, clone the code
1731 // related parameters from this method.
1732 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1733 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1734 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1735 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1736 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Jesse Wilson95caa792011-10-12 18:14:17 -04001737
Ian Rogers466bb252011-10-14 03:29:56 -07001738 // Basic sanity
1739 DCHECK(method->GetName()->Equals(prototype->GetName()));
1740 DCHECK(method->GetSignature()->Equals(prototype->GetSignature()));
1741 DCHECK(method->GetShorty()->Equals(prototype->GetShorty()));
1742
1743 // More complex sanity - via dex cache
1744 CHECK_EQ(method->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04001745
1746 return method;
1747}
1748
Brian Carlstrom25c33252011-09-18 15:58:35 -07001749bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001750 CHECK(klass->IsResolved() || klass->IsErroneous())
1751 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001752
Carl Shapirob5573532011-07-12 18:22:59 -07001753 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001754
Brian Carlstrom25c33252011-09-18 15:58:35 -07001755 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001756 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001757 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001758 ObjectLock lock(klass);
1759
Brian Carlstromd1422f82011-09-28 11:37:09 -07001760 if (klass->GetStatus() == Class::kStatusInitialized) {
1761 return true;
1762 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001763
Brian Carlstromd1422f82011-09-28 11:37:09 -07001764 if (klass->IsErroneous()) {
1765 ThrowEarlierClassFailure(klass);
1766 return false;
1767 }
1768
1769 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001770 VerifyClass(klass);
1771 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001772 return false;
1773 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001774 }
1775
Brian Carlstrom25c33252011-09-18 15:58:35 -07001776 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1777 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001778 // if the class has a <clinit> but we can't run it during compilation,
1779 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001780 return false;
1781 }
1782
Brian Carlstromd1422f82011-09-28 11:37:09 -07001783 // If the class is kStatusInitializing, either this thread is
1784 // initializing higher up the stack or another thread has beat us
1785 // to initializing and we need to wait. Either way, this
1786 // invocation of InitializeClass will not be responsible for
1787 // running <clinit> and will return.
1788 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001789 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001790 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001791 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001792 return true;
1793 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001794 // No. That's fine. Wait for another thread to finish initializing.
1795 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001796 }
1797
1798 if (!ValidateSuperClassDescriptors(klass)) {
1799 klass->SetStatus(Class::kStatusError);
1800 return false;
1801 }
1802
Brian Carlstromd1422f82011-09-28 11:37:09 -07001803 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001804
Elliott Hughesdcc24742011-09-07 14:02:44 -07001805 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001806 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001807 }
1808
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001809 uint64_t t0 = NanoTime();
1810
Brian Carlstrom25c33252011-09-18 15:58:35 -07001811 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001812 return false;
1813 }
1814
1815 InitializeStaticFields(klass);
1816
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001817 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001818 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001819 }
1820
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001821 uint64_t t1 = NanoTime();
1822
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001823 {
1824 ObjectLock lock(klass);
1825
1826 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001827 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001828 klass->SetStatus(Class::kStatusError);
1829 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001830 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1831 RuntimeStats* thread_stats = self->GetStats();
1832 ++global_stats->class_init_count;
1833 ++thread_stats->class_init_count;
1834 global_stats->class_init_time_ns += (t1 - t0);
1835 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001836 klass->SetStatus(Class::kStatusInitialized);
1837 }
1838 lock.NotifyAll();
1839 }
1840
1841 return true;
1842}
1843
Brian Carlstromd1422f82011-09-28 11:37:09 -07001844bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1845 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001846 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001847 lock.Wait();
1848
1849 // When we wake up, repeat the test for init-in-progress. If
1850 // there's an exception pending (only possible if
1851 // "interruptShouldThrow" was set), bail out.
1852 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001853 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001854 klass->SetStatus(Class::kStatusError);
1855 return false;
1856 }
1857 // Spurious wakeup? Go back to waiting.
1858 if (klass->GetStatus() == Class::kStatusInitializing) {
1859 continue;
1860 }
1861 if (klass->IsErroneous()) {
1862 // The caller wants an exception, but it was thrown in a
1863 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001864 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
1865 PrettyDescriptor(klass->GetDescriptor()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001866 return false;
1867 }
1868 if (klass->IsInitialized()) {
1869 return true;
1870 }
1871 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1872 }
1873 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1874}
1875
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001876bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1877 if (klass->IsInterface()) {
1878 return true;
1879 }
1880 // begin with the methods local to the superclass
1881 if (klass->HasSuperClass() &&
1882 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1883 const Class* super = klass->GetSuperClass();
1884 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001885 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001886 if (method != super->GetVirtualMethod(i) &&
1887 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001888 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1889
1890 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 -07001891 return false;
1892 }
1893 }
1894 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001895 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1896 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1897 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001898 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1899 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001900 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001901 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001902 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001903 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1904
1905 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 -07001906 return false;
1907 }
1908 }
1909 }
1910 }
1911 return true;
1912}
1913
1914bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001915 const Class* klass1,
1916 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07001917 if (klass1 == klass2) {
1918 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07001919 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001920 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001921 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Brian Carlstromf615a612011-07-23 12:50:34 -07001922 DexFile::ParameterIterator *it;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001923 for (it = dex_file.GetParameterIterator(proto_id); it->HasNext(); it->Next()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001924 const char* descriptor = it->GetDescriptor();
1925 if (descriptor == NULL) {
1926 break;
1927 }
1928 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1929 // Found a non-primitive type.
1930 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1931 return false;
1932 }
1933 }
1934 }
1935 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001936 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001937 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001938 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001939 return false;
1940 }
1941 }
1942 return true;
1943}
1944
1945// Returns true if classes referenced by the descriptor are the
1946// same classes in klass1 as they are in klass2.
1947bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001948 const Class* klass1,
1949 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001950 CHECK(descriptor != NULL);
1951 CHECK(klass1 != NULL);
1952 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07001953 if (klass1 == klass2) {
1954 return true;
1955 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001956 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001957 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001958 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001959 // TODO: found2 == NULL
1960 // TODO: lookup found1 in initiating loader list
1961 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001962 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07001963 return found1 == found2;
1964 } else {
1965 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001966 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001967}
1968
Brian Carlstrom25c33252011-09-18 15:58:35 -07001969bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001970 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001971 if (!klass->IsInterface() && klass->HasSuperClass()) {
1972 Class* super_class = klass->GetSuperClass();
1973 if (super_class->GetStatus() != Class::kStatusInitialized) {
1974 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001975 Thread* self = Thread::Current();
1976 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07001977 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07001978 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001979 // TODO: check for a pending exception
1980 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07001981 if (!can_run_clinit) {
1982 // Don't set status to error when we can't run <clinit>.
1983 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
1984 klass->SetStatus(Class::kStatusVerified);
1985 return false;
1986 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001987 klass->SetStatus(Class::kStatusError);
1988 klass->NotifyAll();
1989 return false;
1990 }
1991 }
1992 }
1993 return true;
1994}
1995
Brian Carlstrom25c33252011-09-18 15:58:35 -07001996bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001997 CHECK(c != NULL);
1998 if (c->IsInitialized()) {
1999 return true;
2000 }
2001
Elliott Hughes5f791332011-09-15 17:45:30 -07002002 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002003 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002004 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002005 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002006}
2007
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002008void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
2009 Class* c, std::map<int, Field*>& field_map) {
2010 const ClassLoader* cl = c->GetClassLoader();
2011 const byte* class_data = dex_file.GetClassData(dex_class_def);
2012 DexFile::ClassDataHeader header = dex_file.ReadClassDataHeader(&class_data);
2013 uint32_t last_idx = 0;
2014 for (size_t i = 0; i < header.static_fields_size_; ++i) {
2015 DexFile::Field dex_field;
2016 dex_file.dexReadClassDataField(&class_data, &dex_field, &last_idx);
2017 field_map[i] = ResolveField(dex_file, dex_field.field_idx_, c->GetDexCache(), cl, true);
2018 }
2019}
2020
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002021void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002022 size_t num_static_fields = klass->NumStaticFields();
2023 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002024 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002025 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002026 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002027 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002028 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002029 return;
2030 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002031 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002032 const DexFile& dex_file = FindDexFile(dex_cache);
2033 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07002034 CHECK(dex_class_def != NULL);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002035
2036 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2037 std::map<int, Field*> field_map;
2038 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2039
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002040 const byte* addr = dex_file.GetEncodedArray(*dex_class_def);
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002041 if (addr == NULL) {
2042 // All this class' static fields have default values.
2043 return;
2044 }
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002045 size_t array_size = DecodeUnsignedLeb128(&addr);
2046 for (size_t i = 0; i < array_size; ++i) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002047 Field* field = field_map[i];
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002048 JValue value;
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002049 DexFile::ValueType type = dex_file.ReadEncodedValue(&addr, &value);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002050 switch (type) {
Brian Carlstromf615a612011-07-23 12:50:34 -07002051 case DexFile::kByte:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002052 field->SetByte(NULL, value.b);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002053 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002054 case DexFile::kShort:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002055 field->SetShort(NULL, value.s);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002056 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002057 case DexFile::kChar:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002058 field->SetChar(NULL, value.c);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002059 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002060 case DexFile::kInt:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002061 field->SetInt(NULL, value.i);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002062 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002063 case DexFile::kLong:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002064 field->SetLong(NULL, value.j);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002065 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002066 case DexFile::kFloat:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002067 field->SetFloat(NULL, value.f);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002068 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002069 case DexFile::kDouble:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002070 field->SetDouble(NULL, value.d);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002071 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002072 case DexFile::kString: {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002073 uint32_t string_idx = value.i;
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002074 const String* resolved = ResolveString(dex_file, string_idx, klass->GetDexCache());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002075 field->SetObject(NULL, resolved);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002076 break;
2077 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002078 case DexFile::kBoolean:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002079 field->SetBoolean(NULL, value.z);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002080 break;
Brian Carlstromf615a612011-07-23 12:50:34 -07002081 case DexFile::kNull:
Brian Carlstrom4873d462011-08-21 15:23:39 -07002082 field->SetObject(NULL, value.l);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002083 break;
2084 default:
Carl Shapiro606258b2011-07-09 16:09:09 -07002085 LOG(FATAL) << "Unknown type " << static_cast<int>(type);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002086 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002087 }
2088}
2089
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002090bool ClassLinker::LinkClass(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002091 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002092 if (!LinkSuperClass(klass)) {
2093 return false;
2094 }
2095 if (!LinkMethods(klass)) {
2096 return false;
2097 }
2098 if (!LinkInstanceFields(klass)) {
2099 return false;
2100 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002101 if (!LinkStaticFields(klass)) {
2102 return false;
2103 }
2104 CreateReferenceInstanceOffsets(klass);
2105 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002106 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2107 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002108 return true;
2109}
2110
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002111bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002112 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
2113 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002114 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002115 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002116 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002117 return false;
2118 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002119 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002120 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002121 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
2122 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002123 Class* interface = ResolveType(dex_file, idx, klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002124 klass->SetInterface(i, interface);
2125 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002126 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002127 return false;
2128 }
2129 // Verify
2130 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002131 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002132 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002133 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002134 PrettyDescriptor(interface->GetDescriptor()).c_str(),
2135 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002136 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002137 }
2138 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002139 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002140 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002141 return true;
2142}
2143
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002144bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002145 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002146 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002147 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002148 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002149 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002150 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002151 return false;
2152 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002153 return true;
2154 }
2155 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002156 ThrowLinkageError("No superclass defined for class %s",
2157 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002158 return false;
2159 }
2160 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002161 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002162 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002163 "Superclass %s of %s is %s",
2164 PrettyDescriptor(super->GetDescriptor()).c_str(),
2165 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002166 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002167 return false;
2168 }
2169 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002170 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002171 "Superclass %s is inaccessible by %s",
2172 PrettyDescriptor(super->GetDescriptor()).c_str(),
2173 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002174 return false;
2175 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002176
2177 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2178 if (super->IsFinalizable()) {
2179 klass->SetFinalizable();
2180 }
2181
Elliott Hughes2da50362011-10-10 16:57:08 -07002182 // Inherit reference flags (if any) from the superclass.
2183 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2184 if (reference_flags != 0) {
2185 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2186 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002187 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002188 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002189 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
2190 PrettyDescriptor(klass->GetDescriptor()).c_str());
2191 return false;
2192 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002193
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002194#ifndef NDEBUG
2195 // Ensure super classes are fully resolved prior to resolving fields..
2196 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002197 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002198 super = super->GetSuperClass();
2199 }
2200#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002201 return true;
2202}
2203
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002204// Populate the class vtable and itable. Compute return type indices.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002205bool ClassLinker::LinkMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002206 if (klass->IsInterface()) {
2207 // No vtable.
2208 size_t count = klass->NumVirtualMethods();
2209 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002210 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002211 return false;
2212 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002213 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002214 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002215 }
jeffhaobdb76512011-09-07 11:43:16 -07002216 // Link interface method tables
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002217 return LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002218 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002219 // Link virtual and interface method tables
2220 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002221 }
2222 return true;
2223}
2224
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002225bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002226 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002227 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2228 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002229 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002230 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002231 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002232 // See if any of our virtual methods override the superclass.
2233 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002234 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002235 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002236 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002237 Method* super_method = vtable->Get(j);
Ian Rogers466bb252011-10-14 03:29:56 -07002238 if (local_method->HasSameNameAndSignature(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002239 // Verify
2240 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002241 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002242 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2243 local_method->GetName()->ToModifiedUtf8().c_str(),
2244 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002245 return false;
2246 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002247 vtable->Set(j, local_method);
2248 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002249 break;
2250 }
2251 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002252 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002253 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002254 vtable->Set(actual_count, local_method);
2255 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002256 actual_count += 1;
2257 }
2258 }
2259 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002260 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002261 return false;
2262 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002263 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002264 CHECK_LE(actual_count, max_count);
2265 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002266 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002267 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002268 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002269 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002270 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002271 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002272 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002273 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002274 return false;
2275 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002276 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002277 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002278 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2279 vtable->Set(i, virtual_method);
2280 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002281 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002282 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002283 }
2284 return true;
2285}
2286
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002287bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288 size_t super_ifcount;
2289 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002290 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002291 } else {
2292 super_ifcount = 0;
2293 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002294 size_t ifcount = super_ifcount;
2295 ifcount += klass->NumInterfaces();
2296 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002297 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002298 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002299 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002300 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002301 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002302 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002303 return true;
2304 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002305 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002306 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002307 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2308 for (size_t i = 0; i < super_ifcount; i++) {
2309 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2310 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002311 }
2312 // Flatten the interface inheritance hierarchy.
2313 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002314 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002315 Class* interface = klass->GetInterface(i);
2316 DCHECK(interface != NULL);
2317 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002318 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002319 "Class %s implements non-interface class %s",
2320 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2321 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002322 return false;
2323 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002324 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002325 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002326 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002327 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2328 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002329 }
2330 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002331 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002332 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002333
2334 // If we're an interface, we don't need the vtable pointers, so we're done.
2335 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002336 return true;
2337 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002338 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002339 for (size_t i = 0; i < ifcount; ++i) {
2340 InterfaceEntry* interface_entry = iftable->Get(i);
2341 Class* interface = interface_entry->GetInterface();
2342 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2343 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002344 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002345 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2346 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002347 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002348 // For each method listed in the interface's method list, find the
2349 // matching method in our class's method list. We want to favor the
2350 // subclass over the superclass, which just requires walking
2351 // back from the end of the vtable. (This only matters if the
2352 // superclass defines a private method and this class redefines
2353 // it -- otherwise it would use the same vtable slot. In .dex files
2354 // those don't end up in the virtual method table, so it shouldn't
2355 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002356 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2357 Method* vtable_method = vtable->Get(k);
Ian Rogers466bb252011-10-14 03:29:56 -07002358 if (interface_method->HasSameNameAndSignature(vtable_method)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002359 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002360 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002361 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002362 return false;
2363 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002364 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002365 break;
2366 }
2367 }
2368 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002369 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002370 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers466bb252011-10-14 03:29:56 -07002371 if (miranda_list[mir]->HasSameNameAndSignature(interface_method)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002372 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002373 break;
2374 }
2375 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002376 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002377 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002378 miranda_method.reset(AllocMethod());
2379 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2380 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002381 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002382 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002383 }
2384 }
2385 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002386 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002387 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002388 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002389 klass->SetVirtualMethods((old_method_count == 0)
2390 ? AllocObjectArray<Method>(new_method_count)
2391 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002392
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002393 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2394 CHECK(vtable != NULL);
2395 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002396 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002397 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002398 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002399 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002400 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002401 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2402 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2403 klass->SetVirtualMethod(old_method_count + i, method);
2404 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002405 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002406 // TODO: do not assign to the vtable field until it is fully constructed.
2407 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002408 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002409
2410 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2411 for (int i = 0; i < vtable->GetLength(); ++i) {
2412 CHECK(vtable->Get(i) != NULL);
2413 }
2414
2415// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2416
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002417 return true;
2418}
2419
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002420bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2421 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002422 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002423}
2424
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002425bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2426 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002427 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002428 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002429 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002430 return success;
2431}
2432
Brian Carlstromdbc05252011-09-09 01:59:59 -07002433struct LinkFieldsComparator {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002434 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002435 // First come reference fields, then 64-bit, and finally 32-bit
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002436 Primitive::Type type1 = field1->GetPrimitiveType();
2437 Primitive::Type type2 = field2->GetPrimitiveType();
2438 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2439 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2440 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2441 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002442 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2443 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2444 if (order1 != order2) {
2445 return order1 < order2;
2446 }
2447
2448 // same basic group? then sort by string.
2449 std::string name1 = field1->GetName()->ToModifiedUtf8();
2450 std::string name2 = field2->GetName()->ToModifiedUtf8();
2451 return name1 < name2;
2452 }
2453};
2454
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002455bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002456 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002457 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002458
2459 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002460 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002461
2462 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002463 size_t size;
2464 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002465 if (is_static) {
2466 size = klass->GetClassSize();
2467 field_offset = Class::FieldsOffset();
2468 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002469 Class* super_class = klass->GetSuperClass();
2470 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002471 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002472 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002473 }
2474 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002475 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002476
Brian Carlstromdbc05252011-09-09 01:59:59 -07002477 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002478
Brian Carlstromdbc05252011-09-09 01:59:59 -07002479 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002480 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002481 std::deque<Field*> grouped_and_sorted_fields;
2482 for (size_t i = 0; i < num_fields; i++) {
2483 grouped_and_sorted_fields.push_back(fields->Get(i));
2484 }
2485 std::sort(grouped_and_sorted_fields.begin(),
2486 grouped_and_sorted_fields.end(),
2487 LinkFieldsComparator());
2488
2489 // References should be at the front.
2490 size_t current_field = 0;
2491 size_t num_reference_fields = 0;
2492 for (; current_field < num_fields; current_field++) {
2493 Field* field = grouped_and_sorted_fields.front();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002494 Primitive::Type type = field->GetPrimitiveType();
2495 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002496 if (isPrimitive) {
2497 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002498 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002499 grouped_and_sorted_fields.pop_front();
2500 num_reference_fields++;
2501 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002502 field->SetOffset(field_offset);
2503 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002504 }
2505
2506 // Now we want to pack all of the double-wide fields together. If
2507 // we're not aligned, though, we want to shuffle one 32-bit field
2508 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002509 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002510 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2511 Field* field = grouped_and_sorted_fields[i];
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002512 Primitive::Type type = field->GetPrimitiveType();
2513 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2514 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002515 continue;
2516 }
2517 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002518 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002519 // drop the consumed field
2520 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2521 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002522 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002523 // whether we found a 32-bit field for padding or not, we advance
2524 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002525 }
2526
2527 // Alignment is good, shuffle any double-wide fields forward, and
2528 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002529 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002530 while (!grouped_and_sorted_fields.empty()) {
2531 Field* field = grouped_and_sorted_fields.front();
2532 grouped_and_sorted_fields.pop_front();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002533 Primitive::Type type = field->GetPrimitiveType();
2534 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002535 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002536 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002537 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002538 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002539 ? sizeof(uint64_t)
2540 : sizeof(uint32_t)));
2541 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002542 }
2543
Elliott Hughesadb460d2011-10-05 17:02:34 -07002544 // 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 -07002545 if (!is_static && klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002546 // We know there are no non-reference fields in the Reference classes, and we know
2547 // that 'referent' is alphabetically last, so this is easy...
2548 CHECK_EQ(num_reference_fields, num_fields);
2549 CHECK(fields->Get(num_fields - 1)->GetName()->Equals("referent"));
2550 --num_reference_fields;
2551 }
2552
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002553#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002554 // Make sure that all reference fields appear before
2555 // non-reference fields, and all double-wide fields are aligned.
2556 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002557 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002558 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002559 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002560 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002561 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002562 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002563 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2564 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002565 Primitive::Type type = field->GetPrimitiveType();
2566 bool is_primitive = type != Primitive::kPrimNot;
Elliott Hughesadb460d2011-10-05 17:02:34 -07002567 if (klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;") && field->GetName()->Equals("referent")) {
2568 is_primitive = true; // We lied above, so we have to expect a lie here.
2569 }
2570 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002571 if (!seen_non_ref) {
2572 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002573 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002574 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002575 } else {
2576 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002577 }
2578 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002579 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002580 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002581 }
2582#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002583 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002584 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002585 if (is_static) {
2586 klass->SetNumReferenceStaticFields(num_reference_fields);
2587 klass->SetClassSize(size);
2588 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002589 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002590 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002591 klass->SetObjectSize(size);
2592 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002593 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002594 return true;
2595}
2596
2597// Set the bitmap of reference offsets, refOffsets, from the ifields
2598// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002599void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002600 uint32_t reference_offsets = 0;
2601 Class* super_class = klass->GetSuperClass();
2602 if (super_class != NULL) {
2603 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002604 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002605 if (reference_offsets == CLASS_WALK_SUPER) {
2606 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002607 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002608 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002609 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002610 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002611}
2612
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002613void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002614 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002615}
2616
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002617void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002618 uint32_t reference_offsets) {
2619 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002620 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2621 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002622 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002623 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002624 // All of the fields that contain object references are guaranteed
2625 // to be at the beginning of the fields list.
2626 for (size_t i = 0; i < num_reference_fields; ++i) {
2627 // Note that byte_offset is the offset from the beginning of
2628 // object, not the offset into instance data
2629 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002630 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002631 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2632 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2633 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002634 CHECK_NE(new_bit, 0U);
2635 reference_offsets |= new_bit;
2636 } else {
2637 reference_offsets = CLASS_WALK_SUPER;
2638 break;
2639 }
2640 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002641 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002642 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002643 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002644 } else {
2645 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002646 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002647}
2648
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002649String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002650 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002651 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002652 if (resolved != NULL) {
2653 return resolved;
2654 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002655 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2656 int32_t utf16_length = dex_file.GetStringLength(string_id);
2657 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002658 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002659 dex_cache->SetResolvedString(string_idx, string);
2660 return string;
2661}
2662
2663Class* ClassLinker::ResolveType(const DexFile& dex_file,
2664 uint32_t type_idx,
2665 DexCache* dex_cache,
2666 const ClassLoader* class_loader) {
2667 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002668 if (resolved == NULL) {
2669 const char* descriptor = dex_file.dexStringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002670 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002671 if (resolved != NULL) {
jeffhaod760bc42011-10-03 14:54:53 -07002672 Class* check = resolved;
2673 while (check->IsArrayClass()) {
2674 check = check->GetComponentType();
2675 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002676 if (dex_cache != check->GetDexCache()) {
2677 if (check->GetClassLoader() != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002678 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002679 "Class with type index %d resolved by unexpected .dex", type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002680 resolved = NULL;
2681 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002682 }
2683 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002684 if (resolved != NULL) {
2685 dex_cache->SetResolvedType(type_idx, resolved);
2686 } else {
2687 DCHECK(Thread::Current()->IsExceptionPending());
2688 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002689 }
2690 return resolved;
2691}
2692
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002693Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2694 uint32_t method_idx,
2695 DexCache* dex_cache,
2696 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002697 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002698 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2699 if (resolved != NULL) {
2700 return resolved;
2701 }
2702 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2703 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2704 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002705 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002706 return NULL;
2707 }
2708
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002709 const char* name = dex_file.dexStringById(method_id.name_idx_);
Elliott Hughes0c424cb2011-08-26 10:16:25 -07002710 std::string signature(dex_file.CreateMethodDescriptor(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002711 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002712 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002713 } else if (klass->IsInterface()) {
2714 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002715 } else {
2716 resolved = klass->FindVirtualMethod(name, signature);
2717 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002718 if (resolved != NULL) {
2719 dex_cache->SetResolvedMethod(method_idx, resolved);
2720 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002721 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002722 }
2723 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002724}
2725
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002726Field* ClassLinker::ResolveField(const DexFile& dex_file,
2727 uint32_t field_idx,
2728 DexCache* dex_cache,
2729 const ClassLoader* class_loader,
2730 bool is_static) {
2731 Field* resolved = dex_cache->GetResolvedField(field_idx);
2732 if (resolved != NULL) {
2733 return resolved;
2734 }
2735 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2736 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2737 if (klass == NULL) {
2738 return NULL;
2739 }
2740
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002741 const char* name = dex_file.GetFieldName(field_id);
2742 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002743 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002744 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002745 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002746 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002747 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002748 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002749 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002750 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002751 DCHECK(Thread::Current()->IsExceptionPending())
2752 << PrettyClass(klass) << " " << name << " " << type << " " << is_static;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002753 }
2754 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002755}
2756
Ian Rogersad25ac52011-10-04 19:13:33 -07002757const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2758 Class* declaring_class = referrer->GetDeclaringClass();
2759 DexCache* dex_cache = declaring_class->GetDexCache();
2760 const DexFile& dex_file = FindDexFile(dex_cache);
2761 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2762 return dex_file.GetShorty(method_id.proto_idx_);
2763}
2764
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002765void ClassLinker::DumpAllClasses(int flags) const {
2766 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2767 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2768 std::vector<Class*> all_classes;
2769 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002770 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002771 typedef Table::const_iterator It; // TODO: C++0x auto
2772 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2773 all_classes.push_back(it->second);
2774 }
2775 }
2776
2777 for (size_t i = 0; i < all_classes.size(); ++i) {
2778 all_classes[i]->DumpClass(std::cerr, flags);
2779 }
2780}
2781
Elliott Hughese27955c2011-08-26 15:21:24 -07002782size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002783 MutexLock mu(classes_lock_);
Elliott Hughese27955c2011-08-26 15:21:24 -07002784 return classes_.size();
2785}
2786
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002787pid_t ClassLinker::GetClassesLockOwner() {
2788 return classes_lock_.GetOwner();
2789}
2790
2791pid_t ClassLinker::GetDexLockOwner() {
2792 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002793}
2794
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002795} // namespace art