blob: 02d9acb8e30fcfbdc421066fbb13adc79df520d4 [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=");
561 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
562 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
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800584 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700585 "--runtime-arg", "-Xms64m",
586 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500587 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800588 "--runtime-arg", class_path,
589 boot_image_option,
590 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800591 oat_fd_option,
592 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700593 NULL);
594
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800595 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800596 return false;
jeffhao262bf462011-10-20 18:36:32 -0700597 } else {
598 // wait for dex2oat to finish
599 int status;
600 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
601 if (got_pid != pid) {
602 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800603 return false;
jeffhao262bf462011-10-20 18:36:32 -0700604 }
605 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800606 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
607 return false;
jeffhao262bf462011-10-20 18:36:32 -0700608 }
609 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800610 return true;
jeffhao262bf462011-10-20 18:36:32 -0700611}
612
Brian Carlstrom866c8622012-01-06 16:35:13 -0800613void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
614 MutexLock mu(dex_lock_);
615 RegisterOatFileLocked(oat_file);
616}
617
618void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
619 dex_lock_.AssertHeld();
620 oat_files_.push_back(&oat_file);
621}
622
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700623OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700624 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700625 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800626 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700627 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800628 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
629 // check the down cast
630 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700631 std::string oat_filename;
632 oat_filename += runtime->GetHostPrefix();
633 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700634 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700635 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700636 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700637 return NULL;
638 }
639 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
640 uint32_t image_oat_checksum = image_header.GetOatChecksum();
641 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800642 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700643 << " to expected oat checksum " << std::hex << oat_checksum
644 << " in image";
645 return NULL;
646 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800647 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800648 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700649 return oat_file;
650}
651
Brian Carlstromae826982011-11-09 01:33:42 -0800652const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
653 for (size_t i = 0; i < oat_files_.size(); i++) {
654 const OatFile* oat_file = oat_files_[i];
655 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800656 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800657 return oat_file;
658 }
659 }
660 return NULL;
661}
662
Brian Carlstromd601af82012-01-06 10:15:19 -0800663class LockedFd {
664 public:
665 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
666 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
667 if (fd == -1) {
668 PLOG(ERROR) << "Failed to open file '" << name << "'";
669 return NULL;
670 }
671 fchmod(fd, mode);
672
673 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
674 // try to lock non-blocking so we can log if we need may need to block
675 int result = flock(fd, LOCK_EX | LOCK_NB);
676 if (result == -1) {
677 LOG(WARNING) << "sleeping while locking file " << name;
678 // retry blocking
679 result = flock(fd, LOCK_EX);
680 }
681 if (result == -1) {
682 PLOG(ERROR) << "Failed to lock file '" << name << "'";
683 close(fd);
684 return NULL;
685 }
686 return new LockedFd(fd);
687 }
688
689 int GetFd() const {
690 return fd_;
691 }
692
693 ~LockedFd() {
694 if (fd_ != -1) {
695 int result = flock(fd_, LOCK_UN);
696 if (result == -1) {
697 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
698 }
699 close(fd_);
700 }
701 }
702
703 private:
704 explicit LockedFd(int fd) : fd_(fd) {}
705
706 int fd_;
707};
708
Brian Carlstromae826982011-11-09 01:33:42 -0800709const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700710 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800711 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
712 if (open_oat_file != NULL) {
713 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800714 }
715
Brian Carlstromd601af82012-01-06 10:15:19 -0800716 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800717 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
718 if (open_oat_file != NULL) {
719 return open_oat_file;
720 }
721
Brian Carlstromd601af82012-01-06 10:15:19 -0800722 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800723 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
724 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800725 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
726 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800727 RegisterOatFileLocked(*oat_file.get());
728 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800729 }
730 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
731 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
732 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
733 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
734 }
735 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700736 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800737 // Try to generate oat file if it wasn't found or was obsolete.
738 // Note we can be racing with another runtime to do this.
739 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
740 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
741 if (locked_fd.get() == NULL) {
742 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
743 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700744 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800745 // Check to see if the fd we opened and locked matches the file in
746 // the filesystem. If they don't, then somebody else unlinked ours
747 // and created a new file, and we need to use that one instead. (If
748 // we caught them between the unlink and the create, we'll get an
749 // ENOENT from the file stat.)
750 struct stat fd_stat;
751 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
752 if (fd_stat_result != 0) {
753 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
754 return NULL;
755 }
756 struct stat file_stat;
757 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
758 if (file_stat_result != 0
759 || fd_stat.st_dev != file_stat.st_dev
760 || fd_stat.st_ino != file_stat.st_ino) {
761 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
762 usleep(250 * 1000); // if something is hosed, don't peg machine
763 continue;
764 }
765
766 // We have the correct file open and locked. If the file size is
767 // zero, then it was just created by us and we can generate its
768 // contents. If not, someone else created it. Either way, we'll
769 // loop to retry opening the file.
770 if (fd_stat.st_size == 0) {
771 bool success = GenerateOatFile(dex_file.GetLocation(),
772 locked_fd->GetFd(),
773 oat_cache_filename);
774 if (!success) {
775 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
776 return NULL;
777 }
778 }
jeffhao262bf462011-10-20 18:36:32 -0700779 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800780 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700781}
782
Brian Carlstromae826982011-11-09 01:33:42 -0800783const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700784 for (size_t i = 0; i < oat_files_.size(); i++) {
785 const OatFile* oat_file = oat_files_[i];
786 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800787 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700788 return oat_file;
789 }
790 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700791 return NULL;
792}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700793
Brian Carlstromae826982011-11-09 01:33:42 -0800794const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800795 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700796 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800797 if (oat_location.empty() || oat_location[0] != '/') {
798 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700799 return NULL;
800 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700801
Brian Carlstroma9f19782011-10-13 00:14:47 -0700802 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800803 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800804 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700805 if (oat_file != NULL) {
806 return oat_file;
807 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700808 oat_file = OatFile::Open(cache_location, "", NULL);
809 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800810 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700811 return NULL;
812 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700813 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700814
Brian Carlstromae826982011-11-09 01:33:42 -0800815 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700816 return oat_file;
817}
818
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700819void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800820 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700821 CHECK(!init_done_);
822
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700823 const std::vector<Space*>& spaces = Heap::GetSpaces();
824 for (size_t i = 0; i < spaces.size(); i++) {
Elliott Hughesba8eee12012-01-24 20:25:24 -0800825 Space* space = spaces[i];
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700826 if (space->IsImageSpace()) {
827 OatFile* oat_file = OpenOat(space);
828 CHECK(oat_file != NULL) << "Failed to open oat file for image";
829 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
830 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
831
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800832 if (i == 0) {
833 // Special case of setting up the String class early so that we can test arbitrary objects
834 // as being Strings or not
835 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
836 ->AsObjectArray<Class>()->Get(kJavaLangString);
837 String::SetClass(java_lang_String);
838 }
839
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700840 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
841 static_cast<uint32_t>(dex_caches->GetLength()));
842 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700843 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800844 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800845 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
846 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700847 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800848 LOG(FATAL) << "Failed to open dex file " << dex_file_location
849 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700850 }
851
Brian Carlstromaded5f72011-10-07 17:15:04 -0700852 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700853
Brian Carlstromdf143242011-10-10 18:05:34 -0700854 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700855 }
856 }
857 }
858
Brian Carlstroma663ea52011-08-19 23:33:41 -0700859 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
860 DCHECK(heap_bitmap != NULL);
861
Brian Carlstroma663ea52011-08-19 23:33:41 -0700862 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700863 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700864
865 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700866 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
867 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700868
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800869 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700870 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
871 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800872 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700873 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700874 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700875 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
876 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
877 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
878 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
879 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
880 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
881 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
882 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700883 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700884 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700885
886 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700887
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800888 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700889}
890
Brian Carlstrom78128a62011-09-15 17:21:19 -0700891void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700892 DCHECK(obj != NULL);
893 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700894 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700895
Elliott Hughesdbb40792011-11-18 17:05:22 -0800896 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700897 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700898 return;
899 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700900 if (obj->IsClass()) {
901 // restore class to ClassLinker::classes_ table
902 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800903 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800904 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
905 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700906 return;
907 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700908}
909
910// Keep in sync with InitCallback. Anything we visit, we need to
911// reinit references to when reinitializing a ClassLinker from a
912// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700913void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
914 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700915
916 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700917 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700918 }
919
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700920 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700921 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700922 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700923 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700924 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700925 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700926 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700927 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700928
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700929 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700930}
931
Elliott Hughesa2155262011-11-16 16:26:58 -0800932void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
933 MutexLock mu(classes_lock_);
934 typedef Table::const_iterator It; // TODO: C++0x auto
935 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
936 if (!visitor(it->second, arg)) {
937 return;
938 }
939 }
940 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
941 if (!visitor(it->second, arg)) {
942 return;
943 }
944 }
945}
946
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700947ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700948 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700949 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700950 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700951 BooleanArray::ResetArrayClass();
952 ByteArray::ResetArrayClass();
953 CharArray::ResetArrayClass();
954 DoubleArray::ResetArrayClass();
955 FloatArray::ResetArrayClass();
956 IntArray::ResetArrayClass();
957 LongArray::ResetArrayClass();
958 ShortArray::ResetArrayClass();
959 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700960 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700961 STLDeleteElements(&boot_class_path_);
962 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700963}
964
965DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700966 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
967 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700968 return NULL;
969 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700970 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
971 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700972 return NULL;
973 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700974 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
975 if (strings.get() == NULL) {
976 return NULL;
977 }
978 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
979 if (types.get() == NULL) {
980 return NULL;
981 }
982 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
983 if (methods.get() == NULL) {
984 return NULL;
985 }
986 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
987 if (fields.get() == NULL) {
988 return NULL;
989 }
990 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
991 if (code_and_direct_methods.get() == NULL) {
992 return NULL;
993 }
994 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
995 if (initialized_static_storage.get() == NULL) {
996 return NULL;
997 }
998
999 dex_cache->Init(location.get(),
1000 strings.get(),
1001 types.get(),
1002 methods.get(),
1003 fields.get(),
1004 code_and_direct_methods.get(),
1005 initialized_static_storage.get());
1006 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001007}
1008
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001009CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1010 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001011}
1012
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001013InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1014 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001015 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1016 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001017 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001018 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001019}
1020
Brian Carlstrom4873d462011-08-21 15:23:39 -07001021Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1022 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001023 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001024 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001025 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001026 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001027}
1028
Brian Carlstrom4873d462011-08-21 15:23:39 -07001029Class* ClassLinker::AllocClass(size_t class_size) {
1030 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001031}
1032
Jesse Wilson35baaab2011-08-10 16:18:03 -04001033Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001034 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001035}
1036
1037Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001038 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001039}
1040
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001041ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1042 return ObjectArray<StackTraceElement>::Alloc(
1043 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1044 length);
1045}
1046
Brian Carlstromaded5f72011-10-07 17:15:04 -07001047Class* EnsureResolved(Class* klass) {
1048 DCHECK(klass != NULL);
1049 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001050 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001051 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001052 ObjectLock lock(klass);
1053 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001054 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001055 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001056 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001057 return NULL;
1058 }
1059 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001060 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001061 lock.Wait();
1062 }
1063 }
1064 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001065 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001066 return NULL;
1067 }
1068 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001069 CHECK(klass->IsResolved()) << PrettyClass(klass);
1070 CHECK(!self->IsExceptionPending())
1071 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1072 return klass;
1073}
1074
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001075Class* ClassLinker::FindSystemClass(const char* descriptor) {
1076 return FindClass(descriptor, NULL);
1077}
1078
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001079Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
Elliott Hughesba8eee12012-01-24 20:25:24 -08001080 DCHECK_NE(*descriptor, '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001081 Thread* self = Thread::Current();
1082 DCHECK(self != NULL);
1083 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001084 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001085 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1086 // for primitive classes that aren't backed by dex files.
1087 return FindPrimitiveClass(descriptor[0]);
1088 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001089 // Find the class in the loaded classes table.
1090 Class* klass = LookupClass(descriptor, class_loader);
1091 if (klass != NULL) {
1092 return EnsureResolved(klass);
1093 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001094 // Class is not yet loaded.
Elliott Hughesa7679b62012-01-24 17:15:23 -08001095 JNIEnv* env = self->GetJniEnv();
1096 ScopedLocalRef<jthrowable> cause(env, NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001097 if (descriptor[0] == '[') {
1098 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001099
Jesse Wilson47daf872011-11-23 11:42:45 -05001100 } else if (class_loader == NULL) {
1101 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1102 if (pair.second != NULL) {
1103 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1104 }
1105
1106 } else if (ClassLoader::UseCompileTimeClassPath()) {
1107 // first try the boot class path
1108 Class* system_class = FindSystemClass(descriptor);
1109 if (system_class != NULL) {
1110 return system_class;
1111 }
1112 CHECK(self->IsExceptionPending());
1113 self->ClearException();
1114
1115 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001116 const std::vector<const DexFile*>& class_path
1117 = ClassLoader::GetCompileTimeClassPath(class_loader);
1118 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001119 if (pair.second != NULL) {
1120 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001121 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001122
1123 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001124 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001125 ScopedThreadStateChange(self, Thread::kNative);
Jesse Wilson47daf872011-11-23 11:42:45 -05001126 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1127 CHECK(c.get() != NULL);
1128 // TODO: cache method?
1129 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1130 CHECK(mid != NULL);
1131 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1132 if (class_name_object.get() == NULL) {
1133 return NULL;
1134 }
1135 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001136 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1137 class_name_object.get()));
Elliott Hughesa7679b62012-01-24 17:15:23 -08001138 cause.reset(env->ExceptionOccurred());
1139 if (cause.get() != NULL) {
1140 env->ExceptionClear();
1141 // Failed to find class, so fall-through to throw NCDFE.
Ian Rogers761bfa82012-01-11 10:14:05 -08001142 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001143 // broken loader - throw NPE to be compatible with Dalvik
1144 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1145 class_name_string.c_str());
1146 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001147 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001148 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001149 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001150 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001151 }
1152
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001153 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Elliott Hughesa7679b62012-01-24 17:15:23 -08001154 if (cause.get() != NULL) {
1155 // Initialize the cause of the NCDFE.
1156 ScopedLocalRef<jthrowable> ncdfe(env, env->ExceptionOccurred());
1157 env->ExceptionClear();
Elliott Hughes844f9a02012-01-24 20:19:58 -08001158 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 -08001159 env->CallObjectMethod(ncdfe.get(), initCause_mid, cause.get());
1160 env->Throw(ncdfe.get());
1161 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001162 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001163}
1164
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001165Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001166 const ClassLoader* class_loader,
1167 const DexFile& dex_file,
1168 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001169 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001170 // Load the class from the dex file.
1171 if (!init_done_) {
1172 // finish up init of hand crafted class_roots_
1173 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001174 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001175 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001176 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001177 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001178 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001179 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001180 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001181 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001182 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001183 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001184 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001185 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001186 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 }
1188 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001189 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001190 }
1191 klass->SetDexCache(FindDexCache(dex_file));
1192 LoadClass(dex_file, dex_class_def, klass, class_loader);
1193 // Check for a pending exception during load
1194 Thread* self = Thread::Current();
1195 if (self->IsExceptionPending()) {
1196 return NULL;
1197 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001198 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001199 klass->SetClinitThreadId(self->GetTid());
1200 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001201 Class* existing = InsertClass(descriptor, klass.get(), false);
1202 if (existing != NULL) {
1203 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001204 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001205 klass.reset(existing);
1206 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001207 }
1208 // Finish loading (if necessary) by finding parents
1209 CHECK(!klass->IsLoaded());
1210 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1211 // Loading failed.
1212 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001213 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001214 lock.NotifyAll();
1215 return NULL;
1216 }
1217 CHECK(klass->IsLoaded());
1218 // Link the class (if necessary)
1219 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001220 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001221 // Linking failed.
1222 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001223 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001224 lock.NotifyAll();
1225 return NULL;
1226 }
1227 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001228
1229 /*
1230 * We send CLASS_PREPARE events to the debugger from here. The
1231 * definition of "preparation" is creating the static fields for a
1232 * class and initializing them to the standard default values, but not
1233 * executing any code (that comes later, during "initialization").
1234 *
1235 * We did the static preparation in LinkClass.
1236 *
1237 * The class has been prepared and resolved but possibly not yet verified
1238 * at this point.
1239 */
1240 Dbg::PostClassPrepare(klass.get());
1241
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001242 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001243}
1244
Brian Carlstrom4873d462011-08-21 15:23:39 -07001245// Precomputes size that will be needed for Class, matching LinkStaticFields
1246size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1247 const DexFile::ClassDef& dex_class_def) {
1248 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001249 size_t num_ref = 0;
1250 size_t num_32 = 0;
1251 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001252 if (class_data != NULL) {
1253 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1254 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001255 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001256 char c = descriptor[0];
1257 if (c == 'L' || c == '[') {
1258 num_ref++;
1259 } else if (c == 'J' || c == 'D') {
1260 num_64++;
1261 } else {
1262 num_32++;
1263 }
1264 }
1265 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001266 // start with generic class data
1267 size_t size = sizeof(Class);
1268 // follow with reference fields which must be contiguous at start
1269 size += (num_ref * sizeof(uint32_t));
1270 // if there are 64-bit fields to add, make sure they are aligned
1271 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1272 if (num_32 != 0) {
1273 // use an available 32-bit field for padding
1274 num_32--;
1275 }
1276 size += sizeof(uint32_t); // either way, we are adding a word
1277 DCHECK_EQ(size, RoundUp(size, 8));
1278 }
1279 // tack on any 64-bit fields now that alignment is assured
1280 size += (num_64 * sizeof(uint64_t));
1281 // tack on any remaining 32-bit fields
1282 size += (num_32 * sizeof(uint32_t));
1283 return size;
1284}
1285
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001286void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001287 // Every kind of method should at least get an invoke stub from the oat_method.
1288 // non-abstract methods also get their code pointers.
1289 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001290 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001291
1292 if (method->IsAbstract()) {
1293 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1294 return;
1295 }
1296 if (method->IsNative()) {
1297 // unregistering restores the dlsym lookup stub
1298 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001299 }
1300
1301 if (Runtime::Current()->IsMethodTracingActive()) {
1302#if defined(__arm__)
1303 Trace* tracer = Runtime::Current()->GetTracer();
1304 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1305 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1306#else
1307 UNIMPLEMENTED(WARNING);
1308#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001309 }
1310}
1311
Brian Carlstromf615a612011-07-23 12:50:34 -07001312void ClassLinker::LoadClass(const DexFile& dex_file,
1313 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001314 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001315 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001316 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001317 CHECK(klass->GetDexCache() != NULL);
1318 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001319 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001320 CHECK(descriptor != NULL);
1321
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001322 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001323 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001324 // Make sure that none of our runtime-only flags are set.
1325 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001326 klass->SetAccessFlags(access_flags);
1327 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001328 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001329 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001330
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001331 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001332
Ian Rogers0571d352011-11-03 19:51:38 -07001333 // Load fields fields.
1334 const byte* class_data = dex_file.GetClassData(dex_class_def);
1335 if (class_data == NULL) {
1336 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001337 }
Ian Rogers0571d352011-11-03 19:51:38 -07001338 ClassDataItemIterator it(dex_file, class_data);
1339 if (it.NumStaticFields() != 0) {
1340 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1341 }
1342 if (it.NumInstanceFields() != 0) {
1343 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1344 }
1345 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1346 SirtRef<Field> sfield(AllocField());
1347 klass->SetStaticField(i, sfield.get());
1348 LoadField(dex_file, it, klass, sfield);
1349 }
1350 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1351 SirtRef<Field> ifield(AllocField());
1352 klass->SetInstanceField(i, ifield.get());
1353 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001354 }
1355
Brian Carlstromaded5f72011-10-07 17:15:04 -07001356 UniquePtr<const OatFile::OatClass> oat_class;
1357 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001358 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001359 if (oat_file != NULL) {
1360 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1361 if (oat_dex_file != NULL) {
1362 uint32_t class_def_index;
1363 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1364 CHECK(found) << descriptor;
1365 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001366 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001367 }
1368 }
1369 }
Ian Rogers0571d352011-11-03 19:51:38 -07001370 // Load methods.
1371 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001372 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001373 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001374 }
Ian Rogers0571d352011-11-03 19:51:38 -07001375 if (it.NumVirtualMethods() != 0) {
1376 // TODO: append direct methods to class object
1377 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001378 }
Ian Rogers0571d352011-11-03 19:51:38 -07001379 size_t method_index = 0;
1380 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1381 SirtRef<Method> method(AllocMethod());
1382 klass->SetDirectMethod(i, method.get());
1383 LoadMethod(dex_file, it, klass, method);
1384 if (oat_class.get() != NULL) {
1385 LinkCode(method, oat_class.get(), method_index);
1386 }
1387 method_index++;
1388 }
1389 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1390 SirtRef<Method> method(AllocMethod());
1391 klass->SetVirtualMethod(i, method.get());
1392 LoadMethod(dex_file, it, klass, method);
1393 if (oat_class.get() != NULL) {
1394 LinkCode(method, oat_class.get(), method_index);
1395 }
1396 method_index++;
1397 }
1398 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001399}
1400
Ian Rogers0571d352011-11-03 19:51:38 -07001401void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1402 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001403 uint32_t field_idx = it.GetMemberIndex();
1404 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001405 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001406 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001407}
1408
Ian Rogers0571d352011-11-03 19:51:38 -07001409void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1410 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001411 uint32_t method_idx = it.GetMemberIndex();
1412 dst->SetDexMethodIndex(method_idx);
1413 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001414 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001415
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001416
1417 StringPiece method_name(dex_file.GetMethodName(method_id));
1418 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001419 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1420 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001421
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001422 if (method_name == "finalize") {
1423 // Create the prototype for a signature of "()V"
1424 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1425 if (void_string_id != NULL) {
1426 const DexFile::TypeId* void_type_id =
1427 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1428 if (void_type_id != NULL) {
1429 std::vector<uint16_t> no_args;
1430 const DexFile::ProtoId* finalizer_proto =
1431 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1432 if (finalizer_proto != NULL) {
1433 // We have the prototype in the dex file
1434 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1435 klass->SetFinalizable();
1436 } else {
1437 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1438 // The Enum class declares a "final" finalize() method to prevent subclasses from
1439 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1440 // subclasses, so we exclude it here.
1441 // We also want to avoid setting the flag on Object, where we know that finalize() is
1442 // empty.
1443 if (klass_descriptor != "Ljava/lang/Object;" &&
1444 klass_descriptor != "Ljava/lang/Enum;") {
1445 klass->SetFinalizable();
1446 }
1447 }
1448 }
1449 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001450 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001451 }
Ian Rogers0571d352011-11-03 19:51:38 -07001452 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001453 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001454
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001455 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1456 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1457 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1458 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1459 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1460 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001461}
1462
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001463void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001464 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1465 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001466}
1467
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001468void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1469 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001470 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001471 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001472}
1473
Brian Carlstromaded5f72011-10-07 17:15:04 -07001474bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001475 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001476 for (size_t i = 0; i != dex_files_.size(); ++i) {
1477 if (dex_files_[i] == &dex_file) {
1478 return true;
1479 }
1480 }
1481 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001482}
1483
Brian Carlstromaded5f72011-10-07 17:15:04 -07001484bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001485 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001486 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001487}
1488
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001489void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001490 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001491 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001492 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001493 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001494 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001495}
1496
Brian Carlstromaded5f72011-10-07 17:15:04 -07001497void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001498 {
1499 MutexLock mu(dex_lock_);
1500 if (IsDexFileRegisteredLocked(dex_file)) {
1501 return;
1502 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001503 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001504 // Don't alloc while holding the lock, since allocation may need to
1505 // suspend all threads and another thread may need the dex_lock_ to
1506 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001507 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001508 {
1509 MutexLock mu(dex_lock_);
1510 if (IsDexFileRegisteredLocked(dex_file)) {
1511 return;
1512 }
1513 RegisterDexFileLocked(dex_file, dex_cache);
1514 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001515}
1516
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001517void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001518 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001519 RegisterDexFileLocked(dex_file, dex_cache);
1520}
1521
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001522const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001523 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001524 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001525 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1526 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001527 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001528 }
1529 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001530 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001531 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001532}
1533
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001534DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001535 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001536 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001537 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001538 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001539 }
1540 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001541 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001542 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001543}
1544
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001545Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1546 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001547 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001548 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001549 CHECK(primitive_class != NULL);
1550 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001551 primitive_class->SetPrimitiveType(type);
1552 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001553 Class* existing = InsertClass(descriptor, primitive_class, false);
1554 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001555 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001556}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001557
Brian Carlstrombe977852011-07-19 14:54:54 -07001558// Create an array class (i.e. the class object for the array, not the
1559// array itself). "descriptor" looks like "[C" or "[[[[B" or
1560// "[Ljava/lang/String;".
1561//
1562// If "descriptor" refers to an array of primitives, look up the
1563// primitive type's internally-generated class object.
1564//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001565// "class_loader" is the class loader of the class that's referring to
1566// us. It's used to ensure that we're looking for the element type in
1567// the right context. It does NOT become the class loader for the
1568// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001569//
1570// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001571Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001572 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001573
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001574 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001575 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001576 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001577 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001578 return NULL;
1579 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001580
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001581 // See if the component type is already loaded. Array classes are
1582 // always associated with the class loader of their underlying
1583 // element type -- an array of Strings goes with the loader for
1584 // java/lang/String -- so we need to look for it there. (The
1585 // caller should have checked for the existence of the class
1586 // before calling here, but they did so with *their* class loader,
1587 // not the component type's loader.)
1588 //
1589 // If we find it, the caller adds "loader" to the class' initiating
1590 // loader list, which should prevent us from going through this again.
1591 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001592 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001593 // are the same, because our caller (FindClass) just did the
1594 // lookup. (Even if we get this wrong we still have correct behavior,
1595 // because we effectively do this lookup again when we add the new
1596 // class to the hash table --- necessary because of possible races with
1597 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001598 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001599 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001600 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001601 return new_class;
1602 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001603 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001604
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001605 // Fill out the fields in the Class.
1606 //
1607 // It is possible to execute some methods against arrays, because
1608 // all arrays are subclasses of java_lang_Object_, so we need to set
1609 // up a vtable. We can just point at the one in java_lang_Object_.
1610 //
1611 // Array classes are simple enough that we don't need to do a full
1612 // link step.
1613
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001614 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001615 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001616 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001617 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001618 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001619 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001620 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001621 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001622 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001623 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001624 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001625 }
1626 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001627 if (new_class.get() == NULL) {
1628 new_class.reset(AllocClass(sizeof(Class)));
1629 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001630 return NULL;
1631 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001632 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001633 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001634 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001635 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001636 new_class->SetSuperClass(java_lang_Object);
1637 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001638 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001639 new_class->SetClassLoader(component_type->GetClassLoader());
1640 new_class->SetStatus(Class::kStatusInitialized);
1641 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001642 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001643
1644
1645 // All arrays have java/lang/Cloneable and java/io/Serializable as
1646 // interfaces. We need to set that up here, so that stuff like
1647 // "instanceof" works right.
1648 //
1649 // Note: The GC could run during the call to FindSystemClass,
1650 // so we need to make sure the class object is GC-valid while we're in
1651 // there. Do this by clearing the interface list so the GC will just
1652 // think that the entries are null.
1653
1654
1655 // Use the single, global copies of "interfaces" and "iftable"
1656 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001657 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001658 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001659
1660 // Inherit access flags from the component type. Arrays can't be
1661 // used as a superclass or interface, so we want to add "final"
1662 // and remove "interface".
1663 //
1664 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001665 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001666 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001667 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1668 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001669
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001670 Class* existing = InsertClass(descriptor, new_class.get(), false);
1671 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001672 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001673 }
1674 // Another thread must have loaded the class after we
1675 // started but before we finished. Abandon what we've
1676 // done.
1677 //
1678 // (Yes, this happens.)
1679
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001680 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001681}
1682
1683Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001684 switch (Primitive::GetType(type)) {
1685 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001686 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001687 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001688 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001689 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001690 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001691 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001692 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001693 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001694 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001695 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001696 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001697 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001698 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001699 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001700 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001701 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001702 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001703 case Primitive::kPrimNot:
1704 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001705 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001706 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001707 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001708 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001709}
1710
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001711Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001712 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001713 DexCache* dex_cache = klass->GetDexCache();
1714 std::string source;
1715 if (dex_cache != NULL) {
1716 source += " from ";
1717 source += dex_cache->GetLocation()->ToModifiedUtf8();
1718 }
1719 LOG(INFO) << "Loaded class " << descriptor << source;
1720 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001721 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001722 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001723 Table& classes = image_class ? image_classes_ : classes_;
1724 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1725#ifndef NDEBUG
1726 // Check we don't have the class in the other table in error
1727 Table& other_classes = image_class ? classes_ : image_classes_;
1728 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1729#endif
1730 if (existing != NULL) {
1731 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001732 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001733 classes.insert(std::make_pair(hash, klass));
1734 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001735}
1736
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001737bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1738 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001739 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001740 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001741 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001742 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001743 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001744 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001745 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001746 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001747 classes_.erase(it);
1748 return true;
1749 }
1750 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001751 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001752 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001753 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001754 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001755 image_classes_.erase(it);
1756 return true;
1757 }
1758 }
1759 return false;
1760}
1761
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001762Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1763 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001764 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001765 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001766 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1767 if (klass != NULL) {
1768 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001769 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001770 return LookupClass(descriptor, class_loader, hash, image_classes_);
1771}
1772
1773Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1774 size_t hash, const Table& classes) {
1775 ClassHelper kh(NULL, this);
1776 typedef Table::const_iterator It; // TODO: C++0x auto
1777 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001778 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001779 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001780 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001781#ifndef NDEBUG
1782 for (++it; it != end && it->first == hash; ++it) {
1783 kh.ChangeClass(it->second);
1784 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader))
1785 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
1786 << PrettyClass(it->second) << " " << it->second << " " << it->second->GetClassLoader();
1787 }
1788#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001789 return klass;
1790 }
1791 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001792 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001793}
1794
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001795void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001796 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001797 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001798 MutexLock mu(classes_lock_);
1799 typedef Table::const_iterator It; // TODO: C++0x auto
1800 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001801 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001802 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001803 Class* klass = it->second;
1804 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001805 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001806 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001807 }
1808 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001809 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001810 Class* klass = it->second;
1811 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001812 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001813 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001814 }
1815 }
1816}
1817
Ian Rogersc20a83e2012-01-18 18:15:32 -08001818#ifndef NDEBUG
1819static void CheckMethodsHaveGcMaps(Class* klass) {
1820 if (!Runtime::Current()->IsStarted()) {
1821 return;
1822 }
1823 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1824 Method* method = klass->GetDirectMethod(i);
1825 if (!method->IsNative() && !method->IsAbstract()) {
1826 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1827 }
1828 }
1829 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1830 Method* method = klass->GetVirtualMethod(i);
1831 if (!method->IsNative() && !method->IsAbstract()) {
1832 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1833 }
1834 }
1835}
1836#else
1837static void CheckMethodsHaveGcMaps(Class* klass) {
1838}
1839#endif
1840
jeffhao98eacac2011-09-14 16:11:53 -07001841void ClassLinker::VerifyClass(Class* klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001842 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001843 if (klass->IsVerified()) {
1844 return;
1845 }
1846
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001847 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001848 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001849
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001850 // Try to use verification information from oat file, otherwise do runtime verification
1851 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
1852 if (VerifyClassUsingOatFile(dex_file, klass) || verifier::DexVerifier::VerifyClass(klass)) {
1853 // Make sure all classes referenced by catch blocks are resolved
1854 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001855 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001856 // Sanity check that a verified class has GC maps on all methods
1857 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001858 } else {
1859 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001860 Thread* self = Thread::Current();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001861 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001862 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001863 PrettyDescriptor(klass).c_str());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001864 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001865 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001866 }
jeffhao98eacac2011-09-14 16:11:53 -07001867}
1868
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001869bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1870 if (!Runtime::Current()->IsStarted()) {
1871 return false;
1872 }
1873 if (ClassLoader::UseCompileTimeClassPath()) {
1874 return false;
1875 }
1876 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
1877 if (oat_file == NULL) {
1878 return false;
1879 }
1880 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1881 CHECK(oat_dex_file != NULL) << PrettyClass(klass);
1882 const char* descriptor = ClassHelper(klass).GetDescriptor();
1883 uint32_t class_def_index;
1884 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1885 CHECK(found) << descriptor;
1886 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
1887 CHECK(oat_class.get() != NULL) << descriptor;
1888 Class::Status status = oat_class->GetStatus();
1889 if (status == Class::kStatusError) {
1890 ThrowEarlierClassFailure(klass);
1891 klass->SetVerifyErrorClass(Thread::Current()->GetException()->GetClass());
1892 klass->SetStatus(Class::kStatusError);
1893 return true;
1894 }
1895 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1896 return true;
1897 }
1898 if (status == Class::kStatusNotReady) {
1899 return false;
1900 }
1901 LOG(FATAL) << "Unexpected class status: " << status;
1902 return false;
1903}
1904
1905void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
1906 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1907 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
1908 }
1909 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1910 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
1911 }
1912}
1913
1914void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
1915 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
1916 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
1917 if (code_item == NULL) {
1918 return; // native or abstract method
1919 }
1920 if (code_item->tries_size_ == 0) {
1921 return; // nothing to process
1922 }
1923 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
1924 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
1925 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1926 for (uint32_t idx = 0; idx < handlers_size; idx++) {
1927 CatchHandlerIterator iterator(handlers_ptr);
1928 for (; iterator.HasNext(); iterator.Next()) {
1929 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1930 // unresolved exception types will be ignored by exception delivery
1931 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
1932 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
1933 if (exception_type == NULL) {
1934 DCHECK(Thread::Current()->IsExceptionPending());
1935 Thread::Current()->ClearException();
1936 }
1937 }
1938 }
1939 handlers_ptr = iterator.EndDataPointer();
1940 }
1941}
1942
Ian Rogersc2b44472011-12-14 21:17:17 -08001943static void CheckProxyConstructor(Method* constructor);
1944static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1945
Jesse Wilson95caa792011-10-12 18:14:17 -04001946Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001947 ClassLoader* loader, ObjectArray<Method>* methods,
1948 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001949 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001950 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001951 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001952 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001953 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001954 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001955 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001956 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001957 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001958 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001959
1960 klass->SetStatus(Class::kStatusIdx);
1961
1962 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1963
1964 // Create static field that holds throws, instance fields are inherited
1965 klass->SetSFields(AllocObjectArray<Field>(1));
1966 SirtRef<Field> sfield(AllocField());
1967 klass->SetStaticField(0, sfield.get());
1968 sfield->SetDexFieldIndex(-1);
1969 sfield->SetDeclaringClass(klass.get());
1970 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001971
Ian Rogers466bb252011-10-14 03:29:56 -07001972 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001973 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001974 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001975
Ian Rogers466bb252011-10-14 03:29:56 -07001976 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001977 size_t num_virtual_methods = methods->GetLength();
1978 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1979 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001980 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001981 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001982 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001983
1984 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1985 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1986 DCHECK(!Thread::Current()->IsExceptionPending());
1987
1988 // Link the fields and virtual methods, creating vtable and iftables
1989 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001990 DCHECK(Thread::Current()->IsExceptionPending());
1991 return NULL;
1992 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001993 sfield->SetObject(NULL, throws); // initialize throws field
1994 klass->SetStatus(Class::kStatusInitialized);
1995
1996 // sanity checks
1997#ifndef NDEBUG
1998 bool debug = true;
1999#else
2000 bool debug = false;
2001#endif
2002 if (debug) {
2003 CHECK(klass->GetIFields() == NULL);
2004 CheckProxyConstructor(klass->GetDirectMethod(0));
2005 for (size_t i = 0; i < num_virtual_methods; ++i) {
2006 SirtRef<Method> prototype(methods->Get(i));
2007 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2008 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002009 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002010 throws_field_name += name->ToModifiedUtf8();
2011 throws_field_name += ".throws";
2012 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2013
2014 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2015 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2016 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002017 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002018}
2019
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002020std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2021 DCHECK(proxy_class->IsProxyClass());
2022 String* name = proxy_class->GetName();
2023 DCHECK(name != NULL);
2024 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2025}
2026
2027
2028Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002029 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002030 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002031 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002032 Method* proxy_constructor = proxy_direct_methods->Get(2);
2033 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2034 // code_ too)
2035 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2036 // Make this constructor public and fix the class to be our Proxy version
2037 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002038 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002039 return constructor;
2040}
2041
2042static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002043 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002044 MethodHelper mh(constructor);
2045 CHECK_STREQ(mh.GetName(), "<init>");
Elliott Hughesba8eee12012-01-24 20:25:24 -08002046 CHECK_EQ(mh.GetSignature(), std::string("(Ljava/lang/reflect/InvocationHandler;)V"));
Ian Rogers466bb252011-10-14 03:29:56 -07002047 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002048}
2049
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002050Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2051 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2052 // prototype method
2053 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2054 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002055 // as necessary
2056 Method* method = down_cast<Method*>(prototype->Clone());
2057
2058 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2059 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002060 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002061 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002062
Ian Rogers466bb252011-10-14 03:29:56 -07002063 // At runtime the method looks like a reference and argument saving method, clone the code
2064 // related parameters from this method.
2065 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2066 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2067 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2068 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2069 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002070 return method;
2071}
Jesse Wilson95caa792011-10-12 18:14:17 -04002072
Ian Rogersc2b44472011-12-14 21:17:17 -08002073static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002074 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002075 CHECK(!prototype->IsFinal());
2076 CHECK(method->IsFinal());
2077 CHECK(!method->IsAbstract());
2078 MethodHelper mh(method);
2079 const char* method_name = mh.GetName();
2080 const char* method_shorty = mh.GetShorty();
2081 Class* method_return = mh.GetReturnType();
2082
2083 mh.ChangeMethod(prototype.get());
2084
2085 CHECK_STREQ(mh.GetName(), method_name);
2086 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002087
2088 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002089 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002090}
2091
Brian Carlstrom25c33252011-09-18 15:58:35 -07002092bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002093 CHECK(klass->IsResolved() || klass->IsErroneous())
2094 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002095
Carl Shapirob5573532011-07-12 18:22:59 -07002096 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002097
Brian Carlstrom25c33252011-09-18 15:58:35 -07002098 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002099 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002100 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002101 ObjectLock lock(klass);
2102
Brian Carlstromd1422f82011-09-28 11:37:09 -07002103 if (klass->GetStatus() == Class::kStatusInitialized) {
2104 return true;
2105 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002106
Brian Carlstromd1422f82011-09-28 11:37:09 -07002107 if (klass->IsErroneous()) {
2108 ThrowEarlierClassFailure(klass);
2109 return false;
2110 }
2111
2112 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002113 VerifyClass(klass);
2114 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002115 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002116 return false;
2117 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118 }
2119
Brian Carlstrom25c33252011-09-18 15:58:35 -07002120 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2121 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002122 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002123 // don't bother going to kStatusInitializing. We return true to maintain
2124 // the invariant that a false result implies there is a pending exception.
2125 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002126 }
2127
Brian Carlstromd1422f82011-09-28 11:37:09 -07002128 // If the class is kStatusInitializing, either this thread is
2129 // initializing higher up the stack or another thread has beat us
2130 // to initializing and we need to wait. Either way, this
2131 // invocation of InitializeClass will not be responsible for
2132 // running <clinit> and will return.
2133 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002134 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002135 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002136 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002137 return true;
2138 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002139 // No. That's fine. Wait for another thread to finish initializing.
2140 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002141 }
2142
2143 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002144 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002145 klass->SetStatus(Class::kStatusError);
2146 return false;
2147 }
2148
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002149 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002150
Elliott Hughesdcc24742011-09-07 14:02:44 -07002151 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002152 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002153 }
2154
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002155 uint64_t t0 = NanoTime();
2156
Brian Carlstrom25c33252011-09-18 15:58:35 -07002157 if (!InitializeSuperClass(klass, can_run_clinit)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002158 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002159 return false;
2160 }
2161
2162 InitializeStaticFields(klass);
2163
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002164 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002165 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002166 }
2167
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002168 uint64_t t1 = NanoTime();
2169
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002170 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002171 {
2172 ObjectLock lock(klass);
2173
2174 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002175 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002176 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002177 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002178 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002179 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2180 RuntimeStats* thread_stats = self->GetStats();
2181 ++global_stats->class_init_count;
2182 ++thread_stats->class_init_count;
2183 global_stats->class_init_time_ns += (t1 - t0);
2184 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002185 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002186 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002187 ClassHelper kh(klass);
2188 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002189 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002190 }
2191 lock.NotifyAll();
2192 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002193 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002194}
2195
Brian Carlstromd1422f82011-09-28 11:37:09 -07002196bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2197 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002198 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002199 lock.Wait();
2200
2201 // When we wake up, repeat the test for init-in-progress. If
2202 // there's an exception pending (only possible if
2203 // "interruptShouldThrow" was set), bail out.
2204 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002205 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002206 klass->SetStatus(Class::kStatusError);
2207 return false;
2208 }
2209 // Spurious wakeup? Go back to waiting.
2210 if (klass->GetStatus() == Class::kStatusInitializing) {
2211 continue;
2212 }
2213 if (klass->IsErroneous()) {
2214 // The caller wants an exception, but it was thrown in a
2215 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002216 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002217 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002218 return false;
2219 }
2220 if (klass->IsInitialized()) {
2221 return true;
2222 }
2223 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2224 }
2225 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2226}
2227
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002228bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2229 if (klass->IsInterface()) {
2230 return true;
2231 }
2232 // begin with the methods local to the superclass
2233 if (klass->HasSuperClass() &&
2234 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2235 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002236 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2237 const Method* method = klass->GetVTable()->Get(i);
2238 if (method != super->GetVTable()->Get(i) &&
2239 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002240 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2241 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2242 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002243 return false;
2244 }
2245 }
2246 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002247 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2248 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2249 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002250 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2251 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002252 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002253 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2254 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002255 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2256 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2257 PrettyMethod(method).c_str(),
2258 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002259 return false;
2260 }
2261 }
2262 }
2263 }
2264 return true;
2265}
2266
Ian Rogers595799e2012-01-11 17:32:51 -08002267// Returns true if classes referenced by the signature of the method are the
2268// same classes in klass1 as they are in klass2.
2269bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2270 const Class* klass1,
2271 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002272 if (klass1 == klass2) {
2273 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002274 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002275 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002276 const DexFile::ProtoId& proto_id =
2277 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002278 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2279 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002280 if (descriptor == NULL) {
2281 break;
2282 }
2283 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2284 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002285 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002286 return false;
2287 }
2288 }
2289 }
2290 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002291 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002292 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002293 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 return false;
2295 }
2296 }
2297 return true;
2298}
2299
Ian Rogers595799e2012-01-11 17:32:51 -08002300// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2301bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2302 const Class* klass1,
2303 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002304 CHECK(descriptor != NULL);
2305 CHECK(klass1 != NULL);
2306 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002307 if (klass1 == klass2) {
2308 return true;
2309 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002310 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002311 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002312 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002313 }
Ian Rogers595799e2012-01-11 17:32:51 -08002314 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2315 if (found2 == NULL) {
2316 Thread::Current()->ClearException();
2317 }
2318 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002319}
2320
Brian Carlstrom25c33252011-09-18 15:58:35 -07002321bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002322 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002323 if (!klass->IsInterface() && klass->HasSuperClass()) {
2324 Class* super_class = klass->GetSuperClass();
2325 if (super_class->GetStatus() != Class::kStatusInitialized) {
2326 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002327 Thread* self = Thread::Current();
2328 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002329 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002330 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002331 // TODO: check for a pending exception
2332 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002333 if (!can_run_clinit) {
2334 // Don't set status to error when we can't run <clinit>.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002335 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002336 klass->SetStatus(Class::kStatusVerified);
2337 return false;
2338 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002339 klass->SetStatus(Class::kStatusError);
2340 klass->NotifyAll();
2341 return false;
2342 }
2343 }
2344 }
2345 return true;
2346}
2347
Brian Carlstrom25c33252011-09-18 15:58:35 -07002348bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002349 CHECK(c != NULL);
2350 if (c->IsInitialized()) {
2351 return true;
2352 }
2353
Elliott Hughes5f791332011-09-15 17:45:30 -07002354 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002355 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002356 bool success = InitializeClass(c, can_run_clinit);
2357 if (!success) {
2358 CHECK(self->IsExceptionPending());
2359 }
2360 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002361}
2362
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002363void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002364 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002365 const ClassLoader* cl = c->GetClassLoader();
2366 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002367 ClassDataItemIterator it(dex_file, class_data);
2368 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2369 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002370 }
2371}
2372
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002373void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002374 size_t num_static_fields = klass->NumStaticFields();
2375 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002376 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002377 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002378 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002379 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002380 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002381 return;
2382 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002383 ClassHelper kh(klass);
2384 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002385 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002386 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002387 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002388
Ian Rogers0571d352011-11-03 19:51:38 -07002389 if (it.HasNext()) {
2390 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2391 std::map<uint32_t, Field*> field_map;
2392 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2393 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2394 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002395 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002396 }
2397}
2398
Ian Rogersc2b44472011-12-14 21:17:17 -08002399bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002400 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002401 if (!LinkSuperClass(klass)) {
2402 return false;
2403 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002404 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002405 return false;
2406 }
2407 if (!LinkInstanceFields(klass)) {
2408 return false;
2409 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002410 if (!LinkStaticFields(klass)) {
2411 return false;
2412 }
2413 CreateReferenceInstanceOffsets(klass);
2414 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002415 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2416 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002417 return true;
2418}
2419
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002420bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002421 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002422 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2423 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002424 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002425 uint16_t super_class_idx = class_def->superclass_idx_;
2426 if (super_class_idx != DexFile::kDexNoIndex16) {
2427 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002428 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002429 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 return false;
2431 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002432 // Verify
2433 if (!klass->CanAccess(super_class)) {
2434 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2435 "Class %s extended by class %s is inaccessible",
2436 PrettyDescriptor(super_class).c_str(),
2437 PrettyDescriptor(klass.get()).c_str());
2438 return false;
2439 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002440 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002441 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002442 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2443 if (interfaces != NULL) {
2444 for (size_t i = 0; i < interfaces->Size(); i++) {
2445 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2446 Class* interface = ResolveType(dex_file, idx, klass.get());
2447 if (interface == NULL) {
2448 DCHECK(Thread::Current()->IsExceptionPending());
2449 return false;
2450 }
2451 // Verify
2452 if (!klass->CanAccess(interface)) {
2453 // TODO: the RI seemed to ignore this in my testing.
2454 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2455 "Interface %s implemented by class %s is inaccessible",
2456 PrettyDescriptor(interface).c_str(),
2457 PrettyDescriptor(klass.get()).c_str());
2458 return false;
2459 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002460 }
2461 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002462 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002463 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002464 return true;
2465}
2466
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002467bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002468 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002469 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002470 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002471 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002472 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002473 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002474 return false;
2475 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002476 return true;
2477 }
2478 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002479 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002480 return false;
2481 }
2482 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002483 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002484 Thread* thread = Thread::Current();
2485 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002486 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002487 PrettyDescriptor(super).c_str(),
2488 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002489 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002490 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002491 return false;
2492 }
2493 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002494 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002495 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002496 PrettyDescriptor(super).c_str(),
2497 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002498 return false;
2499 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002500
2501 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2502 if (super->IsFinalizable()) {
2503 klass->SetFinalizable();
2504 }
2505
Elliott Hughes2da50362011-10-10 16:57:08 -07002506 // Inherit reference flags (if any) from the superclass.
2507 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2508 if (reference_flags != 0) {
2509 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2510 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002511 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002512 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002513 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002514 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002515 return false;
2516 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002517
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002518#ifndef NDEBUG
2519 // Ensure super classes are fully resolved prior to resolving fields..
2520 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002521 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002522 super = super->GetSuperClass();
2523 }
2524#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002525 return true;
2526}
2527
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002528// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002529bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002530 if (klass->IsInterface()) {
2531 // No vtable.
2532 size_t count = klass->NumVirtualMethods();
2533 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002534 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002535 return false;
2536 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002537 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002538 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002539 }
jeffhaobdb76512011-09-07 11:43:16 -07002540 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002541 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002542 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002543 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002544 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002545 }
2546 return true;
2547}
2548
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002549bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002550 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002551 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2552 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002553 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002554 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002555 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002556 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002557 MethodHelper local_mh(NULL, this);
2558 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002559 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002560 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002561 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002562 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002563 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002564 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002565 super_mh.ChangeMethod(super_method);
2566 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002567 // Verify
2568 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002569 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002570 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002571 PrettyDescriptor(klass.get()).c_str(),
2572 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002573 return false;
2574 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002575 vtable->Set(j, local_method);
2576 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002577 break;
2578 }
2579 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002580 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002581 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002582 vtable->Set(actual_count, local_method);
2583 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002584 actual_count += 1;
2585 }
2586 }
2587 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002588 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002589 return false;
2590 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002591 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002592 CHECK_LE(actual_count, max_count);
2593 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002594 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002595 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002596 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002598 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002599 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002600 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002601 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002602 return false;
2603 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002604 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002605 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002606 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2607 vtable->Set(i, virtual_method);
2608 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002609 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002610 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002611 }
2612 return true;
2613}
2614
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002615bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002616 size_t super_ifcount;
2617 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002618 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002619 } else {
2620 super_ifcount = 0;
2621 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002622 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002623 ClassHelper kh(klass.get(), this);
2624 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2625 ifcount += num_interfaces;
2626 for (size_t i = 0; i < num_interfaces; i++) {
2627 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2628 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002629 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002630 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002631 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002632 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002633 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002634 return true;
2635 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002636 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002637 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002638 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2639 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002640 Class* super_interface = super_iftable->Get(i)->GetInterface();
2641 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002642 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002643 }
2644 // Flatten the interface inheritance hierarchy.
2645 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002646 for (size_t i = 0; i < num_interfaces; i++) {
2647 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002648 DCHECK(interface != NULL);
2649 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002650 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002651 Thread* thread = Thread::Current();
2652 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002653 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002654 PrettyDescriptor(klass.get()).c_str(),
2655 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002656 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002657 return false;
2658 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002659 // Check if interface is already in iftable
2660 bool duplicate = false;
2661 for (size_t j = 0; j < idx; j++) {
2662 Class* existing_interface = iftable->Get(j)->GetInterface();
2663 if (existing_interface == interface) {
2664 duplicate = true;
2665 break;
2666 }
2667 }
2668 if (!duplicate) {
2669 // Add this non-duplicate interface.
2670 iftable->Set(idx++, AllocInterfaceEntry(interface));
2671 // Add this interface's non-duplicate super-interfaces.
2672 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2673 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2674 bool super_duplicate = false;
2675 for (size_t k = 0; k < idx; k++) {
2676 Class* existing_interface = iftable->Get(k)->GetInterface();
2677 if (existing_interface == super_interface) {
2678 super_duplicate = true;
2679 break;
2680 }
2681 }
2682 if (!super_duplicate) {
2683 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2684 }
2685 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002686 }
2687 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002688 // Shrink iftable in case duplicates were found
2689 if (idx < ifcount) {
2690 iftable.reset(iftable->CopyOf(idx));
2691 ifcount = idx;
2692 } else {
2693 CHECK_EQ(idx, ifcount);
2694 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002695 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002696
2697 // If we're an interface, we don't need the vtable pointers, so we're done.
2698 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002699 return true;
2700 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002701 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002702 MethodHelper vtable_mh(NULL, this);
2703 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002704 for (size_t i = 0; i < ifcount; ++i) {
2705 InterfaceEntry* interface_entry = iftable->Get(i);
2706 Class* interface = interface_entry->GetInterface();
2707 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2708 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002709 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002710 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2711 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002712 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002713 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002714 // For each method listed in the interface's method list, find the
2715 // matching method in our class's method list. We want to favor the
2716 // subclass over the superclass, which just requires walking
2717 // back from the end of the vtable. (This only matters if the
2718 // superclass defines a private method and this class redefines
2719 // it -- otherwise it would use the same vtable slot. In .dex files
2720 // those don't end up in the virtual method table, so it shouldn't
2721 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002722 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2723 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002724 vtable_mh.ChangeMethod(vtable_method);
2725 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002726 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002727 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002728 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002729 return false;
2730 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002731 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002732 break;
2733 }
2734 }
2735 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002736 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002737 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002738 Method* mir_method = miranda_list[mir];
2739 vtable_mh.ChangeMethod(mir_method);
2740 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002741 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002742 break;
2743 }
2744 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002745 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002746 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002747 miranda_method.reset(AllocMethod());
2748 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2749 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002750 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002751 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002752 }
2753 }
2754 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002755 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002756 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002757 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002758 klass->SetVirtualMethods((old_method_count == 0)
2759 ? AllocObjectArray<Method>(new_method_count)
2760 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002761
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002762 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2763 CHECK(vtable != NULL);
2764 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002765 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002766 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002767 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002768 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002769 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002770 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2771 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2772 klass->SetVirtualMethod(old_method_count + i, method);
2773 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002774 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002775 // TODO: do not assign to the vtable field until it is fully constructed.
2776 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002777 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002778
2779 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2780 for (int i = 0; i < vtable->GetLength(); ++i) {
2781 CHECK(vtable->Get(i) != NULL);
2782 }
2783
2784// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2785
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002786 return true;
2787}
2788
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002789bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2790 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002791 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002792}
2793
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002794bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2795 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002796 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002797 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002798 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002799 return success;
2800}
2801
Brian Carlstromdbc05252011-09-09 01:59:59 -07002802struct LinkFieldsComparator {
Elliott Hughesba8eee12012-01-24 20:25:24 -08002803 explicit LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002804 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002805 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002806 fh_->ChangeField(field1);
2807 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2808 fh_->ChangeField(field2);
2809 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002810 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2811 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2812 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2813 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002814 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2815 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2816 if (order1 != order2) {
2817 return order1 < order2;
2818 }
2819
2820 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002821 fh_->ChangeField(field1);
2822 StringPiece name1(fh_->GetName());
2823 fh_->ChangeField(field2);
2824 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002825 return name1 < name2;
2826 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002827
2828 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002829};
2830
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002831bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002832 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002833 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002834
2835 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002836 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002837
2838 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002839 size_t size;
2840 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002841 if (is_static) {
2842 size = klass->GetClassSize();
2843 field_offset = Class::FieldsOffset();
2844 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002845 Class* super_class = klass->GetSuperClass();
2846 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002847 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002848 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002849 }
2850 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002851 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002852
Brian Carlstromdbc05252011-09-09 01:59:59 -07002853 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002854
Brian Carlstromdbc05252011-09-09 01:59:59 -07002855 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002856 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002857 std::deque<Field*> grouped_and_sorted_fields;
2858 for (size_t i = 0; i < num_fields; i++) {
2859 grouped_and_sorted_fields.push_back(fields->Get(i));
2860 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002861 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002862 std::sort(grouped_and_sorted_fields.begin(),
2863 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002864 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002865
2866 // References should be at the front.
2867 size_t current_field = 0;
2868 size_t num_reference_fields = 0;
2869 for (; current_field < num_fields; current_field++) {
2870 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002871 fh.ChangeField(field);
2872 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002873 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002874 if (isPrimitive) {
2875 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002876 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002877 grouped_and_sorted_fields.pop_front();
2878 num_reference_fields++;
2879 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002880 field->SetOffset(field_offset);
2881 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002882 }
2883
2884 // Now we want to pack all of the double-wide fields together. If
2885 // we're not aligned, though, we want to shuffle one 32-bit field
2886 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002887 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002888 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2889 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002890 fh.ChangeField(field);
2891 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002892 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2893 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002894 continue;
2895 }
2896 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002897 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002898 // drop the consumed field
2899 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2900 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002901 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002902 // whether we found a 32-bit field for padding or not, we advance
2903 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002904 }
2905
2906 // Alignment is good, shuffle any double-wide fields forward, and
2907 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002908 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002909 while (!grouped_and_sorted_fields.empty()) {
2910 Field* field = grouped_and_sorted_fields.front();
2911 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002912 fh.ChangeField(field);
2913 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002914 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002915 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002916 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002917 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002918 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002919 ? sizeof(uint64_t)
2920 : sizeof(uint32_t)));
2921 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002922 }
2923
Elliott Hughesadb460d2011-10-05 17:02:34 -07002924 // 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 -08002925 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2926 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002927 // We know there are no non-reference fields in the Reference classes, and we know
2928 // that 'referent' is alphabetically last, so this is easy...
2929 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002930 fh.ChangeField(fields->Get(num_fields - 1));
Elliott Hughesba8eee12012-01-24 20:25:24 -08002931 CHECK_STREQ(fh.GetName(), "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002932 --num_reference_fields;
2933 }
2934
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002935#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002936 // Make sure that all reference fields appear before
2937 // non-reference fields, and all double-wide fields are aligned.
2938 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002939 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002940 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002941 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002942 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002943 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002944 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002945 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2946 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002947 fh.ChangeField(field);
2948 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002949 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002950 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002951 is_primitive = true; // We lied above, so we have to expect a lie here.
2952 }
2953 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002954 if (!seen_non_ref) {
2955 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002956 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002957 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002958 } else {
2959 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002960 }
2961 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002962 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002963 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002964 }
2965#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002966 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002967 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002968 if (is_static) {
2969 klass->SetNumReferenceStaticFields(num_reference_fields);
2970 klass->SetClassSize(size);
2971 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002972 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002973 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002974 klass->SetObjectSize(size);
2975 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002976 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002977 return true;
2978}
2979
2980// Set the bitmap of reference offsets, refOffsets, from the ifields
2981// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002982void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002983 uint32_t reference_offsets = 0;
2984 Class* super_class = klass->GetSuperClass();
2985 if (super_class != NULL) {
2986 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002987 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002988 if (reference_offsets == CLASS_WALK_SUPER) {
2989 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002990 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002991 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002992 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002993 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002994}
2995
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002996void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002997 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002998}
2999
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003000void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003001 uint32_t reference_offsets) {
3002 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003003 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3004 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003005 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003006 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003007 // All of the fields that contain object references are guaranteed
3008 // to be at the beginning of the fields list.
3009 for (size_t i = 0; i < num_reference_fields; ++i) {
3010 // Note that byte_offset is the offset from the beginning of
3011 // object, not the offset into instance data
3012 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003013 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003014 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3015 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3016 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003017 CHECK_NE(new_bit, 0U);
3018 reference_offsets |= new_bit;
3019 } else {
3020 reference_offsets = CLASS_WALK_SUPER;
3021 break;
3022 }
3023 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003024 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003025 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003026 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003027 } else {
3028 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003029 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003030}
3031
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003032String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003033 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003034 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003035 if (resolved != NULL) {
3036 return resolved;
3037 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003038 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3039 int32_t utf16_length = dex_file.GetStringLength(string_id);
3040 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003041 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003042 dex_cache->SetResolvedString(string_idx, string);
3043 return string;
3044}
3045
3046Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003047 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003048 DexCache* dex_cache,
3049 const ClassLoader* class_loader) {
3050 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003051 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003052 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003053 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003054 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003055 // TODO: we used to throw here if resolved's class loader was not the
3056 // boot class loader. This was to permit different classes with the
3057 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003058 dex_cache->SetResolvedType(type_idx, resolved);
3059 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003060 CHECK(Thread::Current()->IsExceptionPending())
3061 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003062 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003063 }
3064 return resolved;
3065}
3066
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003067Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3068 uint32_t method_idx,
3069 DexCache* dex_cache,
3070 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003071 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003072 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3073 if (resolved != NULL) {
3074 return resolved;
3075 }
3076 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3077 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3078 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003079 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003080 return NULL;
3081 }
3082
Ian Rogers0571d352011-11-03 19:51:38 -07003083 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3084 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003085 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003086 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003087 } else if (klass->IsInterface()) {
3088 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003089 } else {
3090 resolved = klass->FindVirtualMethod(name, signature);
3091 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003092 if (resolved != NULL) {
3093 dex_cache->SetResolvedMethod(method_idx, resolved);
3094 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003095 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003096 }
3097 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003098}
3099
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003100Field* ClassLinker::ResolveField(const DexFile& dex_file,
3101 uint32_t field_idx,
3102 DexCache* dex_cache,
3103 const ClassLoader* class_loader,
3104 bool is_static) {
3105 Field* resolved = dex_cache->GetResolvedField(field_idx);
3106 if (resolved != NULL) {
3107 return resolved;
3108 }
3109 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3110 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3111 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003112 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003113 return NULL;
3114 }
3115
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003116 const char* name = dex_file.GetFieldName(field_id);
3117 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003118 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003119 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003120 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003121 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003122 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003123 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003124 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003125 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003126 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3127 }
3128 return resolved;
3129}
3130
3131Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3132 uint32_t field_idx,
3133 DexCache* dex_cache,
3134 const ClassLoader* class_loader) {
3135 Field* resolved = dex_cache->GetResolvedField(field_idx);
3136 if (resolved != NULL) {
3137 return resolved;
3138 }
3139 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3140 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3141 if (klass == NULL) {
3142 DCHECK(Thread::Current()->IsExceptionPending());
3143 return NULL;
3144 }
3145
3146 const char* name = dex_file.GetFieldName(field_id);
3147 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3148 resolved = klass->FindField(name, type);
3149 if (resolved != NULL) {
3150 dex_cache->SetResolvedField(field_idx, resolved);
3151 } else {
3152 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003153 }
3154 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003155}
3156
Ian Rogersad25ac52011-10-04 19:13:33 -07003157const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3158 Class* declaring_class = referrer->GetDeclaringClass();
3159 DexCache* dex_cache = declaring_class->GetDexCache();
3160 const DexFile& dex_file = FindDexFile(dex_cache);
3161 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3162 return dex_file.GetShorty(method_id.proto_idx_);
3163}
3164
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003165void ClassLinker::DumpAllClasses(int flags) const {
3166 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3167 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3168 std::vector<Class*> all_classes;
3169 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003170 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003171 typedef Table::const_iterator It; // TODO: C++0x auto
3172 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3173 all_classes.push_back(it->second);
3174 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003175 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3176 all_classes.push_back(it->second);
3177 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003178 }
3179
3180 for (size_t i = 0; i < all_classes.size(); ++i) {
3181 all_classes[i]->DumpClass(std::cerr, flags);
3182 }
3183}
3184
Elliott Hughescac6cc72011-11-03 20:31:21 -07003185void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3186 MutexLock mu(classes_lock_);
3187 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3188 << classes_.size() << " allocated classes\n";
3189}
3190
Elliott Hughese27955c2011-08-26 15:21:24 -07003191size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003192 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003193 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003194}
3195
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003196pid_t ClassLinker::GetClassesLockOwner() {
3197 return classes_lock_.GetOwner();
3198}
3199
3200pid_t ClassLinker::GetDexLockOwner() {
3201 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003202}
3203
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003204void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3205 DCHECK(!init_done_);
3206
3207 DCHECK(klass != NULL);
3208 DCHECK(klass->GetClassLoader() == NULL);
3209
3210 DCHECK(class_roots_ != NULL);
3211 DCHECK(class_roots_->Get(class_root) == NULL);
3212 class_roots_->Set(class_root, klass);
3213}
3214
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003215} // namespace art