blob: 4598ae9397deb3ef95ba979ac97c143144cec6ab [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"
Ian Rogers0571d352011-11-03 19:51:38 -070017#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070018#include "logging.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070019#include "monitor.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070020#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070021#include "object.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070022#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070023#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070024#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070025#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070026#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070027#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070028#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070029#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070030#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070031
32namespace art {
33
Elliott Hughes4a2b4172011-09-20 17:08:25 -070034namespace {
35
Elliott Hughes362f9bc2011-10-17 18:56:41 -070036void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070037void ThrowNoClassDefFoundError(const char* fmt, ...) {
38 va_list args;
39 va_start(args, fmt);
40 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
41 va_end(args);
42}
43
Elliott Hughes362f9bc2011-10-17 18:56:41 -070044void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070045void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070046 va_list args;
47 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070048 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070049 va_end(args);
50}
51
Elliott Hughes362f9bc2011-10-17 18:56:41 -070052void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070053void ThrowLinkageError(const char* fmt, ...) {
54 va_list args;
55 va_start(args, fmt);
56 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
57 va_end(args);
58}
59
Elliott Hughescc5f9a92011-09-28 19:17:29 -070060void ThrowNoSuchMethodError(const char* kind,
61 Class* c, const StringPiece& name, const StringPiece& signature) {
62 DexCache* dex_cache = c->GetDexCache();
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070063 std::ostringstream msg;
Elliott Hughescc5f9a92011-09-28 19:17:29 -070064 msg << "no " << kind << " method " << name << "." << signature
65 << " in class " << c->GetDescriptor()->ToModifiedUtf8()
66 << " or its superclasses";
67 if (dex_cache) {
68 msg << " (defined in " << dex_cache->GetLocation()->ToModifiedUtf8() << ")";
69 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070070 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070071}
72
Elliott Hughes4a2b4172011-09-20 17:08:25 -070073void ThrowEarlierClassFailure(Class* c) {
74 /*
75 * The class failed to initialize on a previous attempt, so we want to throw
76 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
77 * failed in verification, in which case v2 5.4.1 says we need to re-throw
78 * the previous error.
79 */
80 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
81
82 if (c->GetVerifyErrorClass() != NULL) {
83 // TODO: change the verifier to store an _instance_, with a useful detail message?
84 std::string error_descriptor(c->GetVerifyErrorClass()->GetDescriptor()->ToModifiedUtf8());
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070085 Thread::Current()->ThrowNewException(error_descriptor.c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -070086 PrettyDescriptor(c->GetDescriptor()).c_str());
87 } else {
88 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c->GetDescriptor()).c_str());
89 }
90}
91
Elliott Hughes4d0207c2011-10-03 19:14:34 -070092void WrapExceptionInInitializer() {
93 JNIEnv* env = Thread::Current()->GetJniEnv();
94
95 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
96 CHECK(cause.get() != NULL);
97
98 env->ExceptionClear();
99
100 // TODO: add java.lang.Error to JniConstants?
101 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
102 CHECK(error_class.get() != NULL);
103 if (env->IsInstanceOf(cause.get(), error_class.get())) {
104 // We only wrap non-Error exceptions; an Error can just be used as-is.
105 env->Throw(cause.get());
106 return;
107 }
108
109 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
110 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
111 CHECK(eiie_class.get() != NULL);
112
113 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
114 CHECK(mid != NULL);
115
116 ScopedLocalRef<jthrowable> eiie(env,
117 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
118 env->Throw(eiie.get());
119}
120
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700121} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700122
Elliott Hughes418d20f2011-09-22 14:00:39 -0700123const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700124 "Ljava/lang/Class;",
125 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700126 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700127 "[Ljava/lang/Object;",
128 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700129 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700130 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700131 "Ljava/lang/reflect/Field;",
132 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700133 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700134 "Ljava/lang/ClassLoader;",
135 "Ldalvik/system/BaseDexClassLoader;",
136 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700137 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700138 "Z",
139 "B",
140 "C",
141 "D",
142 "F",
143 "I",
144 "J",
145 "S",
146 "V",
147 "[Z",
148 "[B",
149 "[C",
150 "[D",
151 "[F",
152 "[I",
153 "[J",
154 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700155 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700156};
157
Elliott Hughes5f791332011-09-15 17:45:30 -0700158class ObjectLock {
159 public:
160 explicit ObjectLock(Object* object) : self_(Thread::Current()), obj_(object) {
161 CHECK(object != NULL);
162 obj_->MonitorEnter(self_);
163 }
164
165 ~ObjectLock() {
166 obj_->MonitorExit(self_);
167 }
168
169 void Wait() {
170 return Monitor::Wait(self_, obj_, 0, 0, false);
171 }
172
173 void Notify() {
174 obj_->Notify();
175 }
176
177 void NotifyAll() {
178 obj_->NotifyAll();
179 }
180
181 private:
182 Thread* self_;
183 Object* obj_;
184 DISALLOW_COPY_AND_ASSIGN(ObjectLock);
185};
186
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700187ClassLinker* ClassLinker::Create(const std::string& boot_class_path,
188 InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700189 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700190 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700191 class_linker->Init(boot_class_path);
192 return class_linker.release();
193}
194
195ClassLinker* ClassLinker::Create(InternTable* intern_table) {
196 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
197 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700198 return class_linker.release();
199}
200
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700201ClassLinker::ClassLinker(InternTable* intern_table)
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700202 : dex_lock_("ClassLinker dex lock"),
203 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700204 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700205 array_interfaces_(NULL),
206 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700207 init_done_(false),
208 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700209 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700210}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700211
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700212void CreateClassPath(const std::string& class_path,
213 std::vector<const DexFile*>& class_path_vector) {
214 std::vector<std::string> parsed;
215 Split(class_path, ':', parsed);
216 for (size_t i = 0; i < parsed.size(); ++i) {
217 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700218 if (dex_file == NULL) {
219 LOG(WARNING) << "Failed to open dex file " << parsed[i];
220 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700221 class_path_vector.push_back(dex_file);
222 }
223 }
224}
225
226void ClassLinker::Init(const std::string& boot_class_path) {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700227 const Runtime* runtime = Runtime::Current();
228 if (runtime->IsVerboseStartup()) {
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700229 LOG(INFO) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700230 }
231
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700232 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700233
Elliott Hughes30646832011-10-13 16:59:46 -0700234 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700235 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
236 CHECK(java_lang_Class.get() != NULL);
237 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700238 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700239 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700240
Elliott Hughes418d20f2011-09-22 14:00:39 -0700241 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700242 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
243 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700244
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700245 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700246 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
247 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700248 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700249 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700250 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700251
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700252 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700253 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
254 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700255
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700256 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700257 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700258
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700259 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700260 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
261 char_array_class->SetComponentType(char_class.get());
262 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700263
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700264 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700265 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
266 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700267 java_lang_String->SetObjectSize(sizeof(String));
268 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400269
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 // Backfill Class descriptors missing until this point
Brian Carlstromc74255f2011-09-11 22:47:39 -0700271 java_lang_Class->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Class;"));
272 java_lang_Object->SetDescriptor(intern_table_->InternStrong("Ljava/lang/Object;"));
Elliott Hughes418d20f2011-09-22 14:00:39 -0700273 class_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Class;"));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700274 object_array_class->SetDescriptor(intern_table_->InternStrong("[Ljava/lang/Object;"));
275 java_lang_String->SetDescriptor(intern_table_->InternStrong("Ljava/lang/String;"));
276 char_array_class->SetDescriptor(intern_table_->InternStrong("[C"));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700277
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700278 // Create storage for root classes, save away our work so far (requires
279 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700280 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700281 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700282 SetClassRoot(kJavaLangClass, java_lang_Class.get());
283 SetClassRoot(kJavaLangObject, java_lang_Object.get());
284 SetClassRoot(kClassArrayClass, class_array_class.get());
285 SetClassRoot(kObjectArrayClass, object_array_class.get());
286 SetClassRoot(kCharArrayClass, char_array_class.get());
287 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700288
289 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700290 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
291 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
292 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
293 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
294 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
295 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
296 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
297 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700298
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299 // Create array interface entries to populate once we can load system classes
Elliott Hughes418d20f2011-09-22 14:00:39 -0700300 array_interfaces_ = AllocClassArray(2);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700301 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302
303 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700304 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700305 int_array_class->SetDescriptor(intern_table_->InternStrong("[I"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700306 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700307 IntArray::SetArrayClass(int_array_class.get());
308 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700309
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700310 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700311
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700312 // setup boot_class_path_ and register class_path now that we can
313 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700314 std::vector<const DexFile*> boot_class_path_vector;
315 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700316 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700317 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
318 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700319 CHECK(dex_file != NULL);
320 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700321 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700322
Elliott Hughes80609252011-09-23 17:24:51 -0700323 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700324 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Elliott Hughes80609252011-09-23 17:24:51 -0700325 java_lang_reflect_Constructor->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Constructor;"));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700326 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700327 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700328 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700329 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
330
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
332 CHECK(java_lang_reflect_Field.get() != NULL);
Brian Carlstromc74255f2011-09-11 22:47:39 -0700333 java_lang_reflect_Field->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Field;"));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700335 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700336 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700337 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700338
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700339 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Elliott Hughes80609252011-09-23 17:24:51 -0700340 java_lang_reflect_Method->SetDescriptor(intern_table_->InternStrong("Ljava/lang/reflect/Method;"));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700341 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700342 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700343 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700345 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700346
347 // now we can use FindSystemClass
348
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700349 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700350 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700351 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700352
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700353 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 java_lang_Object->SetStatus(Class::kStatusNotReady);
355 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700356 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
358 java_lang_String->SetStatus(Class::kStatusNotReady);
359 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700360 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700361 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
362
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700363 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
365 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
366
367 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
368 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
369
370 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700371 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700372
373 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
374 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
375
376 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700377 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700378
379 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
380 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
381
382 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
383 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
384
385 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
386 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
387
Elliott Hughes418d20f2011-09-22 14:00:39 -0700388 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700389 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700390
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700391 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700392 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393
394 // Setup the single, global copies of "interfaces" and "iftable"
395 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
396 CHECK(java_lang_Cloneable != NULL);
397 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
398 CHECK(java_io_Serializable != NULL);
399 CHECK(array_interfaces_ != NULL);
400 array_interfaces_->Set(0, java_lang_Cloneable);
401 array_interfaces_->Set(1, java_io_Serializable);
402 // We assume that Cloneable/Serializable don't have superinterfaces --
403 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700404 // supers as well.
405 array_iftable_->Set(0, AllocInterfaceEntry(array_interfaces_->Get(0)));
406 array_iftable_->Set(1, AllocInterfaceEntry(array_interfaces_->Get(1)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700407
Elliott Hughes418d20f2011-09-22 14:00:39 -0700408 // Sanity check Class[] and Object[]'s interfaces
409 CHECK_EQ(java_lang_Cloneable, class_array_class->GetInterface(0));
410 CHECK_EQ(java_io_Serializable, class_array_class->GetInterface(1));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411 CHECK_EQ(java_lang_Cloneable, object_array_class->GetInterface(0));
412 CHECK_EQ(java_io_Serializable, object_array_class->GetInterface(1));
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700413
Elliott Hughes80609252011-09-23 17:24:51 -0700414 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700415 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700416 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700417 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700418
Elliott Hughes80609252011-09-23 17:24:51 -0700419 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
420 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700421 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700422
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700423 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700424 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700425 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700426
427 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700428 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700429 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700430
Ian Rogers466bb252011-10-14 03:29:56 -0700431 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
432
433 // Create java.lang.reflect.Proxy root
434 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
435 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
436
Brian Carlstrom1f870082011-08-23 16:02:11 -0700437 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700438 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
439 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700440 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700441 java_lang_ref_FinalizerReference->SetAccessFlags(
442 java_lang_ref_FinalizerReference->GetAccessFlags() |
443 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700444 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700445 java_lang_ref_PhantomReference->SetAccessFlags(
446 java_lang_ref_PhantomReference->GetAccessFlags() |
447 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700448 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700449 java_lang_ref_SoftReference->SetAccessFlags(
450 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700451 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700452 java_lang_ref_WeakReference->SetAccessFlags(
453 java_lang_ref_WeakReference->GetAccessFlags() |
454 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700455
Brian Carlstromaded5f72011-10-07 17:15:04 -0700456 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700457 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700458 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700459 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
460
461 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
462 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
463 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
464
465 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
466 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
467 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
468 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
469
470 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700471 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
472 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700473 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700474
Brian Carlstroma663ea52011-08-19 23:33:41 -0700475 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700476
477 if (runtime->IsVerboseStartup()) {
478 LOG(INFO) << "ClassLinker::InitFrom exiting";
479 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700480}
481
482void ClassLinker::FinishInit() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700483 const Runtime* runtime = Runtime::Current();
484 if (runtime->IsVerboseStartup()) {
485 LOG(INFO) << "ClassLinker::FinishInit entering";
486 }
Brian Carlstrom16192862011-09-12 17:50:06 -0700487
488 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700489 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700490 // as the types of the field can't be resolved prior to the runtime being
491 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700492 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700493 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700494 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
495
Elliott Hughesadb460d2011-10-05 17:02:34 -0700496 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
497
Brian Carlstrom16192862011-09-12 17:50:06 -0700498 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
499 CHECK(pendingNext->GetName()->Equals("pendingNext"));
500 CHECK_EQ(ResolveType(pendingNext->GetTypeIdx(), pendingNext), java_lang_ref_Reference);
501
502 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
503 CHECK(queue->GetName()->Equals("queue"));
Elliott Hughesadb460d2011-10-05 17:02:34 -0700504 CHECK_EQ(ResolveType(queue->GetTypeIdx(), queue), java_lang_ref_ReferenceQueue);
Brian Carlstrom16192862011-09-12 17:50:06 -0700505
506 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
507 CHECK(queueNext->GetName()->Equals("queueNext"));
508 CHECK_EQ(ResolveType(queueNext->GetTypeIdx(), queueNext), java_lang_ref_Reference);
509
510 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
511 CHECK(referent->GetName()->Equals("referent"));
512 CHECK_EQ(ResolveType(referent->GetTypeIdx(), referent), GetClassRoot(kJavaLangObject));
513
514 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
515 CHECK(zombie->GetName()->Equals("zombie"));
516 CHECK_EQ(ResolveType(zombie->GetTypeIdx(), zombie), GetClassRoot(kJavaLangObject));
517
518 Heap::SetReferenceOffsets(referent->GetOffset(),
519 queue->GetOffset(),
520 queueNext->GetOffset(),
521 pendingNext->GetOffset(),
522 zombie->GetOffset());
523
Brian Carlstroma663ea52011-08-19 23:33:41 -0700524 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700525 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700526 ClassRoot class_root = static_cast<ClassRoot>(i);
527 Class* klass = GetClassRoot(class_root);
528 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700529 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700530 // note SetClassRoot does additional validation.
531 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700532 }
533
Elliott Hughes92f14b22011-10-06 12:29:54 -0700534 CHECK(array_iftable_ != NULL);
535 CHECK(array_interfaces_ != NULL);
536
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700537 // disable the slow paths in FindClass and CreatePrimitiveClass now
538 // that Object, Class, and Object[] are setup
539 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700540
541 if (runtime->IsVerboseStartup()) {
542 LOG(INFO) << "ClassLinker::FinishInit exiting";
543 }
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700544}
545
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700546void ClassLinker::RunRootClinits() {
547 Thread* self = Thread::Current();
548 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
549 Class* c = GetClassRoot(ClassRoot(i));
550 if (!c->IsArrayClass() && !c->IsPrimitive()) {
551 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700552 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700553 }
554 }
555}
556
jeffhao262bf462011-10-20 18:36:32 -0700557const OatFile* ClassLinker::GenerateOatFile(const std::string& filename) {
558 std::string oat_filename(GetArtCacheFilenameOrDie(OatFile::DexFilenameToOatFilename(filename)));
559
560 // fork and exec dex2oat
561 pid_t pid = fork();
562 if (pid == 0) {
563 std::string boot_image_option("--boot-image=");
564 boot_image_option += Heap::GetSpaces()[0]->GetImageFilename();
565
566 std::string dex_file_option("--dex-file=");
567 dex_file_option += filename;
568
569 std::string oat_file_option("--oat=");
570 oat_file_option += oat_filename;
571
Elliott Hughes234da572011-11-03 22:13:06 -0700572 std::string dex2oat("/system/bin/dex2oat");
573#ifndef NDEBUG
574 dex2oat += 'd';
575#endif
576
577 execl(dex2oat.c_str(), dex2oat.c_str(),
jeffhao5d840402011-10-24 17:09:45 -0700578 "--runtime-arg", "-Xms64m",
579 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500580 "--runtime-arg", "-classpath",
581 "--runtime-arg", Runtime::Current()->GetClassPath().c_str(),
jeffhao262bf462011-10-20 18:36:32 -0700582 boot_image_option.c_str(),
583 dex_file_option.c_str(),
584 oat_file_option.c_str(),
585 NULL);
586
587 PLOG(FATAL) << "execl(dex2oatd) failed";
588 return NULL;
589 } else {
590 // wait for dex2oat to finish
591 int status;
592 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
593 if (got_pid != pid) {
594 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
595 return NULL;
596 }
597 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
598 LOG(ERROR) << "dex2oatd failed with dex-file=" << filename;
599 return NULL;
600 }
601 }
602 return OatFile::Open(oat_filename, "", NULL);
603}
604
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700605OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700606 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700607 const Runtime* runtime = Runtime::Current();
608 if (runtime->IsVerboseStartup()) {
609 LOG(INFO) << "ClassLinker::OpenOat entering";
610 }
611 const ImageHeader& image_header = space->GetImageHeader();
612 String* oat_location = image_header.GetImageRoot(ImageHeader::kOatLocation)->AsString();
613 std::string oat_filename;
614 oat_filename += runtime->GetHostPrefix();
615 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700616 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700617 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700618 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700619 return NULL;
620 }
621 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
622 uint32_t image_oat_checksum = image_header.GetOatChecksum();
623 if (oat_checksum != image_oat_checksum) {
624 LOG(ERROR) << "Failed to match oat filechecksum " << std::hex << oat_checksum
625 << " to expected oat checksum " << std::hex << oat_checksum
626 << " in image";
627 return NULL;
628 }
629 oat_files_.push_back(oat_file);
630 if (runtime->IsVerboseStartup()) {
631 LOG(INFO) << "ClassLinker::OpenOat exiting";
632 }
633 return oat_file;
634}
635
Brian Carlstromaded5f72011-10-07 17:15:04 -0700636const OatFile* ClassLinker::FindOatFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700637 MutexLock mu(dex_lock_);
jeffhao262bf462011-10-20 18:36:32 -0700638 const OatFile* oat_file = FindOatFile(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
639 if (oat_file != NULL) {
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700640 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
641 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
642 return oat_file;
643 }
644 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
645 << " is older than " << dex_file.GetLocation() << " --- regenerating";
Elliott Hughes234da572011-11-03 22:13:06 -0700646 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
647 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
648 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700649 // Fall through...
jeffhao262bf462011-10-20 18:36:32 -0700650 }
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700651 // Generate oat file if it wasn't found or was obsolete.
jeffhao262bf462011-10-20 18:36:32 -0700652 oat_file = GenerateOatFile(dex_file.GetLocation());
653 if (oat_file == NULL) {
654 LOG(ERROR) << "Failed to generate oat file from dex file " << dex_file.GetLocation();
655 return NULL;
656 }
657 oat_files_.push_back(oat_file);
658 return oat_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700659}
660
Brian Carlstromfad71432011-10-16 20:25:10 -0700661const OatFile* ClassLinker::FindOpenedOatFile(const std::string& location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700662 for (size_t i = 0; i < oat_files_.size(); i++) {
663 const OatFile* oat_file = oat_files_[i];
664 DCHECK(oat_file != NULL);
665 if (oat_file->GetLocation() == location) {
666 return oat_file;
667 }
668 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700669 return NULL;
670}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700671
Brian Carlstromfad71432011-10-16 20:25:10 -0700672const OatFile* ClassLinker::FindOatFile(const std::string& location) {
673 const OatFile* oat_file = FindOpenedOatFile(location);
674 if (oat_file != NULL) {
675 return oat_file;
676 }
677
678 oat_file = OatFile::Open(location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700679 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700680 if (location.empty() || location[0] != '/') {
681 LOG(ERROR) << "Failed to open oat file from " << location;
682 return NULL;
683 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700684
Brian Carlstroma9f19782011-10-13 00:14:47 -0700685 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
jeffhao262bf462011-10-20 18:36:32 -0700686 std::string cache_location = GetArtCacheFilenameOrDie(location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700687 oat_file = FindOpenedOatFile(cache_location);
688 if (oat_file != NULL) {
689 return oat_file;
690 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700691 oat_file = OatFile::Open(cache_location, "", NULL);
692 if (oat_file == NULL) {
jeffhao262bf462011-10-20 18:36:32 -0700693 LOG(INFO) << "Failed to open oat file from " << location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700694 return NULL;
695 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700696 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700697
698 CHECK(oat_file != NULL) << location;
699 oat_files_.push_back(oat_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700700 return oat_file;
701}
702
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700703void ClassLinker::InitFromImage() {
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700704 const Runtime* runtime = Runtime::Current();
705 if (runtime->IsVerboseStartup()) {
706 LOG(INFO) << "ClassLinker::InitFromImage entering";
707 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700708 CHECK(!init_done_);
709
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700710 const std::vector<Space*>& spaces = Heap::GetSpaces();
711 for (size_t i = 0; i < spaces.size(); i++) {
712 Space* space = spaces[i] ;
713 if (space->IsImageSpace()) {
714 OatFile* oat_file = OpenOat(space);
715 CHECK(oat_file != NULL) << "Failed to open oat file for image";
716 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
717 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
718
719 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
720 static_cast<uint32_t>(dex_caches->GetLength()));
721 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700722 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700723 const std::string& dex_file_location = dex_cache->GetLocation()->ToModifiedUtf8();
724
725 std::string dex_filename;
726 dex_filename += runtime->GetHostPrefix();
727 dex_filename += dex_file_location;
728 const DexFile* dex_file = DexFile::Open(dex_filename, runtime->GetHostPrefix());
729 if (dex_file == NULL) {
730 LOG(FATAL) << "Failed to open dex file " << dex_filename
731 << " referenced from oat file as " << dex_file_location;
732 }
733
Brian Carlstromaded5f72011-10-07 17:15:04 -0700734 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
735 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700736
Brian Carlstromdf143242011-10-10 18:05:34 -0700737 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700738 }
739 }
740 }
741
Brian Carlstroma663ea52011-08-19 23:33:41 -0700742 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
743 DCHECK(heap_bitmap != NULL);
744
Brian Carlstroma663ea52011-08-19 23:33:41 -0700745 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700746 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700747
748 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700749 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
750 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700751
Elliott Hughes92f14b22011-10-06 12:29:54 -0700752 // reinit array_interfaces_ and array_iftable_ from any array class instance, they should all be ==
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700753 array_interfaces_ = GetClassRoot(kObjectArrayClass)->GetInterfaces();
754 DCHECK(array_interfaces_ == GetClassRoot(kBooleanArrayClass)->GetInterfaces());
Elliott Hughes92f14b22011-10-06 12:29:54 -0700755 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
756 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700757
Brian Carlstroma663ea52011-08-19 23:33:41 -0700758 String::SetClass(GetClassRoot(kJavaLangString));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700759 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700760 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700761 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
762 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
763 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
764 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
765 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
766 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
767 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
768 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700769 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700770 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700771
772 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700773
774 if (runtime->IsVerboseStartup()) {
775 LOG(INFO) << "ClassLinker::InitFromImage exiting";
776 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700777}
778
Brian Carlstrom78128a62011-09-15 17:21:19 -0700779void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700780 DCHECK(obj != NULL);
781 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700782 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700783
Elliott Hughesdbb40792011-11-18 17:05:22 -0800784 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700785 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700786 return;
787 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700788 if (obj->IsClass()) {
789 // restore class to ClassLinker::classes_ table
790 Class* klass = obj->AsClass();
791 std::string descriptor = klass->GetDescriptor()->ToModifiedUtf8();
Ian Rogers5d76c432011-10-31 21:42:49 -0700792 bool success = class_linker->InsertClass(descriptor, klass, true);
793 DCHECK(success);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700794 return;
795 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700796}
797
798// Keep in sync with InitCallback. Anything we visit, we need to
799// reinit references to when reinitializing a ClassLinker from a
800// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700801void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
802 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700803
804 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700805 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700806 }
807
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700808 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700809 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700810 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700811 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700812 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700813 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700814 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700815 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700816
Elliott Hughes410c0c82011-09-01 17:58:25 -0700817 visitor(array_interfaces_, arg);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700818 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700819}
820
Elliott Hughesa2155262011-11-16 16:26:58 -0800821void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
822 MutexLock mu(classes_lock_);
823 typedef Table::const_iterator It; // TODO: C++0x auto
824 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
825 if (!visitor(it->second, arg)) {
826 return;
827 }
828 }
829 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
830 if (!visitor(it->second, arg)) {
831 return;
832 }
833 }
834}
835
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700836ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700837 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700838 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700839 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700840 BooleanArray::ResetArrayClass();
841 ByteArray::ResetArrayClass();
842 CharArray::ResetArrayClass();
843 DoubleArray::ResetArrayClass();
844 FloatArray::ResetArrayClass();
845 IntArray::ResetArrayClass();
846 LongArray::ResetArrayClass();
847 ShortArray::ResetArrayClass();
848 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700849 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700850 STLDeleteElements(&boot_class_path_);
851 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700852}
853
854DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700855 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
856 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700857 return NULL;
858 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700859 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
860 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700861 return NULL;
862 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700863 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
864 if (strings.get() == NULL) {
865 return NULL;
866 }
867 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
868 if (types.get() == NULL) {
869 return NULL;
870 }
871 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
872 if (methods.get() == NULL) {
873 return NULL;
874 }
875 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
876 if (fields.get() == NULL) {
877 return NULL;
878 }
879 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
880 if (code_and_direct_methods.get() == NULL) {
881 return NULL;
882 }
883 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
884 if (initialized_static_storage.get() == NULL) {
885 return NULL;
886 }
887
888 dex_cache->Init(location.get(),
889 strings.get(),
890 types.get(),
891 methods.get(),
892 fields.get(),
893 code_and_direct_methods.get(),
894 initialized_static_storage.get());
895 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -0700896}
897
Brian Carlstrom9cc262e2011-08-28 12:45:30 -0700898CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
899 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -0700900}
901
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700902InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
903 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700904 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
905 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700906 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700907 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700908}
909
Brian Carlstrom4873d462011-08-21 15:23:39 -0700910Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
911 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700912 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700913 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700914 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700915 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700916}
917
Brian Carlstrom4873d462011-08-21 15:23:39 -0700918Class* ClassLinker::AllocClass(size_t class_size) {
919 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -0700920}
921
Jesse Wilson35baaab2011-08-10 16:18:03 -0400922Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700923 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -0700924}
925
926Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -0700927 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700928}
929
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700930ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
931 return ObjectArray<StackTraceElement>::Alloc(
932 GetClassRoot(kJavaLangStackTraceElementArrayClass),
933 length);
934}
935
Brian Carlstromaded5f72011-10-07 17:15:04 -0700936Class* EnsureResolved(Class* klass) {
937 DCHECK(klass != NULL);
938 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -0700939 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700940 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700941 ObjectLock lock(klass);
942 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700943 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -0700944 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700945 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700946 return NULL;
947 }
948 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -0700949 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700950 lock.Wait();
951 }
952 }
953 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700954 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -0700955 return NULL;
956 }
957 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -0700958 CHECK(klass->IsResolved()) << PrettyClass(klass);
959 CHECK(!self->IsExceptionPending())
960 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
961 return klass;
962}
963
964Class* ClassLinker::FindClass(const std::string& descriptor,
965 const ClassLoader* class_loader) {
966 CHECK_NE(descriptor.size(), 0U);
967 Thread* self = Thread::Current();
968 DCHECK(self != NULL);
969 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
970 // Find the class in the loaded classes table.
971 Class* klass = LookupClass(descriptor, class_loader);
972 if (klass != NULL) {
973 return EnsureResolved(klass);
974 }
975 if (descriptor.size() == 1) {
976 // only the descriptors of primitive types should be 1 character long
977 return FindPrimitiveClass(descriptor[0]);
978 }
979 // Class is not yet loaded.
980 if (descriptor[0] == '[') {
981 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700982
Jesse Wilson47daf872011-11-23 11:42:45 -0500983 } else if (class_loader == NULL) {
984 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
985 if (pair.second != NULL) {
986 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
987 }
988
989 } else if (ClassLoader::UseCompileTimeClassPath()) {
990 // first try the boot class path
991 Class* system_class = FindSystemClass(descriptor);
992 if (system_class != NULL) {
993 return system_class;
994 }
995 CHECK(self->IsExceptionPending());
996 self->ClearException();
997
998 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -0700999 const std::vector<const DexFile*>& class_path
1000 = ClassLoader::GetCompileTimeClassPath(class_loader);
1001 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001002 if (pair.second != NULL) {
1003 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001004 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001005
1006 } else {
1007 std::string class_name_string = DescriptorToDot(descriptor);
1008 ScopedThreadStateChange(self, Thread::kNative);
1009 JNIEnv* env = self->GetJniEnv();
1010 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1011 CHECK(c.get() != NULL);
1012 // TODO: cache method?
1013 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1014 CHECK(mid != NULL);
1015 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1016 if (class_name_object.get() == NULL) {
1017 return NULL;
1018 }
1019 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
1020 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid, class_name_object.get()));
1021 return Decode<Class*>(env, result.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001022 }
1023
Jesse Wilson47daf872011-11-23 11:42:45 -05001024 ThrowNoClassDefFoundError("Class %s not found", PrintableString(descriptor).c_str());
1025 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001026}
1027
1028Class* ClassLinker::DefineClass(const std::string& descriptor,
1029 const ClassLoader* class_loader,
1030 const DexFile& dex_file,
1031 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001032 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001033 // Load the class from the dex file.
1034 if (!init_done_) {
1035 // finish up init of hand crafted class_roots_
1036 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001037 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001038 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001039 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001040 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001041 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001042 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001043 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001044 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001045 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001046 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001047 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001048 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001049 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001050 }
1051 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001052 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001053 }
1054 klass->SetDexCache(FindDexCache(dex_file));
1055 LoadClass(dex_file, dex_class_def, klass, class_loader);
1056 // Check for a pending exception during load
1057 Thread* self = Thread::Current();
1058 if (self->IsExceptionPending()) {
1059 return NULL;
1060 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001061 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001062 klass->SetClinitThreadId(self->GetTid());
1063 // Add the newly loaded class to the loaded classes table.
Ian Rogers5d76c432011-10-31 21:42:49 -07001064 bool success = InsertClass(descriptor, klass.get(), false); // TODO: just return collision
Brian Carlstromaded5f72011-10-07 17:15:04 -07001065 if (!success) {
1066 // We may fail to insert if we raced with another thread.
1067 klass->SetClinitThreadId(0);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001068 klass.reset(LookupClass(descriptor, class_loader));
1069 CHECK(klass.get() != NULL);
1070 return klass.get();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001071 }
1072 // Finish loading (if necessary) by finding parents
1073 CHECK(!klass->IsLoaded());
1074 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1075 // Loading failed.
1076 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001077 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001078 lock.NotifyAll();
1079 return NULL;
1080 }
1081 CHECK(klass->IsLoaded());
1082 // Link the class (if necessary)
1083 CHECK(!klass->IsResolved());
1084 if (!LinkClass(klass)) {
1085 // Linking failed.
1086 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001087 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001088 lock.NotifyAll();
1089 return NULL;
1090 }
1091 CHECK(klass->IsResolved());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001092 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001093}
1094
Brian Carlstrom4873d462011-08-21 15:23:39 -07001095// Precomputes size that will be needed for Class, matching LinkStaticFields
1096size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1097 const DexFile::ClassDef& dex_class_def) {
1098 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001099 size_t num_ref = 0;
1100 size_t num_32 = 0;
1101 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001102 if (class_data != NULL) {
1103 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1104 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001105 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001106 char c = descriptor[0];
1107 if (c == 'L' || c == '[') {
1108 num_ref++;
1109 } else if (c == 'J' || c == 'D') {
1110 num_64++;
1111 } else {
1112 num_32++;
1113 }
1114 }
1115 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001116 // start with generic class data
1117 size_t size = sizeof(Class);
1118 // follow with reference fields which must be contiguous at start
1119 size += (num_ref * sizeof(uint32_t));
1120 // if there are 64-bit fields to add, make sure they are aligned
1121 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1122 if (num_32 != 0) {
1123 // use an available 32-bit field for padding
1124 num_32--;
1125 }
1126 size += sizeof(uint32_t); // either way, we are adding a word
1127 DCHECK_EQ(size, RoundUp(size, 8));
1128 }
1129 // tack on any 64-bit fields now that alignment is assured
1130 size += (num_64 * sizeof(uint64_t));
1131 // tack on any remaining 32-bit fields
1132 size += (num_32 * sizeof(uint32_t));
1133 return size;
1134}
1135
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001136void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001137 // Every kind of method should at least get an invoke stub from the oat_method.
1138 // non-abstract methods also get their code pointers.
1139 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001140 oat_method.LinkMethod(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001141
1142 if (method->IsAbstract()) {
1143 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1144 return;
1145 }
1146 if (method->IsNative()) {
1147 // unregistering restores the dlsym lookup stub
1148 method->UnregisterNative();
1149 return;
1150 }
1151}
1152
Brian Carlstromf615a612011-07-23 12:50:34 -07001153void ClassLinker::LoadClass(const DexFile& dex_file,
1154 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001155 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001156 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001157 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001158 CHECK(klass->GetDexCache() != NULL);
1159 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001160 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001161 CHECK(descriptor != NULL);
1162
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001163 klass->SetClass(GetClassRoot(kJavaLangClass));
1164 if (klass->GetDescriptor() != NULL) {
1165 DCHECK(klass->GetDescriptor()->Equals(descriptor));
1166 } else {
Brian Carlstromc74255f2011-09-11 22:47:39 -07001167 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001168 if (klass->GetDescriptor() == NULL) {
1169 return;
1170 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001171 }
1172 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001173 // Make sure that none of our runtime-only flags are set.
1174 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001175 klass->SetAccessFlags(access_flags);
1176 klass->SetClassLoader(class_loader);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001177 DCHECK(klass->GetPrimitiveType() == Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001178 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001179
jeffhao64155032011-11-03 17:56:34 -07001180 klass->SetTypeIdx(dex_class_def.class_idx_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001181 klass->SetSuperClassTypeIdx(dex_class_def.superclass_idx_);
jeffhao64155032011-11-03 17:56:34 -07001182 klass->SetAnnotationsOffset(dex_class_def.annotations_off_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001183
Ian Rogers0571d352011-11-03 19:51:38 -07001184 const char* source_file = dex_file.GetSourceFile(dex_class_def);
Jesse Wilson6384f642011-10-07 18:08:35 -04001185 if (source_file != NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -07001186 String* source_file_string = intern_table_->InternStrong(source_file);
1187 if (source_file_string == NULL) {
1188 return;
1189 }
1190 klass->SetSourceFile(source_file_string);
Jesse Wilson6384f642011-10-07 18:08:35 -04001191 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001192
1193 // Load class interfaces.
Brian Carlstromf615a612011-07-23 12:50:34 -07001194 LoadInterfaces(dex_file, dex_class_def, klass);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001195
Ian Rogers0571d352011-11-03 19:51:38 -07001196 // Load fields fields.
1197 const byte* class_data = dex_file.GetClassData(dex_class_def);
1198 if (class_data == NULL) {
1199 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001200 }
Ian Rogers0571d352011-11-03 19:51:38 -07001201 ClassDataItemIterator it(dex_file, class_data);
1202 if (it.NumStaticFields() != 0) {
1203 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1204 }
1205 if (it.NumInstanceFields() != 0) {
1206 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1207 }
1208 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1209 SirtRef<Field> sfield(AllocField());
1210 klass->SetStaticField(i, sfield.get());
1211 LoadField(dex_file, it, klass, sfield);
1212 }
1213 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1214 SirtRef<Field> ifield(AllocField());
1215 klass->SetInstanceField(i, ifield.get());
1216 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001217 }
1218
Brian Carlstromaded5f72011-10-07 17:15:04 -07001219 UniquePtr<const OatFile::OatClass> oat_class;
1220 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
1221 const OatFile* oat_file = FindOatFile(dex_file);
1222 if (oat_file != NULL) {
1223 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1224 if (oat_dex_file != NULL) {
1225 uint32_t class_def_index;
1226 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1227 CHECK(found) << descriptor;
1228 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001229 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001230 }
1231 }
1232 }
Ian Rogers0571d352011-11-03 19:51:38 -07001233 // Load methods.
1234 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001235 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001236 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001237 }
Ian Rogers0571d352011-11-03 19:51:38 -07001238 if (it.NumVirtualMethods() != 0) {
1239 // TODO: append direct methods to class object
1240 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001241 }
Ian Rogers0571d352011-11-03 19:51:38 -07001242 size_t method_index = 0;
1243 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1244 SirtRef<Method> method(AllocMethod());
1245 klass->SetDirectMethod(i, method.get());
1246 LoadMethod(dex_file, it, klass, method);
1247 if (oat_class.get() != NULL) {
1248 LinkCode(method, oat_class.get(), method_index);
1249 }
1250 method_index++;
1251 }
1252 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1253 SirtRef<Method> method(AllocMethod());
1254 klass->SetVirtualMethod(i, method.get());
1255 LoadMethod(dex_file, it, klass, method);
1256 if (oat_class.get() != NULL) {
1257 LinkCode(method, oat_class.get(), method_index);
1258 }
1259 method_index++;
1260 }
1261 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001262}
1263
Brian Carlstromf615a612011-07-23 12:50:34 -07001264void ClassLinker::LoadInterfaces(const DexFile& dex_file,
1265 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001266 SirtRef<Class>& klass) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001267 const DexFile::TypeList* list = dex_file.GetInterfacesList(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001268 if (list != NULL) {
Elliott Hughes418d20f2011-09-22 14:00:39 -07001269 klass->SetInterfaces(AllocClassArray(list->Size()));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001270 IntArray* interfaces_idx = IntArray::Alloc(list->Size());
1271 klass->SetInterfacesTypeIdx(interfaces_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001272 for (size_t i = 0; i < list->Size(); ++i) {
Brian Carlstromf615a612011-07-23 12:50:34 -07001273 const DexFile::TypeItem& type_item = list->GetTypeItem(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001274 interfaces_idx->Set(i, type_item.type_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001275 }
1276 }
1277}
1278
Ian Rogers0571d352011-11-03 19:51:38 -07001279void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1280 SirtRef<Class>& klass, SirtRef<Field>& dst) {
1281 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001282 dst->SetDeclaringClass(klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001283 dst->SetName(ResolveString(dex_file, field_id.name_idx_, klass->GetDexCache()));
1284 dst->SetTypeIdx(field_id.type_idx_);
Ian Rogers0571d352011-11-03 19:51:38 -07001285 dst->SetAccessFlags(it.GetMemberAccessFlags());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001286
1287 // In order to access primitive types using GetTypeDuringLinking we need to
1288 // ensure they are resolved into the dex cache
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001289 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001290 if (descriptor[1] == '\0') {
1291 // only the descriptors of primitive types should be 1 character long
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001292 Class* resolved = ResolveType(dex_file, field_id.type_idx_, klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001293 DCHECK(resolved->IsPrimitive());
1294 }
Brian Carlstrom934486c2011-07-12 23:42:50 -07001295}
1296
Ian Rogers0571d352011-11-03 19:51:38 -07001297void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1298 SirtRef<Class>& klass, SirtRef<Method>& dst) {
1299 const DexFile::MethodId& method_id = dex_file.GetMethodId(it.GetMemberIndex());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001300 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001301
Elliott Hughes80609252011-09-23 17:24:51 -07001302 String* method_name = ResolveString(dex_file, method_id.name_idx_, klass->GetDexCache());
Elliott Hughes30646832011-10-13 16:59:46 -07001303 if (method_name == NULL) {
1304 return;
1305 }
Elliott Hughes80609252011-09-23 17:24:51 -07001306 dst->SetName(method_name);
1307 if (method_name->Equals("<init>")) {
1308 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1309 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001310
1311 int32_t utf16_length;
Ian Rogers0571d352011-11-03 19:51:38 -07001312 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, &utf16_length));
Elliott Hughes30646832011-10-13 16:59:46 -07001313 String* signature_string = intern_table_->InternStrong(utf16_length, signature.c_str());
1314 if (signature_string == NULL) {
1315 return;
1316 }
1317 dst->SetSignature(signature_string);
Elliott Hughes20cde902011-10-04 17:37:27 -07001318
1319 if (method_name->Equals("finalize") && signature == "()V") {
1320 /*
1321 * The Enum class declares a "final" finalize() method to prevent subclasses from introducing
1322 * a finalizer. We don't want to set the finalizable flag for Enum or its subclasses, so we
1323 * exclude it here.
1324 *
1325 * We also want to avoid setting the flag on Object, where we know that finalize() is empty.
1326 */
1327 if (klass->GetClassLoader() != NULL ||
1328 (!klass->GetDescriptor()->Equals("Ljava/lang/Object;") &&
1329 !klass->GetDescriptor()->Equals("Ljava/lang/Enum;"))) {
1330 klass->SetFinalizable();
1331 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001332 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001333
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001334 dst->SetProtoIdx(method_id.proto_idx_);
Ian Rogers0571d352011-11-03 19:51:38 -07001335 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001336 const char* shorty = dex_file.GetShorty(method_id.proto_idx_);
Elliott Hughes30646832011-10-13 16:59:46 -07001337 String* shorty_string = intern_table_->InternStrong(shorty);
1338 dst->SetShorty(shorty_string);
1339 if (shorty_string == NULL) {
1340 return;
1341 }
Ian Rogers0571d352011-11-03 19:51:38 -07001342 dst->SetAccessFlags(it.GetMemberAccessFlags());
Ian Rogers9074b992011-10-26 17:41:55 -07001343 uint32_t return_type_idx = dex_file.GetProtoId(method_id.proto_idx_).return_type_idx_;
1344 DCHECK_LT(return_type_idx, dex_file.NumTypeIds());
1345 dst->SetReturnTypeIdx(return_type_idx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001346
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001347 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1348 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1349 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1350 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1351 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1352 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001353
Brian Carlstrom934486c2011-07-12 23:42:50 -07001354 // TODO: check for finalize method
1355
Ian Rogers0571d352011-11-03 19:51:38 -07001356 const DexFile::CodeItem* code_item = it.GetMethodCodeItem();
Brian Carlstrom934486c2011-07-12 23:42:50 -07001357 if (code_item != NULL) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001358 dst->SetNumRegisters(code_item->registers_size_);
1359 dst->SetNumIns(code_item->ins_size_);
1360 dst->SetNumOuts(code_item->outs_size_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001361 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001362 uint16_t num_args = Method::NumArgRegisters(shorty);
Ian Rogersa3760aa2011-11-14 14:32:37 -08001363 if ((it.GetMemberAccessFlags() & kAccStatic) == 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001364 ++num_args;
1365 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001366 dst->SetNumRegisters(num_args);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001367 // TODO: native methods
1368 }
1369}
1370
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001371void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001372 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1373 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001374}
1375
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001376void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1377 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001378 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001379 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001380}
1381
Brian Carlstromaded5f72011-10-07 17:15:04 -07001382bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001383 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001384 for (size_t i = 0; i != dex_files_.size(); ++i) {
1385 if (dex_files_[i] == &dex_file) {
1386 return true;
1387 }
1388 }
1389 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001390}
1391
Brian Carlstromaded5f72011-10-07 17:15:04 -07001392bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001393 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001394 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001395}
1396
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001397void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001398 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001399 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001400 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001401 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001402 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001403}
1404
Brian Carlstromaded5f72011-10-07 17:15:04 -07001405void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001406 {
1407 MutexLock mu(dex_lock_);
1408 if (IsDexFileRegisteredLocked(dex_file)) {
1409 return;
1410 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001411 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001412 // Don't alloc while holding the lock, since allocation may need to
1413 // suspend all threads and another thread may need the dex_lock_ to
1414 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001415 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001416 {
1417 MutexLock mu(dex_lock_);
1418 if (IsDexFileRegisteredLocked(dex_file)) {
1419 return;
1420 }
1421 RegisterDexFileLocked(dex_file, dex_cache);
1422 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001423}
1424
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001425void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001426 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001427 RegisterDexFileLocked(dex_file, dex_cache);
1428}
1429
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001430const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001431 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001432 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001433 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1434 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001435 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001436 }
1437 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001438 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001439 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001440}
1441
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001442DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001443 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001444 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001445 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001446 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001447 }
1448 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001449 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001450 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001451}
1452
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001453Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1454 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001455 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001456 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001457 CHECK(primitive_class != NULL);
1458 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
1459 primitive_class->SetDescriptor(intern_table_->InternStrong(descriptor));
Elliott Hughes30646832011-10-13 16:59:46 -07001460 CHECK(primitive_class->GetDescriptor() != NULL);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001461 primitive_class->SetPrimitiveType(type);
1462 primitive_class->SetStatus(Class::kStatusInitialized);
Ian Rogers5d76c432011-10-31 21:42:49 -07001463 bool success = InsertClass(descriptor, primitive_class, false);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001464 CHECK(success) << "InitPrimitiveClass(" << descriptor << ") failed";
1465 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001466}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001467
Brian Carlstrombe977852011-07-19 14:54:54 -07001468// Create an array class (i.e. the class object for the array, not the
1469// array itself). "descriptor" looks like "[C" or "[[[[B" or
1470// "[Ljava/lang/String;".
1471//
1472// If "descriptor" refers to an array of primitives, look up the
1473// primitive type's internally-generated class object.
1474//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001475// "class_loader" is the class loader of the class that's referring to
1476// us. It's used to ensure that we're looking for the element type in
1477// the right context. It does NOT become the class loader for the
1478// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001479//
1480// Returns NULL with an exception raised on failure.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001481Class* ClassLinker::CreateArrayClass(const std::string& descriptor,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001482 const ClassLoader* class_loader) {
1483 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001484
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001485 // Identify the underlying component type
1486 Class* component_type = FindClass(descriptor.substr(1), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001487 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001488 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001489 return NULL;
1490 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001491
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001492 // See if the component type is already loaded. Array classes are
1493 // always associated with the class loader of their underlying
1494 // element type -- an array of Strings goes with the loader for
1495 // java/lang/String -- so we need to look for it there. (The
1496 // caller should have checked for the existence of the class
1497 // before calling here, but they did so with *their* class loader,
1498 // not the component type's loader.)
1499 //
1500 // If we find it, the caller adds "loader" to the class' initiating
1501 // loader list, which should prevent us from going through this again.
1502 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001503 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001504 // are the same, because our caller (FindClass) just did the
1505 // lookup. (Even if we get this wrong we still have correct behavior,
1506 // because we effectively do this lookup again when we add the new
1507 // class to the hash table --- necessary because of possible races with
1508 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001509 if (class_loader != component_type->GetClassLoader()) {
1510 Class* new_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001511 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001512 return new_class;
1513 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001514 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001515
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001516 // Fill out the fields in the Class.
1517 //
1518 // It is possible to execute some methods against arrays, because
1519 // all arrays are subclasses of java_lang_Object_, so we need to set
1520 // up a vtable. We can just point at the one in java_lang_Object_.
1521 //
1522 // Array classes are simple enough that we don't need to do a full
1523 // link step.
1524
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001525 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001526 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001527 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001528 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001529 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001530 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001531 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001532 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001533 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001534 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001535 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001536 }
1537 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001538 if (new_class.get() == NULL) {
1539 new_class.reset(AllocClass(sizeof(Class)));
1540 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001541 return NULL;
1542 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001543 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001544 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001545 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom693267a2011-09-06 09:25:34 -07001546 if (new_class->GetDescriptor() != NULL) {
1547 DCHECK(new_class->GetDescriptor()->Equals(descriptor));
1548 } else {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001549 new_class->SetDescriptor(intern_table_->InternStrong(descriptor.c_str()));
Elliott Hughes30646832011-10-13 16:59:46 -07001550 if (new_class->GetDescriptor() == NULL) {
1551 return NULL;
1552 }
Brian Carlstrom693267a2011-09-06 09:25:34 -07001553 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001554 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001555 new_class->SetSuperClass(java_lang_Object);
1556 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001557 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001558 new_class->SetClassLoader(component_type->GetClassLoader());
1559 new_class->SetStatus(Class::kStatusInitialized);
1560 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001561 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001562
1563
1564 // All arrays have java/lang/Cloneable and java/io/Serializable as
1565 // interfaces. We need to set that up here, so that stuff like
1566 // "instanceof" works right.
1567 //
1568 // Note: The GC could run during the call to FindSystemClass,
1569 // so we need to make sure the class object is GC-valid while we're in
1570 // there. Do this by clearing the interface list so the GC will just
1571 // think that the entries are null.
1572
1573
1574 // Use the single, global copies of "interfaces" and "iftable"
1575 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001576 CHECK(array_interfaces_ != NULL);
1577 CHECK(array_iftable_ != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001578 new_class->SetInterfaces(array_interfaces_);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001579 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001580
1581 // Inherit access flags from the component type. Arrays can't be
1582 // used as a superclass or interface, so we want to add "final"
1583 // and remove "interface".
1584 //
1585 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001586 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001587 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001588 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1589 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001590
Ian Rogers5d76c432011-10-31 21:42:49 -07001591 if (InsertClass(descriptor, new_class.get(), false)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001592 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001593 }
1594 // Another thread must have loaded the class after we
1595 // started but before we finished. Abandon what we've
1596 // done.
1597 //
1598 // (Yes, this happens.)
1599
1600 // Grab the winning class.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001601 Class* other_class = LookupClass(descriptor, component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001602 DCHECK(other_class != NULL);
1603 return other_class;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001604}
1605
1606Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001607 switch (Primitive::GetType(type)) {
1608 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001609 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001610 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001611 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001612 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001613 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001614 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001615 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001616 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001617 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001618 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001619 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001620 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001621 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001622 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001623 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001624 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001625 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001626 case Primitive::kPrimNot:
1627 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001628 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001629 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001630 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001631 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001632}
1633
Ian Rogers5d76c432011-10-31 21:42:49 -07001634bool ClassLinker::InsertClass(const std::string& descriptor, Class* klass, bool image_class) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001635 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001636 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001637 Table::iterator it;
1638 if (image_class) {
1639 // TODO: sanity check there's no match in classes_
1640 it = image_classes_.insert(std::make_pair(hash, klass));
1641 } else {
1642 // TODO: sanity check there's no match in image_classes_
1643 it = classes_.insert(std::make_pair(hash, klass));
1644 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001645 return ((*it).second == klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001646}
1647
Brian Carlstromaded5f72011-10-07 17:15:04 -07001648Class* ClassLinker::LookupClass(const std::string& descriptor, const ClassLoader* class_loader) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001649 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001650 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001651 typedef Table::const_iterator It; // TODO: C++0x auto
Ian Rogers5d76c432011-10-31 21:42:49 -07001652 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001653 for (It it = classes_.find(hash), end = classes_.end(); it != end; ++it) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001654 Class* klass = it->second;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001655 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001656 return klass;
1657 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001658 }
Ian Rogers5d76c432011-10-31 21:42:49 -07001659 for (It it = image_classes_.find(hash), end = image_classes_.end(); it != end; ++it) {
1660 Class* klass = it->second;
1661 if (klass->GetDescriptor()->Equals(descriptor) && klass->GetClassLoader() == class_loader) {
1662 return klass;
1663 }
1664 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001665 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001666}
1667
jeffhao98eacac2011-09-14 16:11:53 -07001668void ClassLinker::VerifyClass(Class* klass) {
1669 if (klass->IsVerified()) {
1670 return;
1671 }
1672
1673 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved);
jeffhao98eacac2011-09-14 16:11:53 -07001674 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001675
Ian Rogersd81871c2011-10-03 13:57:23 -07001676 if (verifier::DexVerifier::VerifyClass(klass)) {
jeffhao5cfd6fb2011-09-27 13:54:29 -07001677 klass->SetStatus(Class::kStatusVerified);
1678 } else {
1679 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001680 Thread* self = Thread::Current();
1681 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
1682 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
1683 PrettyDescriptor(klass->GetDescriptor()).c_str());
jeffhao5cfd6fb2011-09-27 13:54:29 -07001684 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001685 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001686 }
jeffhao98eacac2011-09-14 16:11:53 -07001687}
1688
Jesse Wilson95caa792011-10-12 18:14:17 -04001689Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers466bb252011-10-14 03:29:56 -07001690 ClassLoader* loader, ObjectArray<Method>* methods, ObjectArray<ObjectArray<Class> >* throws) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001691 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(ProxyClass)));
1692 CHECK(klass.get() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001693 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers466bb252011-10-14 03:29:56 -07001694 const char* descriptor = DotToDescriptor(name->ToModifiedUtf8().c_str()).c_str();;
1695 klass->SetDescriptor(intern_table_->InternStrong(descriptor));
Jesse Wilson95caa792011-10-12 18:14:17 -04001696 klass->SetAccessFlags(kAccPublic | kAccFinal);
1697 klass->SetClassLoader(loader);
Ian Rogers466bb252011-10-14 03:29:56 -07001698 klass->SetStatus(Class::kStatusInitialized); // no loading or initializing necessary
1699 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1700 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1701 klass->SetInterfaces(interfaces); // The interfaces are the array of interfaces specified
Jesse Wilson95caa792011-10-12 18:14:17 -04001702
Ian Rogers466bb252011-10-14 03:29:56 -07001703 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001704 klass->SetDirectMethods(AllocObjectArray<Method>(1));
1705 klass->SetDirectMethod(0, CreateProxyConstructor(klass));
1706
Ian Rogers466bb252011-10-14 03:29:56 -07001707 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001708 size_t num_virtual_methods = methods->GetLength();
1709 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1710 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001711 SirtRef<Method> prototype(methods->Get(i));
Jesse Wilson95caa792011-10-12 18:14:17 -04001712 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype, throws->Get(i)));
1713 }
Ian Rogers466bb252011-10-14 03:29:56 -07001714 // Link the virtual methods, creating vtable and iftables
Jesse Wilson95caa792011-10-12 18:14:17 -04001715 if (!LinkMethods(klass)) {
1716 DCHECK(Thread::Current()->IsExceptionPending());
1717 return NULL;
1718 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001719 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04001720}
1721
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001722Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass) {
Ian Rogers466bb252011-10-14 03:29:56 -07001723 // Create constructor for Proxy that must initialize h
1724 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
1725 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04001726 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07001727 Method* proxy_constructor = proxy_direct_methods->Get(2);
1728 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
1729 // code_ too)
1730 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
1731 // Make this constructor public and fix the class to be our Proxy version
1732 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001733 constructor->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001734 // Sanity checks
1735 CHECK(constructor->IsConstructor());
1736 CHECK(constructor->GetName()->Equals("<init>"));
1737 CHECK(constructor->GetSignature()->Equals("(Ljava/lang/reflect/InvocationHandler;)V"));
1738 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04001739 return constructor;
1740}
1741
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001742Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype,
Ian Rogers466bb252011-10-14 03:29:56 -07001743 ObjectArray<Class>* throws) {
1744 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialise
1745 // as necessary
1746 Method* method = down_cast<Method*>(prototype->Clone());
1747
1748 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
1749 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001750 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07001751 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001752 method->SetExceptionTypes(throws);
1753
Ian Rogers466bb252011-10-14 03:29:56 -07001754 // At runtime the method looks like a reference and argument saving method, clone the code
1755 // related parameters from this method.
1756 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
1757 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
1758 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
1759 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
1760 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Jesse Wilson95caa792011-10-12 18:14:17 -04001761
Ian Rogers466bb252011-10-14 03:29:56 -07001762 // Basic sanity
1763 DCHECK(method->GetName()->Equals(prototype->GetName()));
1764 DCHECK(method->GetSignature()->Equals(prototype->GetSignature()));
1765 DCHECK(method->GetShorty()->Equals(prototype->GetShorty()));
1766
1767 // More complex sanity - via dex cache
1768 CHECK_EQ(method->GetReturnType(), prototype->GetReturnType());
Jesse Wilson95caa792011-10-12 18:14:17 -04001769
1770 return method;
1771}
1772
Brian Carlstrom25c33252011-09-18 15:58:35 -07001773bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001774 CHECK(klass->IsResolved() || klass->IsErroneous())
1775 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001776
Carl Shapirob5573532011-07-12 18:22:59 -07001777 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001778
Brian Carlstrom25c33252011-09-18 15:58:35 -07001779 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001780 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001781 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001782 ObjectLock lock(klass);
1783
Brian Carlstromd1422f82011-09-28 11:37:09 -07001784 if (klass->GetStatus() == Class::kStatusInitialized) {
1785 return true;
1786 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001787
Brian Carlstromd1422f82011-09-28 11:37:09 -07001788 if (klass->IsErroneous()) {
1789 ThrowEarlierClassFailure(klass);
1790 return false;
1791 }
1792
1793 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07001794 VerifyClass(klass);
1795 if (klass->GetStatus() != Class::kStatusVerified) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001796 return false;
1797 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001798 }
1799
Brian Carlstrom25c33252011-09-18 15:58:35 -07001800 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
1801 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001802 // if the class has a <clinit> but we can't run it during compilation,
1803 // don't bother going to kStatusInitializing
Brian Carlstrom25c33252011-09-18 15:58:35 -07001804 return false;
1805 }
1806
Brian Carlstromd1422f82011-09-28 11:37:09 -07001807 // If the class is kStatusInitializing, either this thread is
1808 // initializing higher up the stack or another thread has beat us
1809 // to initializing and we need to wait. Either way, this
1810 // invocation of InitializeClass will not be responsible for
1811 // running <clinit> and will return.
1812 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07001813 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07001814 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07001815 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001816 return true;
1817 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07001818 // No. That's fine. Wait for another thread to finish initializing.
1819 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001820 }
1821
1822 if (!ValidateSuperClassDescriptors(klass)) {
1823 klass->SetStatus(Class::kStatusError);
1824 return false;
1825 }
1826
Brian Carlstromd1422f82011-09-28 11:37:09 -07001827 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001828
Elliott Hughesdcc24742011-09-07 14:02:44 -07001829 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001830 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001831 }
1832
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001833 uint64_t t0 = NanoTime();
1834
Brian Carlstrom25c33252011-09-18 15:58:35 -07001835 if (!InitializeSuperClass(klass, can_run_clinit)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001836 return false;
1837 }
1838
1839 InitializeStaticFields(klass);
1840
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001841 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07001842 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001843 }
1844
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001845 uint64_t t1 = NanoTime();
1846
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001847 {
1848 ObjectLock lock(klass);
1849
1850 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001851 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001852 klass->SetStatus(Class::kStatusError);
1853 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07001854 RuntimeStats* global_stats = Runtime::Current()->GetStats();
1855 RuntimeStats* thread_stats = self->GetStats();
1856 ++global_stats->class_init_count;
1857 ++thread_stats->class_init_count;
1858 global_stats->class_init_time_ns += (t1 - t0);
1859 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001860 klass->SetStatus(Class::kStatusInitialized);
1861 }
1862 lock.NotifyAll();
1863 }
1864
1865 return true;
1866}
1867
Brian Carlstromd1422f82011-09-28 11:37:09 -07001868bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
1869 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001870 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001871 lock.Wait();
1872
1873 // When we wake up, repeat the test for init-in-progress. If
1874 // there's an exception pending (only possible if
1875 // "interruptShouldThrow" was set), bail out.
1876 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07001877 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07001878 klass->SetStatus(Class::kStatusError);
1879 return false;
1880 }
1881 // Spurious wakeup? Go back to waiting.
1882 if (klass->GetStatus() == Class::kStatusInitializing) {
1883 continue;
1884 }
1885 if (klass->IsErroneous()) {
1886 // The caller wants an exception, but it was thrown in a
1887 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07001888 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
1889 PrettyDescriptor(klass->GetDescriptor()).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07001890 return false;
1891 }
1892 if (klass->IsInitialized()) {
1893 return true;
1894 }
1895 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
1896 }
1897 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
1898}
1899
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001900bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
1901 if (klass->IsInterface()) {
1902 return true;
1903 }
1904 // begin with the methods local to the superclass
1905 if (klass->HasSuperClass() &&
1906 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
1907 const Class* super = klass->GetSuperClass();
1908 for (int i = super->NumVirtualMethods() - 1; i >= 0; --i) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07001909 const Method* method = super->GetVirtualMethod(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001910 if (method != super->GetVirtualMethod(i) &&
1911 !HasSameMethodDescriptorClasses(method, super, klass)) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001912 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1913
1914 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 -07001915 return false;
1916 }
1917 }
1918 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001919 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
1920 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
1921 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001922 if (klass->GetClassLoader() != interface->GetClassLoader()) {
1923 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001924 const Method* method = interface_entry->GetMethodArray()->Get(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001925 if (!HasSameMethodDescriptorClasses(method, interface,
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001926 method->GetDeclaringClass())) {
Elliott Hughes4681c802011-09-25 18:04:37 -07001927 klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
1928
1929 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 -07001930 return false;
1931 }
1932 }
1933 }
1934 }
1935 return true;
1936}
1937
1938bool ClassLinker::HasSameMethodDescriptorClasses(const Method* method,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001939 const Class* klass1,
1940 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07001941 if (klass1 == klass2) {
1942 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07001943 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07001944 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001945 const DexFile::ProtoId& proto_id = dex_file.GetProtoId(method->GetProtoIdx());
Ian Rogers0571d352011-11-03 19:51:38 -07001946 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
1947 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001948 if (descriptor == NULL) {
1949 break;
1950 }
1951 if (descriptor[0] == 'L' || descriptor[0] == '[') {
1952 // Found a non-primitive type.
1953 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
1954 return false;
1955 }
1956 }
1957 }
1958 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001959 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001960 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Brian Carlstrome10b6972011-09-26 13:49:03 -07001961 if (!HasSameDescriptorClasses(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001962 return false;
1963 }
1964 }
1965 return true;
1966}
1967
1968// Returns true if classes referenced by the descriptor are the
1969// same classes in klass1 as they are in klass2.
1970bool ClassLinker::HasSameDescriptorClasses(const char* descriptor,
Brian Carlstrom934486c2011-07-12 23:42:50 -07001971 const Class* klass1,
1972 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001973 CHECK(descriptor != NULL);
1974 CHECK(klass1 != NULL);
1975 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07001976 if (klass1 == klass2) {
1977 return true;
1978 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001979 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001980 // TODO: found1 == NULL
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001981 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001982 // TODO: found2 == NULL
1983 // TODO: lookup found1 in initiating loader list
1984 if (found1 == NULL || found2 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07001985 Thread::Current()->ClearException();
Ian Rogers9074b992011-10-26 17:41:55 -07001986 return found1 == found2;
1987 } else {
1988 return true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001989 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001990}
1991
Brian Carlstrom25c33252011-09-18 15:58:35 -07001992bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001993 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001994 if (!klass->IsInterface() && klass->HasSuperClass()) {
1995 Class* super_class = klass->GetSuperClass();
1996 if (super_class->GetStatus() != Class::kStatusInitialized) {
1997 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07001998 Thread* self = Thread::Current();
1999 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002000 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002001 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002002 // TODO: check for a pending exception
2003 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002004 if (!can_run_clinit) {
2005 // Don't set status to error when we can't run <clinit>.
2006 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing);
2007 klass->SetStatus(Class::kStatusVerified);
2008 return false;
2009 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002010 klass->SetStatus(Class::kStatusError);
2011 klass->NotifyAll();
2012 return false;
2013 }
2014 }
2015 }
2016 return true;
2017}
2018
Brian Carlstrom25c33252011-09-18 15:58:35 -07002019bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002020 CHECK(c != NULL);
2021 if (c->IsInitialized()) {
2022 return true;
2023 }
2024
Elliott Hughes5f791332011-09-15 17:45:30 -07002025 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002026 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002027 InitializeClass(c, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002028 return !self->IsExceptionPending();
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002029}
2030
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002031void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002032 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002033 const ClassLoader* cl = c->GetClassLoader();
2034 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002035 ClassDataItemIterator it(dex_file, class_data);
2036 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2037 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002038 }
2039}
2040
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002041void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002042 size_t num_static_fields = klass->NumStaticFields();
2043 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002044 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002045 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002046 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002047 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002048 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002049 return;
2050 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002051 const DexFile& dex_file = FindDexFile(dex_cache);
Ian Rogers0571d352011-11-03 19:51:38 -07002052 const std::string descriptor(klass->GetDescriptor()->ToModifiedUtf8());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002053 const DexFile::ClassDef* dex_class_def = dex_file.FindClassDef(descriptor);
Brian Carlstromf615a612011-07-23 12:50:34 -07002054 CHECK(dex_class_def != NULL);
Ian Rogers0571d352011-11-03 19:51:38 -07002055 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002056
Ian Rogers0571d352011-11-03 19:51:38 -07002057 if (it.HasNext()) {
2058 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2059 std::map<uint32_t, Field*> field_map;
2060 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2061 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2062 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002063 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002064 }
2065}
2066
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002067bool ClassLinker::LinkClass(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002068 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002069 if (!LinkSuperClass(klass)) {
2070 return false;
2071 }
2072 if (!LinkMethods(klass)) {
2073 return false;
2074 }
2075 if (!LinkInstanceFields(klass)) {
2076 return false;
2077 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002078 if (!LinkStaticFields(klass)) {
2079 return false;
2080 }
2081 CreateReferenceInstanceOffsets(klass);
2082 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002083 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2084 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002085 return true;
2086}
2087
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002088bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002089 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers0571d352011-11-03 19:51:38 -07002090 if (klass->GetSuperClassTypeIdx() != DexFile::kDexNoIndex16) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002091 Class* super_class = ResolveType(dex_file, klass->GetSuperClassTypeIdx(), klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002092 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002093 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002094 return false;
2095 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002096 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002097 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002098 for (size_t i = 0; i < klass->NumInterfaces(); ++i) {
2099 uint32_t idx = klass->GetInterfacesTypeIdx()->Get(i);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002100 Class* interface = ResolveType(dex_file, idx, klass.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002101 klass->SetInterface(i, interface);
2102 if (interface == NULL) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002103 DCHECK(Thread::Current()->IsExceptionPending());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002104 return false;
2105 }
2106 // Verify
2107 if (!klass->CanAccess(interface)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002108 // TODO: the RI seemed to ignore this in my testing.
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002109 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002110 "Interface %s implemented by class %s is inaccessible",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002111 PrettyDescriptor(interface->GetDescriptor()).c_str(),
2112 PrettyDescriptor(klass->GetDescriptor()).c_str());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002113 return false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002114 }
2115 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002116 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002117 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118 return true;
2119}
2120
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002121bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002122 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002123 Class* super = klass->GetSuperClass();
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002124 if (klass->GetDescriptor()->Equals("Ljava/lang/Object;")) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002125 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002126 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002127 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002128 return false;
2129 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002130 return true;
2131 }
2132 if (super == NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002133 ThrowLinkageError("No superclass defined for class %s",
2134 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002135 return false;
2136 }
2137 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002138 if (super->IsFinal() || super->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002139 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002140 "Superclass %s of %s is %s",
2141 PrettyDescriptor(super->GetDescriptor()).c_str(),
2142 PrettyDescriptor(klass->GetDescriptor()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002143 super->IsFinal() ? "declared final" : "an interface");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002144 return false;
2145 }
2146 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002147 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002148 "Superclass %s is inaccessible by %s",
2149 PrettyDescriptor(super->GetDescriptor()).c_str(),
2150 PrettyDescriptor(klass->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002151 return false;
2152 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002153
2154 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2155 if (super->IsFinalizable()) {
2156 klass->SetFinalizable();
2157 }
2158
Elliott Hughes2da50362011-10-10 16:57:08 -07002159 // Inherit reference flags (if any) from the superclass.
2160 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2161 if (reference_flags != 0) {
2162 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2163 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002164 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002165 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002166 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
2167 PrettyDescriptor(klass->GetDescriptor()).c_str());
2168 return false;
2169 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002170
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002171#ifndef NDEBUG
2172 // Ensure super classes are fully resolved prior to resolving fields..
2173 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002174 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002175 super = super->GetSuperClass();
2176 }
2177#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002178 return true;
2179}
2180
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002181// Populate the class vtable and itable. Compute return type indices.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002182bool ClassLinker::LinkMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002183 if (klass->IsInterface()) {
2184 // No vtable.
2185 size_t count = klass->NumVirtualMethods();
2186 if (!IsUint(16, count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002187 ThrowClassFormatError("Too many methods on interface: %d", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002188 return false;
2189 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002190 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002191 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002192 }
jeffhaobdb76512011-09-07 11:43:16 -07002193 // Link interface method tables
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002194 return LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002195 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002196 // Link virtual and interface method tables
2197 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002198 }
2199 return true;
2200}
2201
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002202bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002203 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002204 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2205 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002206 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002207 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002208 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002209 // See if any of our virtual methods override the superclass.
2210 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002211 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002212 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002213 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002214 Method* super_method = vtable->Get(j);
Ian Rogers466bb252011-10-14 03:29:56 -07002215 if (local_method->HasSameNameAndSignature(super_method)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002216 // Verify
2217 if (super_method->IsFinal()) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002218 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002219 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2220 local_method->GetName()->ToModifiedUtf8().c_str(),
2221 PrettyDescriptor(super_method->GetDeclaringClass()->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002222 return false;
2223 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002224 vtable->Set(j, local_method);
2225 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002226 break;
2227 }
2228 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002229 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002230 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002231 vtable->Set(actual_count, local_method);
2232 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002233 actual_count += 1;
2234 }
2235 }
2236 if (!IsUint(16, actual_count)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002237 ThrowClassFormatError("Too many methods defined on class: %d", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002238 return false;
2239 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002240 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002241 CHECK_LE(actual_count, max_count);
2242 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002243 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002244 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002245 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002246 } else {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07002247 CHECK(klass->GetDescriptor()->Equals("Ljava/lang/Object;"));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002248 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002249 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002250 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002251 return false;
2252 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002253 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002254 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002255 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2256 vtable->Set(i, virtual_method);
2257 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002258 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002259 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002260 }
2261 return true;
2262}
2263
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002264bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002265 size_t super_ifcount;
2266 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002267 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002268 } else {
2269 super_ifcount = 0;
2270 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002271 size_t ifcount = super_ifcount;
2272 ifcount += klass->NumInterfaces();
2273 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002274 ifcount += klass->GetInterface(i)->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002275 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002276 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002277 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002278 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002279 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002280 return true;
2281 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002282 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002283 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002284 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2285 for (size_t i = 0; i < super_ifcount; i++) {
2286 iftable->Set(i, AllocInterfaceEntry(super_iftable->Get(i)->GetInterface()));
2287 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288 }
2289 // Flatten the interface inheritance hierarchy.
2290 size_t idx = super_ifcount;
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002291 for (size_t i = 0; i < klass->NumInterfaces(); i++) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002292 Class* interface = klass->GetInterface(i);
2293 DCHECK(interface != NULL);
2294 if (!interface->IsInterface()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002295 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002296 "Class %s implements non-interface class %s",
2297 PrettyDescriptor(klass->GetDescriptor()).c_str(),
2298 PrettyDescriptor(interface->GetDescriptor()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002299 return false;
2300 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002301 // Add this interface.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002302 iftable->Set(idx++, AllocInterfaceEntry(interface));
Elliott Hughes4681c802011-09-25 18:04:37 -07002303 // Add this interface's superinterfaces.
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002304 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2305 iftable->Set(idx++, AllocInterfaceEntry(interface->GetIfTable()->Get(j)->GetInterface()));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002306 }
2307 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002308 klass->SetIfTable(iftable.get());
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002309 CHECK_EQ(idx, ifcount);
Elliott Hughes4681c802011-09-25 18:04:37 -07002310
2311 // If we're an interface, we don't need the vtable pointers, so we're done.
2312 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002313 return true;
2314 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002315 std::vector<Method*> miranda_list;
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002316 for (size_t i = 0; i < ifcount; ++i) {
2317 InterfaceEntry* interface_entry = iftable->Get(i);
2318 Class* interface = interface_entry->GetInterface();
2319 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2320 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002321 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002322 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2323 Method* interface_method = interface->GetVirtualMethod(j);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002324 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002325 // For each method listed in the interface's method list, find the
2326 // matching method in our class's method list. We want to favor the
2327 // subclass over the superclass, which just requires walking
2328 // back from the end of the vtable. (This only matters if the
2329 // superclass defines a private method and this class redefines
2330 // it -- otherwise it would use the same vtable slot. In .dex files
2331 // those don't end up in the virtual method table, so it shouldn't
2332 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002333 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2334 Method* vtable_method = vtable->Get(k);
Ian Rogers466bb252011-10-14 03:29:56 -07002335 if (interface_method->HasSameNameAndSignature(vtable_method)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002336 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002337 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002338 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002339 return false;
2340 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002341 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002342 break;
2343 }
2344 }
2345 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002346 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002347 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers466bb252011-10-14 03:29:56 -07002348 if (miranda_list[mir]->HasSameNameAndSignature(interface_method)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002349 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002350 break;
2351 }
2352 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002353 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002354 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002355 miranda_method.reset(AllocMethod());
2356 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2357 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002358 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002359 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002360 }
2361 }
2362 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002363 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002364 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002365 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002366 klass->SetVirtualMethods((old_method_count == 0)
2367 ? AllocObjectArray<Method>(new_method_count)
2368 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002369
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002370 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2371 CHECK(vtable != NULL);
2372 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002373 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002374 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002375 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002376 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002377 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002378 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2379 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2380 klass->SetVirtualMethod(old_method_count + i, method);
2381 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002382 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002383 // TODO: do not assign to the vtable field until it is fully constructed.
2384 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002385 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002386
2387 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2388 for (int i = 0; i < vtable->GetLength(); ++i) {
2389 CHECK(vtable->Get(i) != NULL);
2390 }
2391
2392// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2393
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002394 return true;
2395}
2396
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002397bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2398 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002399 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002400}
2401
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002402bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2403 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002404 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002405 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002406 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002407 return success;
2408}
2409
Brian Carlstromdbc05252011-09-09 01:59:59 -07002410struct LinkFieldsComparator {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002411 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002412 // First come reference fields, then 64-bit, and finally 32-bit
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002413 Primitive::Type type1 = field1->GetPrimitiveType();
2414 Primitive::Type type2 = field2->GetPrimitiveType();
2415 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2416 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2417 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2418 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002419 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2420 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2421 if (order1 != order2) {
2422 return order1 < order2;
2423 }
2424
2425 // same basic group? then sort by string.
2426 std::string name1 = field1->GetName()->ToModifiedUtf8();
2427 std::string name2 = field2->GetName()->ToModifiedUtf8();
2428 return name1 < name2;
2429 }
2430};
2431
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002432bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002433 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002434 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002435
2436 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002437 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002438
2439 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002440 size_t size;
2441 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002442 if (is_static) {
2443 size = klass->GetClassSize();
2444 field_offset = Class::FieldsOffset();
2445 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002446 Class* super_class = klass->GetSuperClass();
2447 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002448 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002449 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002450 }
2451 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002452 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002453
Brian Carlstromdbc05252011-09-09 01:59:59 -07002454 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002455
Brian Carlstromdbc05252011-09-09 01:59:59 -07002456 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002457 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002458 std::deque<Field*> grouped_and_sorted_fields;
2459 for (size_t i = 0; i < num_fields; i++) {
2460 grouped_and_sorted_fields.push_back(fields->Get(i));
2461 }
2462 std::sort(grouped_and_sorted_fields.begin(),
2463 grouped_and_sorted_fields.end(),
2464 LinkFieldsComparator());
2465
2466 // References should be at the front.
2467 size_t current_field = 0;
2468 size_t num_reference_fields = 0;
2469 for (; current_field < num_fields; current_field++) {
2470 Field* field = grouped_and_sorted_fields.front();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002471 Primitive::Type type = field->GetPrimitiveType();
2472 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002473 if (isPrimitive) {
2474 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002475 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002476 grouped_and_sorted_fields.pop_front();
2477 num_reference_fields++;
2478 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002479 field->SetOffset(field_offset);
2480 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002481 }
2482
2483 // Now we want to pack all of the double-wide fields together. If
2484 // we're not aligned, though, we want to shuffle one 32-bit field
2485 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002486 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002487 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2488 Field* field = grouped_and_sorted_fields[i];
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002489 Primitive::Type type = field->GetPrimitiveType();
2490 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2491 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002492 continue;
2493 }
2494 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002495 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002496 // drop the consumed field
2497 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2498 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002499 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002500 // whether we found a 32-bit field for padding or not, we advance
2501 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002502 }
2503
2504 // Alignment is good, shuffle any double-wide fields forward, and
2505 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002506 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002507 while (!grouped_and_sorted_fields.empty()) {
2508 Field* field = grouped_and_sorted_fields.front();
2509 grouped_and_sorted_fields.pop_front();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002510 Primitive::Type type = field->GetPrimitiveType();
2511 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002512 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002513 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002514 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002515 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002516 ? sizeof(uint64_t)
2517 : sizeof(uint32_t)));
2518 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002519 }
2520
Elliott Hughesadb460d2011-10-05 17:02:34 -07002521 // 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 -07002522 if (!is_static && klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;")) {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002523 // We know there are no non-reference fields in the Reference classes, and we know
2524 // that 'referent' is alphabetically last, so this is easy...
2525 CHECK_EQ(num_reference_fields, num_fields);
2526 CHECK(fields->Get(num_fields - 1)->GetName()->Equals("referent"));
2527 --num_reference_fields;
2528 }
2529
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002530#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002531 // Make sure that all reference fields appear before
2532 // non-reference fields, and all double-wide fields are aligned.
2533 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002534 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002535 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002536 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002537 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002538 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002539 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002540 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2541 }
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002542 Primitive::Type type = field->GetPrimitiveType();
2543 bool is_primitive = type != Primitive::kPrimNot;
Elliott Hughesadb460d2011-10-05 17:02:34 -07002544 if (klass->GetDescriptor()->Equals("Ljava/lang/ref/Reference;") && field->GetName()->Equals("referent")) {
2545 is_primitive = true; // We lied above, so we have to expect a lie here.
2546 }
2547 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002548 if (!seen_non_ref) {
2549 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002550 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002551 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002552 } else {
2553 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002554 }
2555 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002556 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002557 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002558 }
2559#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002560 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002561 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002562 if (is_static) {
2563 klass->SetNumReferenceStaticFields(num_reference_fields);
2564 klass->SetClassSize(size);
2565 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002566 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002567 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002568 klass->SetObjectSize(size);
2569 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002570 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002571 return true;
2572}
2573
2574// Set the bitmap of reference offsets, refOffsets, from the ifields
2575// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002576void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 uint32_t reference_offsets = 0;
2578 Class* super_class = klass->GetSuperClass();
2579 if (super_class != NULL) {
2580 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002581 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002582 if (reference_offsets == CLASS_WALK_SUPER) {
2583 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002584 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002585 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002586 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002587 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002588}
2589
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002590void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002591 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002592}
2593
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002594void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002595 uint32_t reference_offsets) {
2596 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002597 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
2598 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002599 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002600 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002601 // All of the fields that contain object references are guaranteed
2602 // to be at the beginning of the fields list.
2603 for (size_t i = 0; i < num_reference_fields; ++i) {
2604 // Note that byte_offset is the offset from the beginning of
2605 // object, not the offset into instance data
2606 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002607 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002608 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
2609 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
2610 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002611 CHECK_NE(new_bit, 0U);
2612 reference_offsets |= new_bit;
2613 } else {
2614 reference_offsets = CLASS_WALK_SUPER;
2615 break;
2616 }
2617 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002618 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002619 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002620 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002621 } else {
2622 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002623 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002624}
2625
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002626String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07002627 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002628 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002629 if (resolved != NULL) {
2630 return resolved;
2631 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002632 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
2633 int32_t utf16_length = dex_file.GetStringLength(string_id);
2634 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07002635 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002636 dex_cache->SetResolvedString(string_idx, string);
2637 return string;
2638}
2639
2640Class* ClassLinker::ResolveType(const DexFile& dex_file,
2641 uint32_t type_idx,
2642 DexCache* dex_cache,
2643 const ClassLoader* class_loader) {
2644 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002645 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07002646 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07002647 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002648 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05002649 // TODO: we used to throw here if resolved's class loader was not the
2650 // boot class loader. This was to permit different classes with the
2651 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002652 dex_cache->SetResolvedType(type_idx, resolved);
2653 } else {
2654 DCHECK(Thread::Current()->IsExceptionPending());
2655 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002656 }
2657 return resolved;
2658}
2659
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002660Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
2661 uint32_t method_idx,
2662 DexCache* dex_cache,
2663 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002664 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002665 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
2666 if (resolved != NULL) {
2667 return resolved;
2668 }
2669 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2670 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
2671 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002672 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002673 return NULL;
2674 }
2675
Ian Rogers0571d352011-11-03 19:51:38 -07002676 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
2677 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002678 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002679 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07002680 } else if (klass->IsInterface()) {
2681 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002682 } else {
2683 resolved = klass->FindVirtualMethod(name, signature);
2684 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002685 if (resolved != NULL) {
2686 dex_cache->SetResolvedMethod(method_idx, resolved);
2687 } else {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07002688 ThrowNoSuchMethodError(is_direct ? "direct" : "virtual", klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002689 }
2690 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002691}
2692
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002693Field* ClassLinker::ResolveField(const DexFile& dex_file,
2694 uint32_t field_idx,
2695 DexCache* dex_cache,
2696 const ClassLoader* class_loader,
2697 bool is_static) {
2698 Field* resolved = dex_cache->GetResolvedField(field_idx);
2699 if (resolved != NULL) {
2700 return resolved;
2701 }
2702 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
2703 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
2704 if (klass == NULL) {
2705 return NULL;
2706 }
2707
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002708 const char* name = dex_file.GetFieldName(field_id);
2709 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002710 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002711 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002712 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002713 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07002714 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002715 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002716 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002717 } else {
Jesse Wilson47daf872011-11-23 11:42:45 -05002718 // TODO: this check fails when the app class path contains a class from the boot class path
2719 CHECK(Thread::Current()->IsExceptionPending())
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002720 << PrettyClass(klass) << " " << name << " " << type << " " << is_static;
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07002721 }
2722 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002723}
2724
Ian Rogersad25ac52011-10-04 19:13:33 -07002725const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
2726 Class* declaring_class = referrer->GetDeclaringClass();
2727 DexCache* dex_cache = declaring_class->GetDexCache();
2728 const DexFile& dex_file = FindDexFile(dex_cache);
2729 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
2730 return dex_file.GetShorty(method_id.proto_idx_);
2731}
2732
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002733void ClassLinker::DumpAllClasses(int flags) const {
2734 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
2735 // lock held, because it might need to resolve a field's type, which would try to take the lock.
2736 std::vector<Class*> all_classes;
2737 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002738 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002739 typedef Table::const_iterator It; // TODO: C++0x auto
2740 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
2741 all_classes.push_back(it->second);
2742 }
Ian Rogers5d76c432011-10-31 21:42:49 -07002743 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
2744 all_classes.push_back(it->second);
2745 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07002746 }
2747
2748 for (size_t i = 0; i < all_classes.size(); ++i) {
2749 all_classes[i]->DumpClass(std::cerr, flags);
2750 }
2751}
2752
Elliott Hughescac6cc72011-11-03 20:31:21 -07002753void ClassLinker::DumpForSigQuit(std::ostream& os) const {
2754 MutexLock mu(classes_lock_);
2755 os << "Loaded classes: " << image_classes_.size() << " image classes; "
2756 << classes_.size() << " allocated classes\n";
2757}
2758
Elliott Hughese27955c2011-08-26 15:21:24 -07002759size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002760 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07002761 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07002762}
2763
Brian Carlstrom47d237a2011-10-18 15:08:33 -07002764pid_t ClassLinker::GetClassesLockOwner() {
2765 return classes_lock_.GetOwner();
2766}
2767
2768pid_t ClassLinker::GetDexLockOwner() {
2769 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07002770}
2771
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002772} // namespace art