blob: e0bcd04e44d195cc6537217cd9f708f5ed919f49 [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 Carlstromd601af82012-01-06 10:15:19 -08005#include <fcntl.h>
6#include <sys/file.h>
7#include <sys/stat.h>
Brian Carlstromdbf05b72011-12-15 00:55:24 -08008#include <sys/types.h>
9#include <sys/wait.h>
10
Brian Carlstromdbc05252011-09-09 01:59:59 -070011#include <deque>
Ian Rogers0cfe1fb2011-08-26 03:29:44 -070012#include <string>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070013#include <utility>
Elliott Hughes90a33692011-08-30 13:27:07 -070014#include <vector>
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070015
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070016#include "casts.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070017#include "class_loader.h"
Elliott Hughes4740cdf2011-12-07 14:07:12 -080018#include "debugger.h"
Brian Carlstrom7e49dca2011-07-22 18:07:34 -070019#include "dex_cache.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070020#include "dex_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070021#include "dex_verifier.h"
22#include "heap.h"
Elliott Hughescf4c6c42011-09-01 15:16:42 -070023#include "intern_table.h"
Ian Rogers0571d352011-11-03 19:51:38 -070024#include "leb128.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070025#include "logging.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070026#include "oat_file.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070027#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080028#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070029#include "runtime.h"
Ian Rogers466bb252011-10-14 03:29:56 -070030#include "runtime_support.h"
Elliott Hughes4d0207c2011-10-03 19:14:34 -070031#include "ScopedLocalRef.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070032#include "space.h"
Brian Carlstrom40381fb2011-10-19 14:13:40 -070033#include "stack_indirect_reference_table.h"
Brian Carlstrom58ae9412011-10-04 00:56:06 -070034#include "stl_util.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070035#include "thread.h"
Elliott Hughes54e7df12011-09-16 11:47:04 -070036#include "UniquePtr.h"
Brian Carlstrom578bbdc2011-07-21 14:07:47 -070037#include "utils.h"
Carl Shapiro0e5d75d2011-07-06 18:28:37 -070038
39namespace art {
40
Elliott Hughes4a2b4172011-09-20 17:08:25 -070041namespace {
42
Elliott Hughes362f9bc2011-10-17 18:56:41 -070043void ThrowNoClassDefFoundError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070044void ThrowNoClassDefFoundError(const char* fmt, ...) {
45 va_list args;
46 va_start(args, fmt);
47 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NoClassDefFoundError;", fmt, args);
48 va_end(args);
49}
50
Elliott Hughes362f9bc2011-10-17 18:56:41 -070051void ThrowClassFormatError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughese555dc02011-09-25 10:46:35 -070052void ThrowClassFormatError(const char* fmt, ...) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -070053 va_list args;
54 va_start(args, fmt);
Elliott Hughese555dc02011-09-25 10:46:35 -070055 Thread::Current()->ThrowNewExceptionV("Ljava/lang/ClassFormatError;", fmt, args);
Elliott Hughes4a2b4172011-09-20 17:08:25 -070056 va_end(args);
57}
58
Elliott Hughes362f9bc2011-10-17 18:56:41 -070059void ThrowLinkageError(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
Elliott Hughes4a2b4172011-09-20 17:08:25 -070060void ThrowLinkageError(const char* fmt, ...) {
61 va_list args;
62 va_start(args, fmt);
63 Thread::Current()->ThrowNewExceptionV("Ljava/lang/LinkageError;", fmt, args);
64 va_end(args);
65}
66
Ian Rogers9f1ab122011-12-12 08:52:43 -080067void ThrowNoSuchMethodError(bool is_direct, Class* c, const StringPiece& name,
68 const StringPiece& signature) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080069 ClassHelper kh(c);
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070070 std::ostringstream msg;
Ian Rogers9f1ab122011-12-12 08:52:43 -080071 msg << "no " << (is_direct ? "direct" : "virtual") << " method " << name << "." << signature
72 << " in class " << kh.GetDescriptor() << " or its superclasses";
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080073 std::string location(kh.GetLocation());
74 if (!location.empty()) {
75 msg << " (defined in " << location << ")";
Elliott Hughescc5f9a92011-09-28 19:17:29 -070076 }
Elliott Hughes5cb5ad22011-10-02 12:13:39 -070077 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchMethodError;", msg.str().c_str());
Elliott Hughescc5f9a92011-09-28 19:17:29 -070078}
79
Ian Rogersb067ac22011-12-13 18:05:09 -080080void ThrowNoSuchFieldError(const StringPiece& scope, Class* c, const StringPiece& type,
Ian Rogers9f1ab122011-12-12 08:52:43 -080081 const StringPiece& name) {
82 ClassHelper kh(c);
83 std::ostringstream msg;
Ian Rogersb067ac22011-12-13 18:05:09 -080084 msg << "no " << scope << "field " << name << " of type " << type
Ian Rogers9f1ab122011-12-12 08:52:43 -080085 << " in class " << kh.GetDescriptor() << " or its superclasses";
86 std::string location(kh.GetLocation());
87 if (!location.empty()) {
88 msg << " (defined in " << location << ")";
89 }
90 Thread::Current()->ThrowNewException("Ljava/lang/NoSuchFieldError;", msg.str().c_str());
91}
92
Ian Rogerscab01012012-01-10 17:35:46 -080093void ThrowNullPointerException(const char* fmt, ...) __attribute__((__format__(__printf__, 1, 2)));
94void ThrowNullPointerException(const char* fmt, ...) {
95 va_list args;
96 va_start(args, fmt);
97 Thread::Current()->ThrowNewExceptionV("Ljava/lang/NullPointerException;", fmt, args);
98 va_end(args);
99}
100
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700101void ThrowEarlierClassFailure(Class* c) {
102 /*
103 * The class failed to initialize on a previous attempt, so we want to throw
104 * a NoClassDefFoundError (v2 2.17.5). The exception to this rule is if we
105 * failed in verification, in which case v2 5.4.1 says we need to re-throw
106 * the previous error.
107 */
108 LOG(INFO) << "Rejecting re-init on previously-failed class " << PrettyClass(c);
109
110 if (c->GetVerifyErrorClass() != NULL) {
111 // TODO: change the verifier to store an _instance_, with a useful detail message?
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800112 ClassHelper ve_ch(c->GetVerifyErrorClass());
113 std::string error_descriptor(ve_ch.GetDescriptor());
114 Thread::Current()->ThrowNewException(error_descriptor.c_str(), PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700115 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800116 ThrowNoClassDefFoundError("%s", PrettyDescriptor(c).c_str());
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700117 }
118}
119
Elliott Hughes4d0207c2011-10-03 19:14:34 -0700120void WrapExceptionInInitializer() {
121 JNIEnv* env = Thread::Current()->GetJniEnv();
122
123 ScopedLocalRef<jthrowable> cause(env, env->ExceptionOccurred());
124 CHECK(cause.get() != NULL);
125
126 env->ExceptionClear();
127
128 // TODO: add java.lang.Error to JniConstants?
129 ScopedLocalRef<jclass> error_class(env, env->FindClass("java/lang/Error"));
130 CHECK(error_class.get() != NULL);
131 if (env->IsInstanceOf(cause.get(), error_class.get())) {
132 // We only wrap non-Error exceptions; an Error can just be used as-is.
133 env->Throw(cause.get());
134 return;
135 }
136
137 // TODO: add java.lang.ExceptionInInitializerError to JniConstants?
138 ScopedLocalRef<jclass> eiie_class(env, env->FindClass("java/lang/ExceptionInInitializerError"));
139 CHECK(eiie_class.get() != NULL);
140
141 jmethodID mid = env->GetMethodID(eiie_class.get(), "<init>" , "(Ljava/lang/Throwable;)V");
142 CHECK(mid != NULL);
143
144 ScopedLocalRef<jthrowable> eiie(env,
145 reinterpret_cast<jthrowable>(env->NewObject(eiie_class.get(), mid, cause.get())));
146 env->Throw(eiie.get());
147}
148
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800149static size_t Hash(const char* s) {
150 // This is the java.lang.String hashcode for convenience, not interoperability.
151 size_t hash = 0;
152 for (; *s != '\0'; ++s) {
153 hash = hash * 31 + *s;
154 }
155 return hash;
156}
157
Elliott Hughes362f9bc2011-10-17 18:56:41 -0700158} // namespace
Elliott Hughes4a2b4172011-09-20 17:08:25 -0700159
Elliott Hughes418d20f2011-09-22 14:00:39 -0700160const char* ClassLinker::class_roots_descriptors_[] = {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700161 "Ljava/lang/Class;",
162 "Ljava/lang/Object;",
Elliott Hughes418d20f2011-09-22 14:00:39 -0700163 "[Ljava/lang/Class;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700164 "[Ljava/lang/Object;",
165 "Ljava/lang/String;",
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700166 "Ljava/lang/ref/Reference;",
Elliott Hughes80609252011-09-23 17:24:51 -0700167 "Ljava/lang/reflect/Constructor;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700168 "Ljava/lang/reflect/Field;",
169 "Ljava/lang/reflect/Method;",
Ian Rogers466bb252011-10-14 03:29:56 -0700170 "Ljava/lang/reflect/Proxy;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700171 "Ljava/lang/ClassLoader;",
172 "Ldalvik/system/BaseDexClassLoader;",
173 "Ldalvik/system/PathClassLoader;",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700174 "Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700175 "Z",
176 "B",
177 "C",
178 "D",
179 "F",
180 "I",
181 "J",
182 "S",
183 "V",
184 "[Z",
185 "[B",
186 "[C",
187 "[D",
188 "[F",
189 "[I",
190 "[J",
191 "[S",
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700192 "[Ljava/lang/StackTraceElement;",
Brian Carlstroma663ea52011-08-19 23:33:41 -0700193};
194
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800195ClassLinker* ClassLinker::Create(const std::string& boot_class_path, InternTable* intern_table) {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700196 CHECK_NE(boot_class_path.size(), 0U);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800197 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700198 class_linker->Init(boot_class_path);
199 return class_linker.release();
200}
201
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800202ClassLinker* ClassLinker::Create(InternTable* intern_table) {
203 UniquePtr<ClassLinker> class_linker(new ClassLinker(intern_table));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700204 class_linker->InitFromImage();
Carl Shapiro61e019d2011-07-14 16:53:09 -0700205 return class_linker.release();
206}
207
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800208ClassLinker::ClassLinker(InternTable* intern_table)
209 : dex_lock_("ClassLinker dex lock"),
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700210 classes_lock_("ClassLinker classes lock"),
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700211 class_roots_(NULL),
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700212 array_iftable_(NULL),
Elliott Hughescf4c6c42011-09-01 15:16:42 -0700213 init_done_(false),
214 intern_table_(intern_table) {
Elliott Hughes418d20f2011-09-22 14:00:39 -0700215 CHECK_EQ(arraysize(class_roots_descriptors_), size_t(kClassRootsMax));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700216}
Brian Carlstroma663ea52011-08-19 23:33:41 -0700217
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700218void CreateClassPath(const std::string& class_path,
219 std::vector<const DexFile*>& class_path_vector) {
220 std::vector<std::string> parsed;
221 Split(class_path, ':', parsed);
222 for (size_t i = 0; i < parsed.size(); ++i) {
223 const DexFile* dex_file = DexFile::Open(parsed[i], Runtime::Current()->GetHostPrefix());
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700224 if (dex_file == NULL) {
225 LOG(WARNING) << "Failed to open dex file " << parsed[i];
226 } else {
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700227 class_path_vector.push_back(dex_file);
228 }
229 }
230}
231
232void ClassLinker::Init(const std::string& boot_class_path) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800233 VLOG(startup) << "ClassLinker::InitFrom entering boot_class_path=" << boot_class_path;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700234
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700235 CHECK(!init_done_);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700236
Elliott Hughes30646832011-10-13 16:59:46 -0700237 // java_lang_Class comes first, it's needed for AllocClass
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700238 SirtRef<Class> java_lang_Class(down_cast<Class*>(Heap::AllocObject(NULL, sizeof(ClassClass))));
239 CHECK(java_lang_Class.get() != NULL);
240 java_lang_Class->SetClass(java_lang_Class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700241 java_lang_Class->SetClassSize(sizeof(ClassClass));
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700242 // AllocClass(Class*) can now be used
Brian Carlstroma0808032011-07-18 00:39:23 -0700243
Elliott Hughes418d20f2011-09-22 14:00:39 -0700244 // Class[] is used for reflection support.
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700245 SirtRef<Class> class_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
246 class_array_class->SetComponentType(java_lang_Class.get());
Elliott Hughes418d20f2011-09-22 14:00:39 -0700247
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700248 // java_lang_Object comes next so that object_array_class can be created
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700249 SirtRef<Class> java_lang_Object(AllocClass(java_lang_Class.get(), sizeof(Class)));
250 CHECK(java_lang_Object.get() != NULL);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700251 // backfill Object as the super class of Class
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700252 java_lang_Class->SetSuperClass(java_lang_Object.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700253 java_lang_Object->SetStatus(Class::kStatusLoaded);
Brian Carlstroma0808032011-07-18 00:39:23 -0700254
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700255 // Object[] next to hold class roots
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700256 SirtRef<Class> object_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
257 object_array_class->SetComponentType(java_lang_Object.get());
Brian Carlstroma0808032011-07-18 00:39:23 -0700258
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700259 // Setup the char class to be used for char[]
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700260 SirtRef<Class> char_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700261
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700262 // Setup the char[] class to be used for String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700263 SirtRef<Class> char_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
264 char_array_class->SetComponentType(char_class.get());
265 CharArray::SetArrayClass(char_array_class.get());
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700266
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700267 // Setup String
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700268 SirtRef<Class> java_lang_String(AllocClass(java_lang_Class.get(), sizeof(StringClass)));
269 String::SetClass(java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700270 java_lang_String->SetObjectSize(sizeof(String));
271 java_lang_String->SetStatus(Class::kStatusResolved);
Jesse Wilson14150742011-07-29 19:04:44 -0400272
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700273 // Create storage for root classes, save away our work so far (requires
274 // descriptors)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700275 class_roots_ = ObjectArray<Class>::Alloc(object_array_class.get(), kClassRootsMax);
Elliott Hughes30646832011-10-13 16:59:46 -0700276 CHECK(class_roots_ != NULL);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700277 SetClassRoot(kJavaLangClass, java_lang_Class.get());
278 SetClassRoot(kJavaLangObject, java_lang_Object.get());
279 SetClassRoot(kClassArrayClass, class_array_class.get());
280 SetClassRoot(kObjectArrayClass, object_array_class.get());
281 SetClassRoot(kCharArrayClass, char_array_class.get());
282 SetClassRoot(kJavaLangString, java_lang_String.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700283
284 // Setup the primitive type classes.
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700285 SetClassRoot(kPrimitiveBoolean, CreatePrimitiveClass("Z", Primitive::kPrimBoolean));
286 SetClassRoot(kPrimitiveByte, CreatePrimitiveClass("B", Primitive::kPrimByte));
287 SetClassRoot(kPrimitiveShort, CreatePrimitiveClass("S", Primitive::kPrimShort));
288 SetClassRoot(kPrimitiveInt, CreatePrimitiveClass("I", Primitive::kPrimInt));
289 SetClassRoot(kPrimitiveLong, CreatePrimitiveClass("J", Primitive::kPrimLong));
290 SetClassRoot(kPrimitiveFloat, CreatePrimitiveClass("F", Primitive::kPrimFloat));
291 SetClassRoot(kPrimitiveDouble, CreatePrimitiveClass("D", Primitive::kPrimDouble));
292 SetClassRoot(kPrimitiveVoid, CreatePrimitiveClass("V", Primitive::kPrimVoid));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700293
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700294 // Create array interface entries to populate once we can load system classes
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700295 array_iftable_ = AllocObjectArray<InterfaceEntry>(2);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700296
297 // Create int array type for AllocDexCache (done in AppendToBootClassPath)
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700298 SirtRef<Class> int_array_class(AllocClass(java_lang_Class.get(), sizeof(Class)));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700299 int_array_class->SetComponentType(GetClassRoot(kPrimitiveInt));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700300 IntArray::SetArrayClass(int_array_class.get());
301 SetClassRoot(kIntArrayClass, int_array_class.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700302
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700303 // now that these are registered, we can use AllocClass() and AllocObjectArray
Brian Carlstroma0808032011-07-18 00:39:23 -0700304
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700305 // setup boot_class_path_ and register class_path now that we can
306 // use AllocObjectArray to create DexCache instances
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700307 std::vector<const DexFile*> boot_class_path_vector;
308 CreateClassPath(boot_class_path, boot_class_path_vector);
Brian Carlstrom0dd7dda2011-10-25 15:47:53 -0700309 CHECK_NE(0U, boot_class_path_vector.size());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700310 for (size_t i = 0; i != boot_class_path_vector.size(); ++i) {
311 const DexFile* dex_file = boot_class_path_vector[i];
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700312 CHECK(dex_file != NULL);
313 AppendToBootClassPath(*dex_file);
Brian Carlstrom913af1b2011-07-23 21:41:13 -0700314 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700315
Elliott Hughes80609252011-09-23 17:24:51 -0700316 // Constructor, Field, and Method are necessary so that FindClass can link members
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700317 SirtRef<Class> java_lang_reflect_Constructor(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700318 CHECK(java_lang_reflect_Constructor.get() != NULL);
Elliott Hughes80609252011-09-23 17:24:51 -0700319 java_lang_reflect_Constructor->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700320 SetClassRoot(kJavaLangReflectConstructor, java_lang_reflect_Constructor.get());
Elliott Hughes80609252011-09-23 17:24:51 -0700321 java_lang_reflect_Constructor->SetStatus(Class::kStatusResolved);
322
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700323 SirtRef<Class> java_lang_reflect_Field(AllocClass(java_lang_Class.get(), sizeof(FieldClass)));
324 CHECK(java_lang_reflect_Field.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700325 java_lang_reflect_Field->SetObjectSize(sizeof(Field));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700326 SetClassRoot(kJavaLangReflectField, java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700327 java_lang_reflect_Field->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700328 Field::SetClass(java_lang_reflect_Field.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700329
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 SirtRef<Class> java_lang_reflect_Method(AllocClass(java_lang_Class.get(), sizeof(MethodClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700331 CHECK(java_lang_reflect_Method.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700332 java_lang_reflect_Method->SetObjectSize(sizeof(Method));
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 SetClassRoot(kJavaLangReflectMethod, java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700334 java_lang_reflect_Method->SetStatus(Class::kStatusResolved);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700335 Method::SetClasses(java_lang_reflect_Constructor.get(), java_lang_reflect_Method.get());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700336
337 // now we can use FindSystemClass
338
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700339 // run char class through InitializePrimitiveClass to finish init
Brian Carlstrom6b4ef022011-10-23 14:59:04 -0700340 InitializePrimitiveClass(char_class.get(), "C", Primitive::kPrimChar);
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700341 SetClassRoot(kPrimitiveChar, char_class.get()); // needs descriptor
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -0700342
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700343 // Object and String need to be rerun through FindSystemClass to finish init
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700344 java_lang_Object->SetStatus(Class::kStatusNotReady);
345 Class* Object_class = FindSystemClass("Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700346 CHECK_EQ(java_lang_Object.get(), Object_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700347 CHECK_EQ(java_lang_Object->GetObjectSize(), sizeof(Object));
348 java_lang_String->SetStatus(Class::kStatusNotReady);
349 Class* String_class = FindSystemClass("Ljava/lang/String;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700350 CHECK_EQ(java_lang_String.get(), String_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700351 CHECK_EQ(java_lang_String->GetObjectSize(), sizeof(String));
352
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700353 // Setup the primitive array type classes - can't be done until Object has a vtable
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700354 SetClassRoot(kBooleanArrayClass, FindSystemClass("[Z"));
355 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
356
357 SetClassRoot(kByteArrayClass, FindSystemClass("[B"));
358 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
359
360 Class* found_char_array_class = FindSystemClass("[C");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700361 CHECK_EQ(char_array_class.get(), found_char_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700362
363 SetClassRoot(kShortArrayClass, FindSystemClass("[S"));
364 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
365
366 Class* found_int_array_class = FindSystemClass("[I");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700367 CHECK_EQ(int_array_class.get(), found_int_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700368
369 SetClassRoot(kLongArrayClass, FindSystemClass("[J"));
370 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
371
372 SetClassRoot(kFloatArrayClass, FindSystemClass("[F"));
373 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
374
375 SetClassRoot(kDoubleArrayClass, FindSystemClass("[D"));
376 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
377
Elliott Hughes418d20f2011-09-22 14:00:39 -0700378 Class* found_class_array_class = FindSystemClass("[Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700379 CHECK_EQ(class_array_class.get(), found_class_array_class);
Elliott Hughes418d20f2011-09-22 14:00:39 -0700380
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700381 Class* found_object_array_class = FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700382 CHECK_EQ(object_array_class.get(), found_object_array_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700383
384 // Setup the single, global copies of "interfaces" and "iftable"
385 Class* java_lang_Cloneable = FindSystemClass("Ljava/lang/Cloneable;");
386 CHECK(java_lang_Cloneable != NULL);
387 Class* java_io_Serializable = FindSystemClass("Ljava/io/Serializable;");
388 CHECK(java_io_Serializable != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700389 // We assume that Cloneable/Serializable don't have superinterfaces --
390 // normally we'd have to crawl up and explicitly list all of the
Brian Carlstrom4b620ff2011-09-11 01:11:01 -0700391 // supers as well.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800392 array_iftable_->Set(0, AllocInterfaceEntry(java_lang_Cloneable));
393 array_iftable_->Set(1, AllocInterfaceEntry(java_io_Serializable));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700394
Elliott Hughes418d20f2011-09-22 14:00:39 -0700395 // Sanity check Class[] and Object[]'s interfaces
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800396 ClassHelper kh(class_array_class.get(), this);
397 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
398 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
399 kh.ChangeClass(object_array_class.get());
400 CHECK_EQ(java_lang_Cloneable, kh.GetInterface(0));
401 CHECK_EQ(java_io_Serializable, kh.GetInterface(1));
Elliott Hughes80609252011-09-23 17:24:51 -0700402 // run Class, Constructor, Field, and Method through FindSystemClass.
Brian Carlstrom74eb46a2011-08-02 20:10:14 -0700403 // this initializes their dex_cache_ fields and register them in classes_.
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700404 Class* Class_class = FindSystemClass("Ljava/lang/Class;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700405 CHECK_EQ(java_lang_Class.get(), Class_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700406
Elliott Hughes80609252011-09-23 17:24:51 -0700407 java_lang_reflect_Constructor->SetStatus(Class::kStatusNotReady);
408 Class* Constructor_class = FindSystemClass("Ljava/lang/reflect/Constructor;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700409 CHECK_EQ(java_lang_reflect_Constructor.get(), Constructor_class);
Elliott Hughes80609252011-09-23 17:24:51 -0700410
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700411 java_lang_reflect_Field->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700412 Class* Field_class = FindSystemClass("Ljava/lang/reflect/Field;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700413 CHECK_EQ(java_lang_reflect_Field.get(), Field_class);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700414
415 java_lang_reflect_Method->SetStatus(Class::kStatusNotReady);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700416 Class* Method_class = FindSystemClass("Ljava/lang/reflect/Method;");
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700417 CHECK_EQ(java_lang_reflect_Method.get(), Method_class);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700418
Ian Rogers466bb252011-10-14 03:29:56 -0700419 // End of special init trickery, subsequent classes may be loaded via FindSystemClass
420
421 // Create java.lang.reflect.Proxy root
422 Class* java_lang_reflect_Proxy = FindSystemClass("Ljava/lang/reflect/Proxy;");
423 SetClassRoot(kJavaLangReflectProxy, java_lang_reflect_Proxy);
424
Brian Carlstrom1f870082011-08-23 16:02:11 -0700425 // java.lang.ref classes need to be specially flagged, but otherwise are normal classes
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700426 Class* java_lang_ref_Reference = FindSystemClass("Ljava/lang/ref/Reference;");
427 SetClassRoot(kJavaLangRefReference, java_lang_ref_Reference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700428 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700429 java_lang_ref_FinalizerReference->SetAccessFlags(
430 java_lang_ref_FinalizerReference->GetAccessFlags() |
431 kAccClassIsReference | kAccClassIsFinalizerReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700432 Class* java_lang_ref_PhantomReference = FindSystemClass("Ljava/lang/ref/PhantomReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700433 java_lang_ref_PhantomReference->SetAccessFlags(
434 java_lang_ref_PhantomReference->GetAccessFlags() |
435 kAccClassIsReference | kAccClassIsPhantomReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700436 Class* java_lang_ref_SoftReference = FindSystemClass("Ljava/lang/ref/SoftReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700437 java_lang_ref_SoftReference->SetAccessFlags(
438 java_lang_ref_SoftReference->GetAccessFlags() | kAccClassIsReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700439 Class* java_lang_ref_WeakReference = FindSystemClass("Ljava/lang/ref/WeakReference;");
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700440 java_lang_ref_WeakReference->SetAccessFlags(
441 java_lang_ref_WeakReference->GetAccessFlags() |
442 kAccClassIsReference | kAccClassIsWeakReference);
Brian Carlstrom1f870082011-08-23 16:02:11 -0700443
Brian Carlstromaded5f72011-10-07 17:15:04 -0700444 // Setup the ClassLoaders, verifying the object_size_
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700445 Class* java_lang_ClassLoader = FindSystemClass("Ljava/lang/ClassLoader;");
Brian Carlstromaded5f72011-10-07 17:15:04 -0700446 CHECK_EQ(java_lang_ClassLoader->GetObjectSize(), sizeof(ClassLoader));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700447 SetClassRoot(kJavaLangClassLoader, java_lang_ClassLoader);
448
449 Class* dalvik_system_BaseDexClassLoader = FindSystemClass("Ldalvik/system/BaseDexClassLoader;");
450 CHECK_EQ(dalvik_system_BaseDexClassLoader->GetObjectSize(), sizeof(BaseDexClassLoader));
451 SetClassRoot(kDalvikSystemBaseDexClassLoader, dalvik_system_BaseDexClassLoader);
452
453 Class* dalvik_system_PathClassLoader = FindSystemClass("Ldalvik/system/PathClassLoader;");
454 CHECK_EQ(dalvik_system_PathClassLoader->GetObjectSize(), sizeof(PathClassLoader));
455 SetClassRoot(kDalvikSystemPathClassLoader, dalvik_system_PathClassLoader);
456 PathClassLoader::SetClass(dalvik_system_PathClassLoader);
457
458 // Set up java.lang.StackTraceElement as a convenience
Brian Carlstrom1f870082011-08-23 16:02:11 -0700459 SetClassRoot(kJavaLangStackTraceElement, FindSystemClass("Ljava/lang/StackTraceElement;"));
460 SetClassRoot(kJavaLangStackTraceElementArrayClass, FindSystemClass("[Ljava/lang/StackTraceElement;"));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700461 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700462
Brian Carlstroma663ea52011-08-19 23:33:41 -0700463 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700464
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800465 VLOG(startup) << "ClassLinker::InitFrom exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700466}
467
468void ClassLinker::FinishInit() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800469 VLOG(startup) << "ClassLinker::FinishInit entering";
Brian Carlstrom16192862011-09-12 17:50:06 -0700470
471 // Let the heap know some key offsets into java.lang.ref instances
Elliott Hughes20cde902011-10-04 17:37:27 -0700472 // Note: we hard code the field indexes here rather than using FindInstanceField
Brian Carlstrom16192862011-09-12 17:50:06 -0700473 // as the types of the field can't be resolved prior to the runtime being
474 // fully initialized
Elliott Hughesbf61ba32011-10-11 10:53:09 -0700475 Class* java_lang_ref_Reference = GetClassRoot(kJavaLangRefReference);
Elliott Hughesadb460d2011-10-05 17:02:34 -0700476 Class* java_lang_ref_ReferenceQueue = FindSystemClass("Ljava/lang/ref/ReferenceQueue;");
Brian Carlstrom16192862011-09-12 17:50:06 -0700477 Class* java_lang_ref_FinalizerReference = FindSystemClass("Ljava/lang/ref/FinalizerReference;");
478
Elliott Hughesadb460d2011-10-05 17:02:34 -0700479 Heap::SetWellKnownClasses(java_lang_ref_FinalizerReference, java_lang_ref_ReferenceQueue);
480
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800481 const DexFile& java_lang_dex = FindDexFile(java_lang_ref_Reference->GetDexCache());
482
Brian Carlstrom16192862011-09-12 17:50:06 -0700483 Field* pendingNext = java_lang_ref_Reference->GetInstanceField(0);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800484 FieldHelper fh(pendingNext, this);
485 CHECK_STREQ(fh.GetName(), "pendingNext");
486 CHECK_EQ(java_lang_dex.GetFieldId(pendingNext->GetDexFieldIndex()).type_idx_,
487 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700488
489 Field* queue = java_lang_ref_Reference->GetInstanceField(1);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800490 fh.ChangeField(queue);
491 CHECK_STREQ(fh.GetName(), "queue");
492 CHECK_EQ(java_lang_dex.GetFieldId(queue->GetDexFieldIndex()).type_idx_,
493 java_lang_ref_ReferenceQueue->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700494
495 Field* queueNext = java_lang_ref_Reference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800496 fh.ChangeField(queueNext);
497 CHECK_STREQ(fh.GetName(), "queueNext");
498 CHECK_EQ(java_lang_dex.GetFieldId(queueNext->GetDexFieldIndex()).type_idx_,
499 java_lang_ref_Reference->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700500
501 Field* referent = java_lang_ref_Reference->GetInstanceField(3);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800502 fh.ChangeField(referent);
503 CHECK_STREQ(fh.GetName(), "referent");
504 CHECK_EQ(java_lang_dex.GetFieldId(referent->GetDexFieldIndex()).type_idx_,
505 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700506
507 Field* zombie = java_lang_ref_FinalizerReference->GetInstanceField(2);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800508 fh.ChangeField(zombie);
509 CHECK_STREQ(fh.GetName(), "zombie");
510 CHECK_EQ(java_lang_dex.GetFieldId(zombie->GetDexFieldIndex()).type_idx_,
511 GetClassRoot(kJavaLangObject)->GetDexTypeIndex());
Brian Carlstrom16192862011-09-12 17:50:06 -0700512
513 Heap::SetReferenceOffsets(referent->GetOffset(),
514 queue->GetOffset(),
515 queueNext->GetOffset(),
516 pendingNext->GetOffset(),
517 zombie->GetOffset());
518
Brian Carlstroma663ea52011-08-19 23:33:41 -0700519 // ensure all class_roots_ are initialized
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700520 for (size_t i = 0; i < kClassRootsMax; i++) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700521 ClassRoot class_root = static_cast<ClassRoot>(i);
522 Class* klass = GetClassRoot(class_root);
523 CHECK(klass != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700524 DCHECK(klass->IsArrayClass() || klass->IsPrimitive() || klass->GetDexCache() != NULL);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700525 // note SetClassRoot does additional validation.
526 // if possible add new checks there to catch errors early
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700527 }
528
Elliott Hughes92f14b22011-10-06 12:29:54 -0700529 CHECK(array_iftable_ != NULL);
Elliott Hughes92f14b22011-10-06 12:29:54 -0700530
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700531 // disable the slow paths in FindClass and CreatePrimitiveClass now
532 // that Object, Class, and Object[] are setup
533 init_done_ = true;
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700534
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800535 VLOG(startup) << "ClassLinker::FinishInit exiting";
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700536}
537
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700538void ClassLinker::RunRootClinits() {
539 Thread* self = Thread::Current();
540 for (size_t i = 0; i < ClassLinker::kClassRootsMax; ++i) {
541 Class* c = GetClassRoot(ClassRoot(i));
542 if (!c->IsArrayClass() && !c->IsPrimitive()) {
543 EnsureInitialized(GetClassRoot(ClassRoot(i)), true);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -0700544 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughes2a20cfd2011-09-23 19:30:41 -0700545 }
546 }
547}
548
Brian Carlstromd601af82012-01-06 10:15:19 -0800549bool ClassLinker::GenerateOatFile(const std::string& dex_filename,
550 int oat_fd,
551 const std::string& oat_cache_filename) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800552 std::string dex2oat_string("/system/bin/dex2oat");
553#ifndef NDEBUG
554 dex2oat_string += 'd';
555#endif
556 const char* dex2oat = dex2oat_string.c_str();
557
558 const char* class_path = Runtime::Current()->GetClassPath().c_str();
559
560 std::string boot_image_option_string("--boot-image=");
Ian Rogers30fab402012-01-23 15:43:46 -0800561 boot_image_option_string += Heap::GetSpaces()[0]->AsImageSpace()->GetImageFilename();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800562 const char* boot_image_option = boot_image_option_string.c_str();
563
564 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800565 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800566 const char* dex_file_option = dex_file_option_string.c_str();
567
Brian Carlstromd601af82012-01-06 10:15:19 -0800568 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800569 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800570 const char* oat_fd_option = oat_fd_option_string.c_str();
571
572 std::string oat_name_option_string("--oat-name=");
573 oat_name_option_string += oat_cache_filename;
574 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800575
jeffhao262bf462011-10-20 18:36:32 -0700576 // fork and exec dex2oat
577 pid_t pid = fork();
578 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800579 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800580
581 // change process groups, so we don't get reaped by ProcessManager
582 setpgid(0, 0);
583
jeffhao10037c82012-01-23 15:06:23 -0800584 VLOG(class_linker) << dex2oat
585 << " --runtime-arg -Xms64m"
586 << " --runtime-arg -Xmx64m"
587 << " --runtime-arg -classpath"
588 << " --runtime-arg " << class_path
589 << " " << boot_image_option
590 << " " << dex_file_option
591 << " " << oat_fd_option
592 << " " << oat_name_option;
593
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800594 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700595 "--runtime-arg", "-Xms64m",
596 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500597 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800598 "--runtime-arg", class_path,
599 boot_image_option,
600 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800601 oat_fd_option,
602 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700603 NULL);
604
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800605 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800606 return false;
jeffhao262bf462011-10-20 18:36:32 -0700607 } else {
608 // wait for dex2oat to finish
609 int status;
610 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
611 if (got_pid != pid) {
612 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800613 return false;
jeffhao262bf462011-10-20 18:36:32 -0700614 }
615 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800616 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
617 return false;
jeffhao262bf462011-10-20 18:36:32 -0700618 }
619 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800620 return true;
jeffhao262bf462011-10-20 18:36:32 -0700621}
622
Brian Carlstrom866c8622012-01-06 16:35:13 -0800623void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
624 MutexLock mu(dex_lock_);
625 RegisterOatFileLocked(oat_file);
626}
627
628void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
629 dex_lock_.AssertHeld();
630 oat_files_.push_back(&oat_file);
631}
632
Ian Rogers30fab402012-01-23 15:43:46 -0800633OatFile* ClassLinker::OpenOat(const ImageSpace* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700634 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700635 const Runtime* runtime = Runtime::Current();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700636 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800637 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
638 // check the down cast
639 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700640 std::string oat_filename;
641 oat_filename += runtime->GetHostPrefix();
642 oat_filename += oat_location->ToModifiedUtf8();
Ian Rogers30fab402012-01-23 15:43:46 -0800643 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBegin());
644 VLOG(startup) << "ClassLinker::OpenOat entering oat_filename=" << oat_filename;
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700645 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700646 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700647 return NULL;
648 }
649 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
650 uint32_t image_oat_checksum = image_header.GetOatChecksum();
651 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800652 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700653 << " to expected oat checksum " << std::hex << oat_checksum
654 << " in image";
655 return NULL;
656 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800657 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800658 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700659 return oat_file;
660}
661
Brian Carlstromae826982011-11-09 01:33:42 -0800662const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
663 for (size_t i = 0; i < oat_files_.size(); i++) {
664 const OatFile* oat_file = oat_files_[i];
665 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800666 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800667 return oat_file;
668 }
669 }
670 return NULL;
671}
672
Brian Carlstromd601af82012-01-06 10:15:19 -0800673class LockedFd {
674 public:
675 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
676 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
677 if (fd == -1) {
678 PLOG(ERROR) << "Failed to open file '" << name << "'";
679 return NULL;
680 }
681 fchmod(fd, mode);
682
683 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
684 // try to lock non-blocking so we can log if we need may need to block
685 int result = flock(fd, LOCK_EX | LOCK_NB);
686 if (result == -1) {
687 LOG(WARNING) << "sleeping while locking file " << name;
688 // retry blocking
689 result = flock(fd, LOCK_EX);
690 }
691 if (result == -1) {
692 PLOG(ERROR) << "Failed to lock file '" << name << "'";
693 close(fd);
694 return NULL;
695 }
696 return new LockedFd(fd);
697 }
698
699 int GetFd() const {
700 return fd_;
701 }
702
703 ~LockedFd() {
704 if (fd_ != -1) {
705 int result = flock(fd_, LOCK_UN);
706 if (result == -1) {
707 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
708 }
709 close(fd_);
710 }
711 }
712
713 private:
714 explicit LockedFd(int fd) : fd_(fd) {}
715
716 int fd_;
717};
718
Brian Carlstromae826982011-11-09 01:33:42 -0800719const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700720 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800721 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
722 if (open_oat_file != NULL) {
723 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800724 }
725
Brian Carlstromd601af82012-01-06 10:15:19 -0800726 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800727 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
728 if (open_oat_file != NULL) {
729 return open_oat_file;
730 }
731
Brian Carlstromd601af82012-01-06 10:15:19 -0800732 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800733 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
734 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800735 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
736 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800737 RegisterOatFileLocked(*oat_file.get());
738 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800739 }
740 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
741 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
742 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
743 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
744 }
745 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700746 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800747 // Try to generate oat file if it wasn't found or was obsolete.
748 // Note we can be racing with another runtime to do this.
749 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
750 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
751 if (locked_fd.get() == NULL) {
752 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
753 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700754 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800755 // Check to see if the fd we opened and locked matches the file in
756 // the filesystem. If they don't, then somebody else unlinked ours
757 // and created a new file, and we need to use that one instead. (If
758 // we caught them between the unlink and the create, we'll get an
759 // ENOENT from the file stat.)
760 struct stat fd_stat;
761 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
762 if (fd_stat_result != 0) {
763 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
764 return NULL;
765 }
766 struct stat file_stat;
767 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
768 if (file_stat_result != 0
769 || fd_stat.st_dev != file_stat.st_dev
770 || fd_stat.st_ino != file_stat.st_ino) {
771 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
772 usleep(250 * 1000); // if something is hosed, don't peg machine
773 continue;
774 }
775
776 // We have the correct file open and locked. If the file size is
777 // zero, then it was just created by us and we can generate its
778 // contents. If not, someone else created it. Either way, we'll
779 // loop to retry opening the file.
780 if (fd_stat.st_size == 0) {
781 bool success = GenerateOatFile(dex_file.GetLocation(),
782 locked_fd->GetFd(),
783 oat_cache_filename);
784 if (!success) {
785 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
786 return NULL;
787 }
788 }
jeffhao262bf462011-10-20 18:36:32 -0700789 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800790 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700791}
792
Brian Carlstromae826982011-11-09 01:33:42 -0800793const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700794 for (size_t i = 0; i < oat_files_.size(); i++) {
795 const OatFile* oat_file = oat_files_[i];
796 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800797 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700798 return oat_file;
799 }
800 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700801 return NULL;
802}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700803
Brian Carlstromae826982011-11-09 01:33:42 -0800804const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800805 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700806 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800807 if (oat_location.empty() || oat_location[0] != '/') {
808 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700809 return NULL;
810 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700811
Brian Carlstroma9f19782011-10-13 00:14:47 -0700812 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800813 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800814 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700815 if (oat_file != NULL) {
816 return oat_file;
817 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700818 oat_file = OatFile::Open(cache_location, "", NULL);
819 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800820 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700821 return NULL;
822 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700823 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700824
Brian Carlstromae826982011-11-09 01:33:42 -0800825 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700826 return oat_file;
827}
828
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700829void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800830 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700831 CHECK(!init_done_);
832
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700833 const std::vector<Space*>& spaces = Heap::GetSpaces();
834 for (size_t i = 0; i < spaces.size(); i++) {
Ian Rogers30fab402012-01-23 15:43:46 -0800835 if (spaces[i]->IsImageSpace()) {
836 ImageSpace* space = spaces[i]->AsImageSpace();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700837 OatFile* oat_file = OpenOat(space);
838 CHECK(oat_file != NULL) << "Failed to open oat file for image";
839 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
840 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
841
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800842 if (i == 0) {
843 // Special case of setting up the String class early so that we can test arbitrary objects
844 // as being Strings or not
Ian Rogers30fab402012-01-23 15:43:46 -0800845 Class* java_lang_String = space->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800846 ->AsObjectArray<Class>()->Get(kJavaLangString);
847 String::SetClass(java_lang_String);
848 }
849
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700850 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
851 static_cast<uint32_t>(dex_caches->GetLength()));
852 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700853 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800854 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800855 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
856 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700857 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800858 LOG(FATAL) << "Failed to open dex file " << dex_file_location
859 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700860 }
861
Brian Carlstromaded5f72011-10-07 17:15:04 -0700862 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700863
Brian Carlstromdf143242011-10-10 18:05:34 -0700864 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700865 }
866 }
867 }
868
Brian Carlstroma663ea52011-08-19 23:33:41 -0700869 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
870 DCHECK(heap_bitmap != NULL);
871
Brian Carlstroma663ea52011-08-19 23:33:41 -0700872 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700873 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700874
875 // reinit class_roots_
Ian Rogers30fab402012-01-23 15:43:46 -0800876 Object* class_roots_object =
877 spaces[0]->AsImageSpace()->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700878 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700879
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800880 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700881 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
882 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800883 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700884 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700885 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700886 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
887 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
888 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
889 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
890 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
891 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
892 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
893 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700894 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700895 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700896
897 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700898
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800899 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700900}
901
Brian Carlstrom78128a62011-09-15 17:21:19 -0700902void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700903 DCHECK(obj != NULL);
904 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700905 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700906
Elliott Hughesdbb40792011-11-18 17:05:22 -0800907 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700908 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700909 return;
910 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700911 if (obj->IsClass()) {
912 // restore class to ClassLinker::classes_ table
913 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800914 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800915 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
916 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700917 return;
918 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700919}
920
921// Keep in sync with InitCallback. Anything we visit, we need to
922// reinit references to when reinitializing a ClassLinker from a
923// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700924void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
925 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700926
927 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700928 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700929 }
930
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700931 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700932 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700933 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700934 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700935 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700936 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700937 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700938 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700939
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700940 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700941}
942
Elliott Hughesa2155262011-11-16 16:26:58 -0800943void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
944 MutexLock mu(classes_lock_);
945 typedef Table::const_iterator It; // TODO: C++0x auto
946 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
947 if (!visitor(it->second, arg)) {
948 return;
949 }
950 }
951 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
952 if (!visitor(it->second, arg)) {
953 return;
954 }
955 }
956}
957
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700958ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700959 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700960 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700961 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700962 BooleanArray::ResetArrayClass();
963 ByteArray::ResetArrayClass();
964 CharArray::ResetArrayClass();
965 DoubleArray::ResetArrayClass();
966 FloatArray::ResetArrayClass();
967 IntArray::ResetArrayClass();
968 LongArray::ResetArrayClass();
969 ShortArray::ResetArrayClass();
970 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700971 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700972 STLDeleteElements(&boot_class_path_);
973 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700974}
975
976DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700977 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
978 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700979 return NULL;
980 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700981 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
982 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700983 return NULL;
984 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700985 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
986 if (strings.get() == NULL) {
987 return NULL;
988 }
989 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
990 if (types.get() == NULL) {
991 return NULL;
992 }
993 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
994 if (methods.get() == NULL) {
995 return NULL;
996 }
997 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
998 if (fields.get() == NULL) {
999 return NULL;
1000 }
1001 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
1002 if (code_and_direct_methods.get() == NULL) {
1003 return NULL;
1004 }
1005 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
1006 if (initialized_static_storage.get() == NULL) {
1007 return NULL;
1008 }
1009
1010 dex_cache->Init(location.get(),
1011 strings.get(),
1012 types.get(),
1013 methods.get(),
1014 fields.get(),
1015 code_and_direct_methods.get(),
1016 initialized_static_storage.get());
1017 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001018}
1019
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001020CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1021 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001022}
1023
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001024InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1025 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001026 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1027 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001028 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001029 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001030}
1031
Brian Carlstrom4873d462011-08-21 15:23:39 -07001032Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1033 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001034 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001035 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001036 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001037 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001038}
1039
Brian Carlstrom4873d462011-08-21 15:23:39 -07001040Class* ClassLinker::AllocClass(size_t class_size) {
1041 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001042}
1043
Jesse Wilson35baaab2011-08-10 16:18:03 -04001044Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001045 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001046}
1047
1048Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001049 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001050}
1051
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001052ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1053 return ObjectArray<StackTraceElement>::Alloc(
1054 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1055 length);
1056}
1057
Brian Carlstromaded5f72011-10-07 17:15:04 -07001058Class* EnsureResolved(Class* klass) {
1059 DCHECK(klass != NULL);
1060 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001061 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001062 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001063 ObjectLock lock(klass);
1064 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001065 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001066 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001067 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001068 return NULL;
1069 }
1070 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001071 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001072 lock.Wait();
1073 }
1074 }
1075 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001076 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001077 return NULL;
1078 }
1079 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001080 CHECK(klass->IsResolved()) << PrettyClass(klass);
1081 CHECK(!self->IsExceptionPending())
1082 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1083 return klass;
1084}
1085
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001086Class* ClassLinker::FindSystemClass(const char* descriptor) {
1087 return FindClass(descriptor, NULL);
1088}
1089
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001090Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001091 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001092 Thread* self = Thread::Current();
1093 DCHECK(self != NULL);
1094 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001095 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001096 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1097 // for primitive classes that aren't backed by dex files.
1098 return FindPrimitiveClass(descriptor[0]);
1099 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001100 // Find the class in the loaded classes table.
1101 Class* klass = LookupClass(descriptor, class_loader);
1102 if (klass != NULL) {
1103 return EnsureResolved(klass);
1104 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001105 // Class is not yet loaded.
Elliott Hughesa7679b62012-01-24 17:15:23 -08001106 JNIEnv* env = self->GetJniEnv();
1107 ScopedLocalRef<jthrowable> cause(env, NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001108 if (descriptor[0] == '[') {
1109 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001110
Jesse Wilson47daf872011-11-23 11:42:45 -05001111 } else if (class_loader == NULL) {
1112 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1113 if (pair.second != NULL) {
1114 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1115 }
1116
1117 } else if (ClassLoader::UseCompileTimeClassPath()) {
1118 // first try the boot class path
1119 Class* system_class = FindSystemClass(descriptor);
1120 if (system_class != NULL) {
1121 return system_class;
1122 }
1123 CHECK(self->IsExceptionPending());
1124 self->ClearException();
1125
1126 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001127 const std::vector<const DexFile*>& class_path
1128 = ClassLoader::GetCompileTimeClassPath(class_loader);
1129 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001130 if (pair.second != NULL) {
1131 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001132 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001133
1134 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001135 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001136 ScopedThreadStateChange(self, Thread::kNative);
Jesse Wilson47daf872011-11-23 11:42:45 -05001137 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1138 CHECK(c.get() != NULL);
1139 // TODO: cache method?
1140 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1141 CHECK(mid != NULL);
1142 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1143 if (class_name_object.get() == NULL) {
1144 return NULL;
1145 }
1146 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001147 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1148 class_name_object.get()));
Elliott Hughesa7679b62012-01-24 17:15:23 -08001149 cause.reset(env->ExceptionOccurred());
1150 if (cause.get() != NULL) {
Elliott Hughes7bfc9632012-01-26 12:02:54 -08001151 // Throw LinkageErrors unmolested...
Elliott Hughesa7679b62012-01-24 17:15:23 -08001152 env->ExceptionClear();
Elliott Hughes7bfc9632012-01-26 12:02:54 -08001153 static jclass LinkageError_class = CacheClass(env, "java/lang/LinkageError");
1154 if (env->IsInstanceOf(cause.get(), LinkageError_class)) {
1155 env->Throw(cause.get());
1156 return NULL;
1157 }
1158 // ...otherwise fall through and throw NCDFE.
Ian Rogers761bfa82012-01-11 10:14:05 -08001159 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001160 // broken loader - throw NPE to be compatible with Dalvik
1161 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1162 class_name_string.c_str());
1163 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001164 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001165 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001166 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001167 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001168 }
1169
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001170 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Elliott Hughesa7679b62012-01-24 17:15:23 -08001171 if (cause.get() != NULL) {
1172 // Initialize the cause of the NCDFE.
1173 ScopedLocalRef<jthrowable> ncdfe(env, env->ExceptionOccurred());
1174 env->ExceptionClear();
Elliott Hughes844f9a02012-01-24 20:19:58 -08001175 static jmethodID initCause_mid = env->GetMethodID(env->FindClass("java/lang/Throwable"), "initCause", "(Ljava/lang/Throwable;)Ljava/lang/Throwable;");
Elliott Hughesa7679b62012-01-24 17:15:23 -08001176 env->CallObjectMethod(ncdfe.get(), initCause_mid, cause.get());
1177 env->Throw(ncdfe.get());
1178 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001179 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001180}
1181
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001182Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001183 const ClassLoader* class_loader,
1184 const DexFile& dex_file,
1185 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001186 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 // Load the class from the dex file.
1188 if (!init_done_) {
1189 // finish up init of hand crafted class_roots_
1190 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001193 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001194 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001195 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001196 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001197 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001198 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001199 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001200 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001201 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001202 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001203 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001204 }
1205 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001206 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001207 }
1208 klass->SetDexCache(FindDexCache(dex_file));
1209 LoadClass(dex_file, dex_class_def, klass, class_loader);
1210 // Check for a pending exception during load
1211 Thread* self = Thread::Current();
1212 if (self->IsExceptionPending()) {
1213 return NULL;
1214 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001215 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001216 klass->SetClinitThreadId(self->GetTid());
1217 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001218 Class* existing = InsertClass(descriptor, klass.get(), false);
1219 if (existing != NULL) {
1220 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001221 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001222 klass.reset(existing);
1223 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001224 }
1225 // Finish loading (if necessary) by finding parents
1226 CHECK(!klass->IsLoaded());
1227 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1228 // Loading failed.
1229 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001230 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001231 lock.NotifyAll();
1232 return NULL;
1233 }
1234 CHECK(klass->IsLoaded());
1235 // Link the class (if necessary)
1236 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001237 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001238 // Linking failed.
1239 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001240 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001241 lock.NotifyAll();
1242 return NULL;
1243 }
1244 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001245
1246 /*
1247 * We send CLASS_PREPARE events to the debugger from here. The
1248 * definition of "preparation" is creating the static fields for a
1249 * class and initializing them to the standard default values, but not
1250 * executing any code (that comes later, during "initialization").
1251 *
1252 * We did the static preparation in LinkClass.
1253 *
1254 * The class has been prepared and resolved but possibly not yet verified
1255 * at this point.
1256 */
1257 Dbg::PostClassPrepare(klass.get());
1258
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001259 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001260}
1261
Brian Carlstrom4873d462011-08-21 15:23:39 -07001262// Precomputes size that will be needed for Class, matching LinkStaticFields
1263size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1264 const DexFile::ClassDef& dex_class_def) {
1265 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001266 size_t num_ref = 0;
1267 size_t num_32 = 0;
1268 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001269 if (class_data != NULL) {
1270 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1271 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001272 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001273 char c = descriptor[0];
1274 if (c == 'L' || c == '[') {
1275 num_ref++;
1276 } else if (c == 'J' || c == 'D') {
1277 num_64++;
1278 } else {
1279 num_32++;
1280 }
1281 }
1282 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001283 // start with generic class data
1284 size_t size = sizeof(Class);
1285 // follow with reference fields which must be contiguous at start
1286 size += (num_ref * sizeof(uint32_t));
1287 // if there are 64-bit fields to add, make sure they are aligned
1288 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1289 if (num_32 != 0) {
1290 // use an available 32-bit field for padding
1291 num_32--;
1292 }
1293 size += sizeof(uint32_t); // either way, we are adding a word
1294 DCHECK_EQ(size, RoundUp(size, 8));
1295 }
1296 // tack on any 64-bit fields now that alignment is assured
1297 size += (num_64 * sizeof(uint64_t));
1298 // tack on any remaining 32-bit fields
1299 size += (num_32 * sizeof(uint32_t));
1300 return size;
1301}
1302
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001303void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001304 // Every kind of method should at least get an invoke stub from the oat_method.
1305 // non-abstract methods also get their code pointers.
1306 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001307 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001308
1309 if (method->IsAbstract()) {
1310 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1311 return;
1312 }
1313 if (method->IsNative()) {
1314 // unregistering restores the dlsym lookup stub
1315 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001316 }
1317
1318 if (Runtime::Current()->IsMethodTracingActive()) {
1319#if defined(__arm__)
1320 Trace* tracer = Runtime::Current()->GetTracer();
1321 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1322 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1323#else
1324 UNIMPLEMENTED(WARNING);
1325#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001326 }
1327}
1328
Brian Carlstromf615a612011-07-23 12:50:34 -07001329void ClassLinker::LoadClass(const DexFile& dex_file,
1330 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001331 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001332 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001333 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001334 CHECK(klass->GetDexCache() != NULL);
1335 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001336 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001337 CHECK(descriptor != NULL);
1338
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001339 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001340 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001341 // Make sure that none of our runtime-only flags are set.
1342 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001343 klass->SetAccessFlags(access_flags);
1344 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001345 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001346 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001347
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001348 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001349
Ian Rogers0571d352011-11-03 19:51:38 -07001350 // Load fields fields.
1351 const byte* class_data = dex_file.GetClassData(dex_class_def);
1352 if (class_data == NULL) {
1353 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001354 }
Ian Rogers0571d352011-11-03 19:51:38 -07001355 ClassDataItemIterator it(dex_file, class_data);
1356 if (it.NumStaticFields() != 0) {
1357 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1358 }
1359 if (it.NumInstanceFields() != 0) {
1360 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1361 }
1362 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1363 SirtRef<Field> sfield(AllocField());
1364 klass->SetStaticField(i, sfield.get());
1365 LoadField(dex_file, it, klass, sfield);
1366 }
1367 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1368 SirtRef<Field> ifield(AllocField());
1369 klass->SetInstanceField(i, ifield.get());
1370 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001371 }
1372
Brian Carlstromaded5f72011-10-07 17:15:04 -07001373 UniquePtr<const OatFile::OatClass> oat_class;
1374 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001375 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001376 if (oat_file != NULL) {
1377 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1378 if (oat_dex_file != NULL) {
1379 uint32_t class_def_index;
1380 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1381 CHECK(found) << descriptor;
1382 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001383 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001384 }
1385 }
1386 }
Ian Rogers0571d352011-11-03 19:51:38 -07001387 // Load methods.
1388 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001389 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001390 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001391 }
Ian Rogers0571d352011-11-03 19:51:38 -07001392 if (it.NumVirtualMethods() != 0) {
1393 // TODO: append direct methods to class object
1394 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001395 }
Ian Rogers0571d352011-11-03 19:51:38 -07001396 size_t method_index = 0;
1397 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1398 SirtRef<Method> method(AllocMethod());
1399 klass->SetDirectMethod(i, method.get());
1400 LoadMethod(dex_file, it, klass, method);
1401 if (oat_class.get() != NULL) {
1402 LinkCode(method, oat_class.get(), method_index);
1403 }
1404 method_index++;
1405 }
1406 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1407 SirtRef<Method> method(AllocMethod());
1408 klass->SetVirtualMethod(i, method.get());
1409 LoadMethod(dex_file, it, klass, method);
1410 if (oat_class.get() != NULL) {
1411 LinkCode(method, oat_class.get(), method_index);
1412 }
1413 method_index++;
1414 }
1415 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001416}
1417
Ian Rogers0571d352011-11-03 19:51:38 -07001418void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1419 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001420 uint32_t field_idx = it.GetMemberIndex();
1421 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001422 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001423 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001424}
1425
Ian Rogers0571d352011-11-03 19:51:38 -07001426void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1427 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001428 uint32_t method_idx = it.GetMemberIndex();
1429 dst->SetDexMethodIndex(method_idx);
1430 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001431 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001432
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001433
1434 StringPiece method_name(dex_file.GetMethodName(method_id));
1435 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001436 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1437 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001438
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001439 if (method_name == "finalize") {
1440 // Create the prototype for a signature of "()V"
1441 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1442 if (void_string_id != NULL) {
1443 const DexFile::TypeId* void_type_id =
1444 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1445 if (void_type_id != NULL) {
1446 std::vector<uint16_t> no_args;
1447 const DexFile::ProtoId* finalizer_proto =
1448 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1449 if (finalizer_proto != NULL) {
1450 // We have the prototype in the dex file
1451 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1452 klass->SetFinalizable();
1453 } else {
1454 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1455 // The Enum class declares a "final" finalize() method to prevent subclasses from
1456 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1457 // subclasses, so we exclude it here.
1458 // We also want to avoid setting the flag on Object, where we know that finalize() is
1459 // empty.
1460 if (klass_descriptor != "Ljava/lang/Object;" &&
1461 klass_descriptor != "Ljava/lang/Enum;") {
1462 klass->SetFinalizable();
1463 }
1464 }
1465 }
1466 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001467 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001468 }
Ian Rogers0571d352011-11-03 19:51:38 -07001469 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001470 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001471
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001472 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1473 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1474 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1475 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1476 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1477 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001478}
1479
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001480void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001481 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1482 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001483}
1484
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001485void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1486 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001487 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001488 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001489}
1490
Brian Carlstromaded5f72011-10-07 17:15:04 -07001491bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001492 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001493 for (size_t i = 0; i != dex_files_.size(); ++i) {
1494 if (dex_files_[i] == &dex_file) {
1495 return true;
1496 }
1497 }
1498 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001499}
1500
Brian Carlstromaded5f72011-10-07 17:15:04 -07001501bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001502 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001503 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001504}
1505
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001506void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001507 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001508 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001509 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001510 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001511 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001512}
1513
Brian Carlstromaded5f72011-10-07 17:15:04 -07001514void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001515 {
1516 MutexLock mu(dex_lock_);
1517 if (IsDexFileRegisteredLocked(dex_file)) {
1518 return;
1519 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001520 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001521 // Don't alloc while holding the lock, since allocation may need to
1522 // suspend all threads and another thread may need the dex_lock_ to
1523 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001524 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001525 {
1526 MutexLock mu(dex_lock_);
1527 if (IsDexFileRegisteredLocked(dex_file)) {
1528 return;
1529 }
1530 RegisterDexFileLocked(dex_file, dex_cache);
1531 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001532}
1533
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001534void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001535 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001536 RegisterDexFileLocked(dex_file, dex_cache);
1537}
1538
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001539const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001540 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001541 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001542 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1543 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001544 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001545 }
1546 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001547 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001548 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001549}
1550
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001551DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001552 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001553 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001554 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001555 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001556 }
1557 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001558 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001559 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001560}
1561
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001562Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1563 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001564 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001565 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001566 CHECK(primitive_class != NULL);
1567 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001568 primitive_class->SetPrimitiveType(type);
1569 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001570 Class* existing = InsertClass(descriptor, primitive_class, false);
1571 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001572 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001573}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001574
Brian Carlstrombe977852011-07-19 14:54:54 -07001575// Create an array class (i.e. the class object for the array, not the
1576// array itself). "descriptor" looks like "[C" or "[[[[B" or
1577// "[Ljava/lang/String;".
1578//
1579// If "descriptor" refers to an array of primitives, look up the
1580// primitive type's internally-generated class object.
1581//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001582// "class_loader" is the class loader of the class that's referring to
1583// us. It's used to ensure that we're looking for the element type in
1584// the right context. It does NOT become the class loader for the
1585// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001586//
1587// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001588Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001589 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001590
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001591 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001592 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001593 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001594 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001595 return NULL;
1596 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001597
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001598 // See if the component type is already loaded. Array classes are
1599 // always associated with the class loader of their underlying
1600 // element type -- an array of Strings goes with the loader for
1601 // java/lang/String -- so we need to look for it there. (The
1602 // caller should have checked for the existence of the class
1603 // before calling here, but they did so with *their* class loader,
1604 // not the component type's loader.)
1605 //
1606 // If we find it, the caller adds "loader" to the class' initiating
1607 // loader list, which should prevent us from going through this again.
1608 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001609 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001610 // are the same, because our caller (FindClass) just did the
1611 // lookup. (Even if we get this wrong we still have correct behavior,
1612 // because we effectively do this lookup again when we add the new
1613 // class to the hash table --- necessary because of possible races with
1614 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001615 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001616 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001617 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001618 return new_class;
1619 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001620 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001621
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001622 // Fill out the fields in the Class.
1623 //
1624 // It is possible to execute some methods against arrays, because
1625 // all arrays are subclasses of java_lang_Object_, so we need to set
1626 // up a vtable. We can just point at the one in java_lang_Object_.
1627 //
1628 // Array classes are simple enough that we don't need to do a full
1629 // link step.
1630
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001631 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001632 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001633 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001634 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001635 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001636 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001637 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001638 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001639 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001640 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001641 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001642 }
1643 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001644 if (new_class.get() == NULL) {
1645 new_class.reset(AllocClass(sizeof(Class)));
1646 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001647 return NULL;
1648 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001649 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001650 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001651 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001652 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001653 new_class->SetSuperClass(java_lang_Object);
1654 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001655 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001656 new_class->SetClassLoader(component_type->GetClassLoader());
1657 new_class->SetStatus(Class::kStatusInitialized);
1658 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001659 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001660
1661
1662 // All arrays have java/lang/Cloneable and java/io/Serializable as
1663 // interfaces. We need to set that up here, so that stuff like
1664 // "instanceof" works right.
1665 //
1666 // Note: The GC could run during the call to FindSystemClass,
1667 // so we need to make sure the class object is GC-valid while we're in
1668 // there. Do this by clearing the interface list so the GC will just
1669 // think that the entries are null.
1670
1671
1672 // Use the single, global copies of "interfaces" and "iftable"
1673 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001674 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001675 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001676
1677 // Inherit access flags from the component type. Arrays can't be
1678 // used as a superclass or interface, so we want to add "final"
1679 // and remove "interface".
1680 //
1681 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001682 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001683 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001684 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1685 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001686
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001687 Class* existing = InsertClass(descriptor, new_class.get(), false);
1688 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001689 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001690 }
1691 // Another thread must have loaded the class after we
1692 // started but before we finished. Abandon what we've
1693 // done.
1694 //
1695 // (Yes, this happens.)
1696
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001697 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001698}
1699
1700Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001701 switch (Primitive::GetType(type)) {
1702 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001703 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001704 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001705 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001706 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001707 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001708 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001709 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001710 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001711 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001712 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001713 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001714 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001715 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001716 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001717 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001718 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001719 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001720 case Primitive::kPrimNot:
1721 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001722 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001723 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001724 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001725 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001726}
1727
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001728Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001729 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001730 DexCache* dex_cache = klass->GetDexCache();
1731 std::string source;
1732 if (dex_cache != NULL) {
1733 source += " from ";
1734 source += dex_cache->GetLocation()->ToModifiedUtf8();
1735 }
1736 LOG(INFO) << "Loaded class " << descriptor << source;
1737 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001738 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001739 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001740 Table& classes = image_class ? image_classes_ : classes_;
1741 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1742#ifndef NDEBUG
1743 // Check we don't have the class in the other table in error
1744 Table& other_classes = image_class ? classes_ : image_classes_;
1745 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1746#endif
1747 if (existing != NULL) {
1748 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001749 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001750 classes.insert(std::make_pair(hash, klass));
1751 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001752}
1753
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001754bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1755 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001756 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001757 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001758 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001759 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001760 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001761 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001762 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001763 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001764 classes_.erase(it);
1765 return true;
1766 }
1767 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001768 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001769 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001770 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001771 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001772 image_classes_.erase(it);
1773 return true;
1774 }
1775 }
1776 return false;
1777}
1778
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001779Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1780 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001781 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001782 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001783 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1784 if (klass != NULL) {
1785 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001786 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001787 return LookupClass(descriptor, class_loader, hash, image_classes_);
1788}
1789
1790Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1791 size_t hash, const Table& classes) {
1792 ClassHelper kh(NULL, this);
1793 typedef Table::const_iterator It; // TODO: C++0x auto
1794 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001795 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001796 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001797 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001798#ifndef NDEBUG
1799 for (++it; it != end && it->first == hash; ++it) {
1800 kh.ChangeClass(it->second);
1801 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader))
1802 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
1803 << PrettyClass(it->second) << " " << it->second << " " << it->second->GetClassLoader();
1804 }
1805#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001806 return klass;
1807 }
1808 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001809 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001810}
1811
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001812void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001813 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001814 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001815 MutexLock mu(classes_lock_);
1816 typedef Table::const_iterator It; // TODO: C++0x auto
1817 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001818 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001819 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001820 Class* klass = it->second;
1821 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001822 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001823 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001824 }
1825 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001826 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001827 Class* klass = it->second;
1828 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001829 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001830 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001831 }
1832 }
1833}
1834
Ian Rogersc20a83e2012-01-18 18:15:32 -08001835#ifndef NDEBUG
1836static void CheckMethodsHaveGcMaps(Class* klass) {
1837 if (!Runtime::Current()->IsStarted()) {
1838 return;
1839 }
1840 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1841 Method* method = klass->GetDirectMethod(i);
1842 if (!method->IsNative() && !method->IsAbstract()) {
1843 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1844 }
1845 }
1846 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1847 Method* method = klass->GetVirtualMethod(i);
1848 if (!method->IsNative() && !method->IsAbstract()) {
1849 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1850 }
1851 }
1852}
1853#else
1854static void CheckMethodsHaveGcMaps(Class* klass) {
1855}
1856#endif
1857
jeffhao98eacac2011-09-14 16:11:53 -07001858void ClassLinker::VerifyClass(Class* klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001859 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001860 if (klass->IsVerified()) {
1861 return;
1862 }
1863
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001864 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001865 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001866
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001867 // Try to use verification information from oat file, otherwise do runtime verification
1868 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
1869 if (VerifyClassUsingOatFile(dex_file, klass) || verifier::DexVerifier::VerifyClass(klass)) {
1870 // Make sure all classes referenced by catch blocks are resolved
1871 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001872 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001873 // Sanity check that a verified class has GC maps on all methods
1874 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001875 } else {
1876 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001877 Thread* self = Thread::Current();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001878 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001879 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001880 PrettyDescriptor(klass).c_str());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001881 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001882 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001883 }
jeffhao98eacac2011-09-14 16:11:53 -07001884}
1885
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001886bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1887 if (!Runtime::Current()->IsStarted()) {
1888 return false;
1889 }
1890 if (ClassLoader::UseCompileTimeClassPath()) {
1891 return false;
1892 }
1893 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
1894 if (oat_file == NULL) {
1895 return false;
1896 }
1897 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1898 CHECK(oat_dex_file != NULL) << PrettyClass(klass);
1899 const char* descriptor = ClassHelper(klass).GetDescriptor();
1900 uint32_t class_def_index;
1901 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1902 CHECK(found) << descriptor;
1903 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
1904 CHECK(oat_class.get() != NULL) << descriptor;
1905 Class::Status status = oat_class->GetStatus();
1906 if (status == Class::kStatusError) {
1907 ThrowEarlierClassFailure(klass);
1908 klass->SetVerifyErrorClass(Thread::Current()->GetException()->GetClass());
1909 klass->SetStatus(Class::kStatusError);
1910 return true;
1911 }
1912 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1913 return true;
1914 }
1915 if (status == Class::kStatusNotReady) {
1916 return false;
1917 }
1918 LOG(FATAL) << "Unexpected class status: " << status;
1919 return false;
1920}
1921
1922void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
1923 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1924 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
1925 }
1926 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1927 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
1928 }
1929}
1930
1931void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
1932 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
1933 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
1934 if (code_item == NULL) {
1935 return; // native or abstract method
1936 }
1937 if (code_item->tries_size_ == 0) {
1938 return; // nothing to process
1939 }
1940 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
1941 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
1942 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1943 for (uint32_t idx = 0; idx < handlers_size; idx++) {
1944 CatchHandlerIterator iterator(handlers_ptr);
1945 for (; iterator.HasNext(); iterator.Next()) {
1946 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1947 // unresolved exception types will be ignored by exception delivery
1948 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
1949 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
1950 if (exception_type == NULL) {
1951 DCHECK(Thread::Current()->IsExceptionPending());
1952 Thread::Current()->ClearException();
1953 }
1954 }
1955 }
1956 handlers_ptr = iterator.EndDataPointer();
1957 }
1958}
1959
Ian Rogersc2b44472011-12-14 21:17:17 -08001960static void CheckProxyConstructor(Method* constructor);
1961static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1962
Jesse Wilson95caa792011-10-12 18:14:17 -04001963Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001964 ClassLoader* loader, ObjectArray<Method>* methods,
1965 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001966 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001967 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001968 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001969 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001970 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001971 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001972 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001973 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001974 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001975 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001976
1977 klass->SetStatus(Class::kStatusIdx);
1978
1979 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1980
1981 // Create static field that holds throws, instance fields are inherited
1982 klass->SetSFields(AllocObjectArray<Field>(1));
1983 SirtRef<Field> sfield(AllocField());
1984 klass->SetStaticField(0, sfield.get());
1985 sfield->SetDexFieldIndex(-1);
1986 sfield->SetDeclaringClass(klass.get());
1987 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001988
Ian Rogers466bb252011-10-14 03:29:56 -07001989 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001990 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001991 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001992
Ian Rogers466bb252011-10-14 03:29:56 -07001993 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001994 size_t num_virtual_methods = methods->GetLength();
1995 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1996 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001997 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001998 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001999 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002000
2001 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
2002 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
2003 DCHECK(!Thread::Current()->IsExceptionPending());
2004
2005 // Link the fields and virtual methods, creating vtable and iftables
2006 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04002007 DCHECK(Thread::Current()->IsExceptionPending());
2008 return NULL;
2009 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002010 sfield->SetObject(NULL, throws); // initialize throws field
2011 klass->SetStatus(Class::kStatusInitialized);
2012
2013 // sanity checks
2014#ifndef NDEBUG
2015 bool debug = true;
2016#else
2017 bool debug = false;
2018#endif
2019 if (debug) {
2020 CHECK(klass->GetIFields() == NULL);
2021 CheckProxyConstructor(klass->GetDirectMethod(0));
2022 for (size_t i = 0; i < num_virtual_methods; ++i) {
2023 SirtRef<Method> prototype(methods->Get(i));
2024 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2025 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002026 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002027 throws_field_name += name->ToModifiedUtf8();
2028 throws_field_name += ".throws";
2029 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2030
2031 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2032 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2033 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002034 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002035}
2036
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002037std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2038 DCHECK(proxy_class->IsProxyClass());
2039 String* name = proxy_class->GetName();
2040 DCHECK(name != NULL);
2041 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2042}
2043
2044
2045Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002046 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002047 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002048 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002049 Method* proxy_constructor = proxy_direct_methods->Get(2);
2050 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2051 // code_ too)
2052 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2053 // Make this constructor public and fix the class to be our Proxy version
2054 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002055 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002056 return constructor;
2057}
2058
2059static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002060 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002061 MethodHelper mh(constructor);
2062 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002063 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002064 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002065}
2066
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002067Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2068 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2069 // prototype method
2070 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2071 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002072 // as necessary
2073 Method* method = down_cast<Method*>(prototype->Clone());
2074
2075 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2076 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002077 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002078 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002079
Ian Rogers466bb252011-10-14 03:29:56 -07002080 // At runtime the method looks like a reference and argument saving method, clone the code
2081 // related parameters from this method.
2082 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2083 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2084 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2085 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2086 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002087 return method;
2088}
Jesse Wilson95caa792011-10-12 18:14:17 -04002089
Ian Rogersc2b44472011-12-14 21:17:17 -08002090static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002091 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002092 CHECK(!prototype->IsFinal());
2093 CHECK(method->IsFinal());
2094 CHECK(!method->IsAbstract());
2095 MethodHelper mh(method);
2096 const char* method_name = mh.GetName();
2097 const char* method_shorty = mh.GetShorty();
2098 Class* method_return = mh.GetReturnType();
2099
2100 mh.ChangeMethod(prototype.get());
2101
2102 CHECK_STREQ(mh.GetName(), method_name);
2103 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002104
2105 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002106 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002107}
2108
Brian Carlstrom25c33252011-09-18 15:58:35 -07002109bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002110 CHECK(klass->IsResolved() || klass->IsErroneous())
2111 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002112
Carl Shapirob5573532011-07-12 18:22:59 -07002113 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002114
Brian Carlstrom25c33252011-09-18 15:58:35 -07002115 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002116 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002117 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118 ObjectLock lock(klass);
2119
Brian Carlstromd1422f82011-09-28 11:37:09 -07002120 if (klass->GetStatus() == Class::kStatusInitialized) {
2121 return true;
2122 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002123
Brian Carlstromd1422f82011-09-28 11:37:09 -07002124 if (klass->IsErroneous()) {
2125 ThrowEarlierClassFailure(klass);
2126 return false;
2127 }
2128
2129 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002130 VerifyClass(klass);
2131 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002132 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002133 return false;
2134 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002135 }
2136
Brian Carlstrom25c33252011-09-18 15:58:35 -07002137 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2138 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002139 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002140 // don't bother going to kStatusInitializing. We return true to maintain
2141 // the invariant that a false result implies there is a pending exception.
2142 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002143 }
2144
Brian Carlstromd1422f82011-09-28 11:37:09 -07002145 // If the class is kStatusInitializing, either this thread is
2146 // initializing higher up the stack or another thread has beat us
2147 // to initializing and we need to wait. Either way, this
2148 // invocation of InitializeClass will not be responsible for
2149 // running <clinit> and will return.
2150 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002151 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002152 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002153 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002154 return true;
2155 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002156 // No. That's fine. Wait for another thread to finish initializing.
2157 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002158 }
2159
2160 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002161 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002162 klass->SetStatus(Class::kStatusError);
2163 return false;
2164 }
2165
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002166 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002167
Elliott Hughesdcc24742011-09-07 14:02:44 -07002168 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002169 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002170 }
2171
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002172 uint64_t t0 = NanoTime();
2173
Brian Carlstrom25c33252011-09-18 15:58:35 -07002174 if (!InitializeSuperClass(klass, can_run_clinit)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002175 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002176 return false;
2177 }
2178
2179 InitializeStaticFields(klass);
2180
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002181 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002182 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002183 }
2184
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002185 uint64_t t1 = NanoTime();
2186
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002187 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002188 {
2189 ObjectLock lock(klass);
2190
2191 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002192 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002193 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002194 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002195 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002196 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2197 RuntimeStats* thread_stats = self->GetStats();
2198 ++global_stats->class_init_count;
2199 ++thread_stats->class_init_count;
2200 global_stats->class_init_time_ns += (t1 - t0);
2201 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002202 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002203 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002204 ClassHelper kh(klass);
2205 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002206 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002207 }
2208 lock.NotifyAll();
2209 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002210 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002211}
2212
Brian Carlstromd1422f82011-09-28 11:37:09 -07002213bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2214 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002215 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002216 lock.Wait();
2217
2218 // When we wake up, repeat the test for init-in-progress. If
2219 // there's an exception pending (only possible if
2220 // "interruptShouldThrow" was set), bail out.
2221 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002222 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002223 klass->SetStatus(Class::kStatusError);
2224 return false;
2225 }
2226 // Spurious wakeup? Go back to waiting.
2227 if (klass->GetStatus() == Class::kStatusInitializing) {
2228 continue;
2229 }
2230 if (klass->IsErroneous()) {
2231 // The caller wants an exception, but it was thrown in a
2232 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002233 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002234 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002235 return false;
2236 }
2237 if (klass->IsInitialized()) {
2238 return true;
2239 }
2240 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2241 }
2242 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2243}
2244
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002245bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2246 if (klass->IsInterface()) {
2247 return true;
2248 }
2249 // begin with the methods local to the superclass
2250 if (klass->HasSuperClass() &&
2251 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2252 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002253 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2254 const Method* method = klass->GetVTable()->Get(i);
2255 if (method != super->GetVTable()->Get(i) &&
2256 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002257 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2258 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2259 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002260 return false;
2261 }
2262 }
2263 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002264 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2265 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2266 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002267 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2268 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002269 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002270 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2271 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002272 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2273 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2274 PrettyMethod(method).c_str(),
2275 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002276 return false;
2277 }
2278 }
2279 }
2280 }
2281 return true;
2282}
2283
Ian Rogers595799e2012-01-11 17:32:51 -08002284// Returns true if classes referenced by the signature of the method are the
2285// same classes in klass1 as they are in klass2.
2286bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2287 const Class* klass1,
2288 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002289 if (klass1 == klass2) {
2290 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002291 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002292 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002293 const DexFile::ProtoId& proto_id =
2294 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002295 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2296 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002297 if (descriptor == NULL) {
2298 break;
2299 }
2300 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2301 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002302 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002303 return false;
2304 }
2305 }
2306 }
2307 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002308 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002309 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002310 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002311 return false;
2312 }
2313 }
2314 return true;
2315}
2316
Ian Rogers595799e2012-01-11 17:32:51 -08002317// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2318bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2319 const Class* klass1,
2320 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002321 CHECK(descriptor != NULL);
2322 CHECK(klass1 != NULL);
2323 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002324 if (klass1 == klass2) {
2325 return true;
2326 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002327 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002328 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002329 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002330 }
Ian Rogers595799e2012-01-11 17:32:51 -08002331 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2332 if (found2 == NULL) {
2333 Thread::Current()->ClearException();
2334 }
2335 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002336}
2337
Brian Carlstrom25c33252011-09-18 15:58:35 -07002338bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002339 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002340 if (!klass->IsInterface() && klass->HasSuperClass()) {
2341 Class* super_class = klass->GetSuperClass();
2342 if (super_class->GetStatus() != Class::kStatusInitialized) {
2343 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002344 Thread* self = Thread::Current();
2345 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002346 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002347 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002348 // TODO: check for a pending exception
2349 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002350 if (!can_run_clinit) {
2351 // Don't set status to error when we can't run <clinit>.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002352 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002353 klass->SetStatus(Class::kStatusVerified);
2354 return false;
2355 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002356 klass->SetStatus(Class::kStatusError);
2357 klass->NotifyAll();
2358 return false;
2359 }
2360 }
2361 }
2362 return true;
2363}
2364
Brian Carlstrom25c33252011-09-18 15:58:35 -07002365bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002366 CHECK(c != NULL);
2367 if (c->IsInitialized()) {
2368 return true;
2369 }
2370
Elliott Hughes5f791332011-09-15 17:45:30 -07002371 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002372 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002373 bool success = InitializeClass(c, can_run_clinit);
2374 if (!success) {
2375 CHECK(self->IsExceptionPending());
2376 }
2377 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002378}
2379
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002380void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002381 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002382 const ClassLoader* cl = c->GetClassLoader();
2383 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002384 ClassDataItemIterator it(dex_file, class_data);
2385 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2386 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002387 }
2388}
2389
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002390void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002391 size_t num_static_fields = klass->NumStaticFields();
2392 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002393 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002394 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002395 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002396 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002397 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002398 return;
2399 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002400 ClassHelper kh(klass);
2401 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002402 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002403 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002404 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002405
Ian Rogers0571d352011-11-03 19:51:38 -07002406 if (it.HasNext()) {
2407 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2408 std::map<uint32_t, Field*> field_map;
2409 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2410 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2411 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002412 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002413 }
2414}
2415
Ian Rogersc2b44472011-12-14 21:17:17 -08002416bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002417 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002418 if (!LinkSuperClass(klass)) {
2419 return false;
2420 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002421 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002422 return false;
2423 }
2424 if (!LinkInstanceFields(klass)) {
2425 return false;
2426 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002427 if (!LinkStaticFields(klass)) {
2428 return false;
2429 }
2430 CreateReferenceInstanceOffsets(klass);
2431 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002432 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2433 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002434 return true;
2435}
2436
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002437bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002438 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002439 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2440 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002441 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002442 uint16_t super_class_idx = class_def->superclass_idx_;
2443 if (super_class_idx != DexFile::kDexNoIndex16) {
2444 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002445 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002446 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002447 return false;
2448 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002449 // Verify
2450 if (!klass->CanAccess(super_class)) {
2451 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2452 "Class %s extended by class %s is inaccessible",
2453 PrettyDescriptor(super_class).c_str(),
2454 PrettyDescriptor(klass.get()).c_str());
2455 return false;
2456 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002457 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002458 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002459 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2460 if (interfaces != NULL) {
2461 for (size_t i = 0; i < interfaces->Size(); i++) {
2462 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2463 Class* interface = ResolveType(dex_file, idx, klass.get());
2464 if (interface == NULL) {
2465 DCHECK(Thread::Current()->IsExceptionPending());
2466 return false;
2467 }
2468 // Verify
2469 if (!klass->CanAccess(interface)) {
2470 // TODO: the RI seemed to ignore this in my testing.
2471 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2472 "Interface %s implemented by class %s is inaccessible",
2473 PrettyDescriptor(interface).c_str(),
2474 PrettyDescriptor(klass.get()).c_str());
2475 return false;
2476 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002477 }
2478 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002479 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002480 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002481 return true;
2482}
2483
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002484bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002485 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002486 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002487 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002488 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002489 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002490 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002491 return false;
2492 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002493 return true;
2494 }
2495 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002496 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002497 return false;
2498 }
2499 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002500 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002501 Thread* thread = Thread::Current();
2502 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002503 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002504 PrettyDescriptor(super).c_str(),
2505 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002506 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002507 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002508 return false;
2509 }
2510 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002511 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002512 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002513 PrettyDescriptor(super).c_str(),
2514 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002515 return false;
2516 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002517
2518 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2519 if (super->IsFinalizable()) {
2520 klass->SetFinalizable();
2521 }
2522
Elliott Hughes2da50362011-10-10 16:57:08 -07002523 // Inherit reference flags (if any) from the superclass.
2524 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2525 if (reference_flags != 0) {
2526 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2527 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002528 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002529 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002530 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002531 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002532 return false;
2533 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002534
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002535#ifndef NDEBUG
2536 // Ensure super classes are fully resolved prior to resolving fields..
2537 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002538 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002539 super = super->GetSuperClass();
2540 }
2541#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002542 return true;
2543}
2544
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002545// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002546bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002547 if (klass->IsInterface()) {
2548 // No vtable.
2549 size_t count = klass->NumVirtualMethods();
2550 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002551 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002552 return false;
2553 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002554 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002555 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002556 }
jeffhaobdb76512011-09-07 11:43:16 -07002557 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002558 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002559 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002560 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002561 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002562 }
2563 return true;
2564}
2565
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002566bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002567 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002568 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2569 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002570 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002571 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002572 SirtRef<ObjectArray<Method> > vtable(klass->GetSuperClass()->GetVTable()->CopyOf(max_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002573 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002574 MethodHelper local_mh(NULL, this);
2575 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002576 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002578 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002579 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002580 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002581 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002582 super_mh.ChangeMethod(super_method);
2583 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 // Verify
2585 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002586 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002587 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002588 PrettyDescriptor(klass.get()).c_str(),
2589 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002590 return false;
2591 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002592 vtable->Set(j, local_method);
2593 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002594 break;
2595 }
2596 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002597 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002598 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002599 vtable->Set(actual_count, local_method);
2600 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002601 actual_count += 1;
2602 }
2603 }
2604 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002605 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002606 return false;
2607 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002608 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002609 CHECK_LE(actual_count, max_count);
2610 if (actual_count < max_count) {
Ian Rogers30fab402012-01-23 15:43:46 -08002611 vtable.reset(vtable->CopyOf(actual_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002612 }
Ian Rogers30fab402012-01-23 15:43:46 -08002613 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002614 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002615 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002616 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002617 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002618 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002619 return false;
2620 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002621 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002622 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002623 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2624 vtable->Set(i, virtual_method);
2625 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002626 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002627 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002628 }
2629 return true;
2630}
2631
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002632bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002633 size_t super_ifcount;
2634 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002635 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002636 } else {
2637 super_ifcount = 0;
2638 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002639 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002640 ClassHelper kh(klass.get(), this);
2641 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2642 ifcount += num_interfaces;
2643 for (size_t i = 0; i < num_interfaces; i++) {
2644 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2645 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002646 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002647 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002648 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002649 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002650 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002651 return true;
2652 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002653 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002654 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002655 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2656 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002657 Class* super_interface = super_iftable->Get(i)->GetInterface();
2658 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002659 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002660 }
2661 // Flatten the interface inheritance hierarchy.
2662 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002663 for (size_t i = 0; i < num_interfaces; i++) {
2664 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002665 DCHECK(interface != NULL);
2666 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002667 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002668 Thread* thread = Thread::Current();
2669 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002670 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002671 PrettyDescriptor(klass.get()).c_str(),
2672 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002673 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002674 return false;
2675 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002676 // Check if interface is already in iftable
2677 bool duplicate = false;
2678 for (size_t j = 0; j < idx; j++) {
2679 Class* existing_interface = iftable->Get(j)->GetInterface();
2680 if (existing_interface == interface) {
2681 duplicate = true;
2682 break;
2683 }
2684 }
2685 if (!duplicate) {
2686 // Add this non-duplicate interface.
2687 iftable->Set(idx++, AllocInterfaceEntry(interface));
2688 // Add this interface's non-duplicate super-interfaces.
2689 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2690 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2691 bool super_duplicate = false;
2692 for (size_t k = 0; k < idx; k++) {
2693 Class* existing_interface = iftable->Get(k)->GetInterface();
2694 if (existing_interface == super_interface) {
2695 super_duplicate = true;
2696 break;
2697 }
2698 }
2699 if (!super_duplicate) {
2700 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2701 }
2702 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002703 }
2704 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002705 // Shrink iftable in case duplicates were found
2706 if (idx < ifcount) {
2707 iftable.reset(iftable->CopyOf(idx));
2708 ifcount = idx;
2709 } else {
2710 CHECK_EQ(idx, ifcount);
2711 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002712 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002713
2714 // If we're an interface, we don't need the vtable pointers, so we're done.
2715 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002716 return true;
2717 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002718 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002719 MethodHelper vtable_mh(NULL, this);
2720 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002721 for (size_t i = 0; i < ifcount; ++i) {
2722 InterfaceEntry* interface_entry = iftable->Get(i);
2723 Class* interface = interface_entry->GetInterface();
2724 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2725 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002726 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002727 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2728 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002729 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002730 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002731 // For each method listed in the interface's method list, find the
2732 // matching method in our class's method list. We want to favor the
2733 // subclass over the superclass, which just requires walking
2734 // back from the end of the vtable. (This only matters if the
2735 // superclass defines a private method and this class redefines
2736 // it -- otherwise it would use the same vtable slot. In .dex files
2737 // those don't end up in the virtual method table, so it shouldn't
2738 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002739 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2740 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002741 vtable_mh.ChangeMethod(vtable_method);
2742 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002743 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002744 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002745 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002746 return false;
2747 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002748 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002749 break;
2750 }
2751 }
2752 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002753 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002754 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002755 Method* mir_method = miranda_list[mir];
2756 vtable_mh.ChangeMethod(mir_method);
2757 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002758 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002759 break;
2760 }
2761 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002762 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002763 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002764 miranda_method.reset(AllocMethod());
2765 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2766 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002767 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002768 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002769 }
2770 }
2771 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002772 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002773 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002774 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002775 klass->SetVirtualMethods((old_method_count == 0)
2776 ? AllocObjectArray<Method>(new_method_count)
2777 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002778
Ian Rogers30fab402012-01-23 15:43:46 -08002779 SirtRef<ObjectArray<Method> > vtable(klass->GetVTableDuringLinking());
2780 CHECK(vtable.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002781 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002782 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers30fab402012-01-23 15:43:46 -08002783 vtable.reset(vtable->CopyOf(new_vtable_count));
Elliott Hughes4681c802011-09-25 18:04:37 -07002784 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002785 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002786 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002787 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2788 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2789 klass->SetVirtualMethod(old_method_count + i, method);
2790 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002791 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002792 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers30fab402012-01-23 15:43:46 -08002793 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002794 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002795
2796 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2797 for (int i = 0; i < vtable->GetLength(); ++i) {
2798 CHECK(vtable->Get(i) != NULL);
2799 }
2800
2801// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2802
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002803 return true;
2804}
2805
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002806bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2807 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002808 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002809}
2810
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002811bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2812 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002813 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002814 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002815 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002816 return success;
2817}
2818
Brian Carlstromdbc05252011-09-09 01:59:59 -07002819struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002820 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002821 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002822 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002823 fh_->ChangeField(field1);
2824 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2825 fh_->ChangeField(field2);
2826 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002827 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2828 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2829 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2830 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002831 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2832 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2833 if (order1 != order2) {
2834 return order1 < order2;
2835 }
2836
2837 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002838 fh_->ChangeField(field1);
2839 StringPiece name1(fh_->GetName());
2840 fh_->ChangeField(field2);
2841 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002842 return name1 < name2;
2843 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002844
2845 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002846};
2847
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002848bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002849 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002850 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002851
2852 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002853 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002854
2855 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002856 size_t size;
2857 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002858 if (is_static) {
2859 size = klass->GetClassSize();
2860 field_offset = Class::FieldsOffset();
2861 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002862 Class* super_class = klass->GetSuperClass();
2863 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002864 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002865 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002866 }
2867 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002868 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002869
Brian Carlstromdbc05252011-09-09 01:59:59 -07002870 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002871
Brian Carlstromdbc05252011-09-09 01:59:59 -07002872 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002873 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002874 std::deque<Field*> grouped_and_sorted_fields;
2875 for (size_t i = 0; i < num_fields; i++) {
2876 grouped_and_sorted_fields.push_back(fields->Get(i));
2877 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002878 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002879 std::sort(grouped_and_sorted_fields.begin(),
2880 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002881 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002882
2883 // References should be at the front.
2884 size_t current_field = 0;
2885 size_t num_reference_fields = 0;
2886 for (; current_field < num_fields; current_field++) {
2887 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002888 fh.ChangeField(field);
2889 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002890 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002891 if (isPrimitive) {
2892 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002893 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002894 grouped_and_sorted_fields.pop_front();
2895 num_reference_fields++;
2896 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002897 field->SetOffset(field_offset);
2898 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002899 }
2900
2901 // Now we want to pack all of the double-wide fields together. If
2902 // we're not aligned, though, we want to shuffle one 32-bit field
2903 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002904 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002905 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2906 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002907 fh.ChangeField(field);
2908 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002909 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2910 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002911 continue;
2912 }
2913 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002914 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002915 // drop the consumed field
2916 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2917 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002918 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002919 // whether we found a 32-bit field for padding or not, we advance
2920 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002921 }
2922
2923 // Alignment is good, shuffle any double-wide fields forward, and
2924 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002925 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002926 while (!grouped_and_sorted_fields.empty()) {
2927 Field* field = grouped_and_sorted_fields.front();
2928 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002929 fh.ChangeField(field);
2930 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002931 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002932 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002933 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002934 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002935 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002936 ? sizeof(uint64_t)
2937 : sizeof(uint32_t)));
2938 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002939 }
2940
Elliott Hughesadb460d2011-10-05 17:02:34 -07002941 // We lie to the GC about the java.lang.ref.Reference.referent field, so it doesn't scan it.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002942 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2943 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002944 // We know there are no non-reference fields in the Reference classes, and we know
2945 // that 'referent' is alphabetically last, so this is easy...
2946 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002947 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08002948 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002949 --num_reference_fields;
2950 }
2951
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002952#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002953 // Make sure that all reference fields appear before
2954 // non-reference fields, and all double-wide fields are aligned.
2955 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002956 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002957 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002958 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002959 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002960 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002961 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002962 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2963 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002964 fh.ChangeField(field);
2965 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002966 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002967 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002968 is_primitive = true; // We lied above, so we have to expect a lie here.
2969 }
2970 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002971 if (!seen_non_ref) {
2972 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002973 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002974 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002975 } else {
2976 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002977 }
2978 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002979 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002980 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002981 }
2982#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002983 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002984 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002985 if (is_static) {
2986 klass->SetNumReferenceStaticFields(num_reference_fields);
2987 klass->SetClassSize(size);
2988 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002989 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002990 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002991 klass->SetObjectSize(size);
2992 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002993 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002994 return true;
2995}
2996
2997// Set the bitmap of reference offsets, refOffsets, from the ifields
2998// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002999void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003000 uint32_t reference_offsets = 0;
3001 Class* super_class = klass->GetSuperClass();
3002 if (super_class != NULL) {
3003 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003004 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003005 if (reference_offsets == CLASS_WALK_SUPER) {
3006 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003007 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003008 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003009 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003010 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003011}
3012
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003013void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003014 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003015}
3016
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003017void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003018 uint32_t reference_offsets) {
3019 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003020 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3021 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003022 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003023 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003024 // All of the fields that contain object references are guaranteed
3025 // to be at the beginning of the fields list.
3026 for (size_t i = 0; i < num_reference_fields; ++i) {
3027 // Note that byte_offset is the offset from the beginning of
3028 // object, not the offset into instance data
3029 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003030 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003031 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3032 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3033 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003034 CHECK_NE(new_bit, 0U);
3035 reference_offsets |= new_bit;
3036 } else {
3037 reference_offsets = CLASS_WALK_SUPER;
3038 break;
3039 }
3040 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003041 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003042 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003043 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003044 } else {
3045 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003046 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003047}
3048
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003049String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003050 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003051 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003052 if (resolved != NULL) {
3053 return resolved;
3054 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003055 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3056 int32_t utf16_length = dex_file.GetStringLength(string_id);
3057 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003058 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003059 dex_cache->SetResolvedString(string_idx, string);
3060 return string;
3061}
3062
3063Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003064 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003065 DexCache* dex_cache,
3066 const ClassLoader* class_loader) {
3067 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003068 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003069 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003070 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003071 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003072 // TODO: we used to throw here if resolved's class loader was not the
3073 // boot class loader. This was to permit different classes with the
3074 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003075 dex_cache->SetResolvedType(type_idx, resolved);
3076 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003077 CHECK(Thread::Current()->IsExceptionPending())
3078 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003079 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003080 }
3081 return resolved;
3082}
3083
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003084Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3085 uint32_t method_idx,
3086 DexCache* dex_cache,
3087 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003088 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003089 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3090 if (resolved != NULL) {
3091 return resolved;
3092 }
3093 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3094 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3095 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003096 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003097 return NULL;
3098 }
3099
Ian Rogers0571d352011-11-03 19:51:38 -07003100 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3101 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003102 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003103 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003104 } else if (klass->IsInterface()) {
3105 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003106 } else {
3107 resolved = klass->FindVirtualMethod(name, signature);
3108 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003109 if (resolved != NULL) {
3110 dex_cache->SetResolvedMethod(method_idx, resolved);
3111 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003112 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003113 }
3114 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003115}
3116
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003117Field* ClassLinker::ResolveField(const DexFile& dex_file,
3118 uint32_t field_idx,
3119 DexCache* dex_cache,
3120 const ClassLoader* class_loader,
3121 bool is_static) {
3122 Field* resolved = dex_cache->GetResolvedField(field_idx);
3123 if (resolved != NULL) {
3124 return resolved;
3125 }
3126 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3127 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3128 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003129 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003130 return NULL;
3131 }
3132
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003133 const char* name = dex_file.GetFieldName(field_id);
3134 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003135 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003136 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003137 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003138 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003139 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003140 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003141 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003142 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003143 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3144 }
3145 return resolved;
3146}
3147
3148Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3149 uint32_t field_idx,
3150 DexCache* dex_cache,
3151 const ClassLoader* class_loader) {
3152 Field* resolved = dex_cache->GetResolvedField(field_idx);
3153 if (resolved != NULL) {
3154 return resolved;
3155 }
3156 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3157 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3158 if (klass == NULL) {
3159 DCHECK(Thread::Current()->IsExceptionPending());
3160 return NULL;
3161 }
3162
3163 const char* name = dex_file.GetFieldName(field_id);
3164 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3165 resolved = klass->FindField(name, type);
3166 if (resolved != NULL) {
3167 dex_cache->SetResolvedField(field_idx, resolved);
3168 } else {
3169 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003170 }
3171 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003172}
3173
Ian Rogersad25ac52011-10-04 19:13:33 -07003174const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3175 Class* declaring_class = referrer->GetDeclaringClass();
3176 DexCache* dex_cache = declaring_class->GetDexCache();
3177 const DexFile& dex_file = FindDexFile(dex_cache);
3178 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3179 return dex_file.GetShorty(method_id.proto_idx_);
3180}
3181
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003182void ClassLinker::DumpAllClasses(int flags) const {
3183 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3184 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3185 std::vector<Class*> all_classes;
3186 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003187 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003188 typedef Table::const_iterator It; // TODO: C++0x auto
3189 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3190 all_classes.push_back(it->second);
3191 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003192 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3193 all_classes.push_back(it->second);
3194 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003195 }
3196
3197 for (size_t i = 0; i < all_classes.size(); ++i) {
3198 all_classes[i]->DumpClass(std::cerr, flags);
3199 }
3200}
3201
Elliott Hughescac6cc72011-11-03 20:31:21 -07003202void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3203 MutexLock mu(classes_lock_);
3204 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3205 << classes_.size() << " allocated classes\n";
3206}
3207
Elliott Hughese27955c2011-08-26 15:21:24 -07003208size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003209 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003210 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003211}
3212
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003213pid_t ClassLinker::GetClassesLockOwner() {
3214 return classes_lock_.GetOwner();
3215}
3216
3217pid_t ClassLinker::GetDexLockOwner() {
3218 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003219}
3220
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003221void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3222 DCHECK(!init_done_);
3223
3224 DCHECK(klass != NULL);
3225 DCHECK(klass->GetClassLoader() == NULL);
3226
3227 DCHECK(class_roots_ != NULL);
3228 DCHECK(class_roots_->Get(class_root) == NULL);
3229 class_roots_->Set(class_root, klass);
3230}
3231
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003232} // namespace art