blob: 3b5ac5d084c661be03ddc52f9cbb7629cec49e40 [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) {
jeffhao262bf462011-10-20 18:36:32 -0700552
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800553 std::string dex2oat_string("/system/bin/dex2oat");
554#ifndef NDEBUG
555 dex2oat_string += 'd';
556#endif
557 const char* dex2oat = dex2oat_string.c_str();
558
559 const char* class_path = Runtime::Current()->GetClassPath().c_str();
560
561 std::string boot_image_option_string("--boot-image=");
562 boot_image_option_string += Heap::GetSpaces()[0]->GetImageFilename();
563 const char* boot_image_option = boot_image_option_string.c_str();
564
565 std::string dex_file_option_string("--dex-file=");
Brian Carlstromd601af82012-01-06 10:15:19 -0800566 dex_file_option_string += dex_filename;
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800567 const char* dex_file_option = dex_file_option_string.c_str();
568
Brian Carlstromd601af82012-01-06 10:15:19 -0800569 std::string oat_fd_option_string("--oat-fd=");
Brian Carlstrom866c8622012-01-06 16:35:13 -0800570 StringAppendF(&oat_fd_option_string, "%d", oat_fd);
Brian Carlstromd601af82012-01-06 10:15:19 -0800571 const char* oat_fd_option = oat_fd_option_string.c_str();
572
573 std::string oat_name_option_string("--oat-name=");
574 oat_name_option_string += oat_cache_filename;
575 const char* oat_name_option = oat_name_option_string.c_str();
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800576
jeffhao262bf462011-10-20 18:36:32 -0700577 // fork and exec dex2oat
578 pid_t pid = fork();
579 if (pid == 0) {
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800580 // no allocation allowed between fork and exec
Ian Rogers725aee52012-01-11 11:56:56 -0800581
582 // change process groups, so we don't get reaped by ProcessManager
583 setpgid(0, 0);
584
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800585 execl(dex2oat, dex2oat,
jeffhao5d840402011-10-24 17:09:45 -0700586 "--runtime-arg", "-Xms64m",
587 "--runtime-arg", "-Xmx64m",
Jesse Wilson254db0f2011-11-16 16:44:11 -0500588 "--runtime-arg", "-classpath",
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800589 "--runtime-arg", class_path,
590 boot_image_option,
591 dex_file_option,
Brian Carlstromd601af82012-01-06 10:15:19 -0800592 oat_fd_option,
593 oat_name_option,
jeffhao262bf462011-10-20 18:36:32 -0700594 NULL);
595
Brian Carlstrom29e7ac72011-12-05 23:42:57 -0800596 PLOG(FATAL) << "execl(" << dex2oat << ") failed";
Brian Carlstromd601af82012-01-06 10:15:19 -0800597 return false;
jeffhao262bf462011-10-20 18:36:32 -0700598 } else {
599 // wait for dex2oat to finish
600 int status;
601 pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
602 if (got_pid != pid) {
603 PLOG(ERROR) << "waitpid failed: wanted " << pid << ", got " << got_pid;
Brian Carlstromd601af82012-01-06 10:15:19 -0800604 return false;
jeffhao262bf462011-10-20 18:36:32 -0700605 }
606 if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800607 LOG(ERROR) << dex2oat << " failed with dex-file=" << dex_filename;
608 return false;
jeffhao262bf462011-10-20 18:36:32 -0700609 }
610 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800611 return true;
jeffhao262bf462011-10-20 18:36:32 -0700612}
613
Brian Carlstrom866c8622012-01-06 16:35:13 -0800614void ClassLinker::RegisterOatFile(const OatFile& oat_file) {
615 MutexLock mu(dex_lock_);
616 RegisterOatFileLocked(oat_file);
617}
618
619void ClassLinker::RegisterOatFileLocked(const OatFile& oat_file) {
620 dex_lock_.AssertHeld();
621 oat_files_.push_back(&oat_file);
622}
623
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700624OatFile* ClassLinker::OpenOat(const Space* space) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700625 MutexLock mu(dex_lock_);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700626 const Runtime* runtime = Runtime::Current();
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800627 VLOG(startup) << "ClassLinker::OpenOat entering";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700628 const ImageHeader& image_header = space->GetImageHeader();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800629 // Grab location but don't use Object::AsString as we haven't yet initialized the roots to
630 // check the down cast
631 String* oat_location = down_cast<String*>(image_header.GetImageRoot(ImageHeader::kOatLocation));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700632 std::string oat_filename;
633 oat_filename += runtime->GetHostPrefix();
634 oat_filename += oat_location->ToModifiedUtf8();
Brian Carlstroma9f19782011-10-13 00:14:47 -0700635 OatFile* oat_file = OatFile::Open(oat_filename, "", image_header.GetOatBaseAddr());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700636 if (oat_file == NULL) {
Brian Carlstroma9f19782011-10-13 00:14:47 -0700637 LOG(ERROR) << "Failed to open oat file " << oat_filename << " referenced from image.";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700638 return NULL;
639 }
640 uint32_t oat_checksum = oat_file->GetOatHeader().GetChecksum();
641 uint32_t image_oat_checksum = image_header.GetOatChecksum();
642 if (oat_checksum != image_oat_checksum) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800643 LOG(ERROR) << "Failed to match oat file checksum " << std::hex << oat_checksum
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700644 << " to expected oat checksum " << std::hex << oat_checksum
645 << " in image";
646 return NULL;
647 }
Brian Carlstrom866c8622012-01-06 16:35:13 -0800648 RegisterOatFileLocked(*oat_file);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800649 VLOG(startup) << "ClassLinker::OpenOat exiting";
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700650 return oat_file;
651}
652
Brian Carlstromae826982011-11-09 01:33:42 -0800653const OatFile* ClassLinker::FindOpenedOatFileForDexFile(const DexFile& dex_file) {
654 for (size_t i = 0; i < oat_files_.size(); i++) {
655 const OatFile* oat_file = oat_files_[i];
656 DCHECK(oat_file != NULL);
Ian Rogers7fe2c692011-12-06 16:35:59 -0800657 if (oat_file->GetOatDexFile(dex_file.GetLocation(), false)) {
Brian Carlstromae826982011-11-09 01:33:42 -0800658 return oat_file;
659 }
660 }
661 return NULL;
662}
663
Brian Carlstromd601af82012-01-06 10:15:19 -0800664class LockedFd {
665 public:
666 static LockedFd* CreateAndLock(std::string& name, mode_t mode) {
667 int fd = open(name.c_str(), O_CREAT | O_RDWR, mode);
668 if (fd == -1) {
669 PLOG(ERROR) << "Failed to open file '" << name << "'";
670 return NULL;
671 }
672 fchmod(fd, mode);
673
674 LOG(INFO) << "locking file " << name << " (fd=" << fd << ")";
675 // try to lock non-blocking so we can log if we need may need to block
676 int result = flock(fd, LOCK_EX | LOCK_NB);
677 if (result == -1) {
678 LOG(WARNING) << "sleeping while locking file " << name;
679 // retry blocking
680 result = flock(fd, LOCK_EX);
681 }
682 if (result == -1) {
683 PLOG(ERROR) << "Failed to lock file '" << name << "'";
684 close(fd);
685 return NULL;
686 }
687 return new LockedFd(fd);
688 }
689
690 int GetFd() const {
691 return fd_;
692 }
693
694 ~LockedFd() {
695 if (fd_ != -1) {
696 int result = flock(fd_, LOCK_UN);
697 if (result == -1) {
698 PLOG(WARNING) << "flock(" << fd_ << ", LOCK_UN) failed";
699 }
700 close(fd_);
701 }
702 }
703
704 private:
705 explicit LockedFd(int fd) : fd_(fd) {}
706
707 int fd_;
708};
709
Brian Carlstromae826982011-11-09 01:33:42 -0800710const OatFile* ClassLinker::FindOatFileForDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700711 MutexLock mu(dex_lock_);
Brian Carlstrom866c8622012-01-06 16:35:13 -0800712 const OatFile* open_oat_file = FindOpenedOatFileForDexFile(dex_file);
713 if (open_oat_file != NULL) {
714 return open_oat_file;
Brian Carlstromae826982011-11-09 01:33:42 -0800715 }
716
Brian Carlstromd601af82012-01-06 10:15:19 -0800717 std::string oat_filename(OatFile::DexFilenameToOatFilename(dex_file.GetLocation()));
Brian Carlstrom866c8622012-01-06 16:35:13 -0800718 open_oat_file = FindOpenedOatFileFromOatLocation(oat_filename);
719 if (open_oat_file != NULL) {
720 return open_oat_file;
721 }
722
Brian Carlstromd601af82012-01-06 10:15:19 -0800723 while (true) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800724 UniquePtr<const OatFile> oat_file(FindOatFileFromOatLocation(oat_filename));
725 if (oat_file.get() != NULL) {
Brian Carlstromd601af82012-01-06 10:15:19 -0800726 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
727 if (dex_file.GetHeader().checksum_ == oat_dex_file->GetDexFileChecksum()) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800728 RegisterOatFileLocked(*oat_file.get());
729 return oat_file.release();
Brian Carlstromd601af82012-01-06 10:15:19 -0800730 }
731 LOG(WARNING) << ".oat file " << oat_file->GetLocation()
732 << " checksum mismatch with " << dex_file.GetLocation() << " --- regenerating";
733 if (TEMP_FAILURE_RETRY(unlink(oat_file->GetLocation().c_str())) != 0) {
734 PLOG(FATAL) << "Couldn't remove obsolete .oat file " << oat_file->GetLocation();
735 }
736 // Fall through...
Elliott Hughesed6d78e2011-10-25 17:35:14 -0700737 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800738 // Try to generate oat file if it wasn't found or was obsolete.
739 // Note we can be racing with another runtime to do this.
740 std::string oat_cache_filename(GetArtCacheFilenameOrDie(oat_filename));
741 UniquePtr<LockedFd> locked_fd(LockedFd::CreateAndLock(oat_cache_filename, 0644));
742 if (locked_fd.get() == NULL) {
743 LOG(ERROR) << "Failed to create and lock oat file " << oat_cache_filename;
744 return NULL;
Elliott Hughes234da572011-11-03 22:13:06 -0700745 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800746 // Check to see if the fd we opened and locked matches the file in
747 // the filesystem. If they don't, then somebody else unlinked ours
748 // and created a new file, and we need to use that one instead. (If
749 // we caught them between the unlink and the create, we'll get an
750 // ENOENT from the file stat.)
751 struct stat fd_stat;
752 int fd_stat_result = fstat(locked_fd->GetFd(), &fd_stat);
753 if (fd_stat_result != 0) {
754 PLOG(ERROR) << "Failed to fstat file descriptor of oat file " << oat_cache_filename;
755 return NULL;
756 }
757 struct stat file_stat;
758 int file_stat_result = stat(oat_cache_filename.c_str(), &file_stat);
759 if (file_stat_result != 0
760 || fd_stat.st_dev != file_stat.st_dev
761 || fd_stat.st_ino != file_stat.st_ino) {
762 LOG(INFO) << "Opened oat file " << oat_cache_filename << " is stale; sleeping and retrying";
763 usleep(250 * 1000); // if something is hosed, don't peg machine
764 continue;
765 }
766
767 // We have the correct file open and locked. If the file size is
768 // zero, then it was just created by us and we can generate its
769 // contents. If not, someone else created it. Either way, we'll
770 // loop to retry opening the file.
771 if (fd_stat.st_size == 0) {
772 bool success = GenerateOatFile(dex_file.GetLocation(),
773 locked_fd->GetFd(),
774 oat_cache_filename);
775 if (!success) {
776 LOG(ERROR) << "Failed to generate oat file " << oat_cache_filename;
777 return NULL;
778 }
779 }
jeffhao262bf462011-10-20 18:36:32 -0700780 }
Brian Carlstromd601af82012-01-06 10:15:19 -0800781 // Not reached
Brian Carlstromaded5f72011-10-07 17:15:04 -0700782}
783
Brian Carlstromae826982011-11-09 01:33:42 -0800784const OatFile* ClassLinker::FindOpenedOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700785 for (size_t i = 0; i < oat_files_.size(); i++) {
786 const OatFile* oat_file = oat_files_[i];
787 DCHECK(oat_file != NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800788 if (oat_file->GetLocation() == oat_location) {
Brian Carlstromaded5f72011-10-07 17:15:04 -0700789 return oat_file;
790 }
791 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700792 return NULL;
793}
Brian Carlstromaded5f72011-10-07 17:15:04 -0700794
Brian Carlstromae826982011-11-09 01:33:42 -0800795const OatFile* ClassLinker::FindOatFileFromOatLocation(const std::string& oat_location) {
Brian Carlstrom866c8622012-01-06 16:35:13 -0800796 const OatFile* oat_file = OatFile::Open(oat_location, "", NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -0700797 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800798 if (oat_location.empty() || oat_location[0] != '/') {
799 LOG(ERROR) << "Failed to open oat file from " << oat_location;
Brian Carlstroma9f19782011-10-13 00:14:47 -0700800 return NULL;
801 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700802
Brian Carlstroma9f19782011-10-13 00:14:47 -0700803 // not found in /foo/bar/baz.oat? try /data/art-cache/foo@bar@baz.oat
Elliott Hughes95572412011-12-13 18:14:20 -0800804 std::string cache_location(GetArtCacheFilenameOrDie(oat_location));
Brian Carlstromae826982011-11-09 01:33:42 -0800805 oat_file = FindOpenedOatFileFromOatLocation(cache_location);
Brian Carlstromfad71432011-10-16 20:25:10 -0700806 if (oat_file != NULL) {
807 return oat_file;
808 }
Brian Carlstroma9f19782011-10-13 00:14:47 -0700809 oat_file = OatFile::Open(cache_location, "", NULL);
810 if (oat_file == NULL) {
Brian Carlstromae826982011-11-09 01:33:42 -0800811 LOG(INFO) << "Failed to open oat file from " << oat_location << " or " << cache_location << ".";
Brian Carlstroma9f19782011-10-13 00:14:47 -0700812 return NULL;
813 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700814 }
Brian Carlstromfad71432011-10-16 20:25:10 -0700815
Brian Carlstromae826982011-11-09 01:33:42 -0800816 CHECK(oat_file != NULL) << oat_location;
Brian Carlstromaded5f72011-10-07 17:15:04 -0700817 return oat_file;
818}
819
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700820void ClassLinker::InitFromImage() {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800821 VLOG(startup) << "ClassLinker::InitFromImage entering";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700822 CHECK(!init_done_);
823
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700824 const std::vector<Space*>& spaces = Heap::GetSpaces();
825 for (size_t i = 0; i < spaces.size(); i++) {
826 Space* space = spaces[i] ;
827 if (space->IsImageSpace()) {
828 OatFile* oat_file = OpenOat(space);
829 CHECK(oat_file != NULL) << "Failed to open oat file for image";
830 Object* dex_caches_object = space->GetImageHeader().GetImageRoot(ImageHeader::kDexCaches);
831 ObjectArray<DexCache>* dex_caches = dex_caches_object->AsObjectArray<DexCache>();
832
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800833 if (i == 0) {
834 // Special case of setting up the String class early so that we can test arbitrary objects
835 // as being Strings or not
836 Class* java_lang_String = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots)
837 ->AsObjectArray<Class>()->Get(kJavaLangString);
838 String::SetClass(java_lang_String);
839 }
840
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700841 CHECK_EQ(oat_file->GetOatHeader().GetDexFileCount(),
842 static_cast<uint32_t>(dex_caches->GetLength()));
843 for (int i = 0; i < dex_caches->GetLength(); i++) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700844 SirtRef<DexCache> dex_cache(dex_caches->Get(i));
Elliott Hughes95572412011-12-13 18:14:20 -0800845 const std::string& dex_file_location(dex_cache->GetLocation()->ToModifiedUtf8());
Brian Carlstrom89521892011-12-07 22:05:07 -0800846 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file_location);
847 const DexFile* dex_file = oat_dex_file->OpenDexFile();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700848 if (dex_file == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800849 LOG(FATAL) << "Failed to open dex file " << dex_file_location
850 << " from within oat file " << oat_file->GetLocation();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700851 }
852
Brian Carlstromaded5f72011-10-07 17:15:04 -0700853 CHECK_EQ(dex_file->GetHeader().checksum_, oat_dex_file->GetDexFileChecksum());
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700854
Brian Carlstromdf143242011-10-10 18:05:34 -0700855 AppendToBootClassPath(*dex_file, dex_cache);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700856 }
857 }
858 }
859
Brian Carlstroma663ea52011-08-19 23:33:41 -0700860 HeapBitmap* heap_bitmap = Heap::GetLiveBits();
861 DCHECK(heap_bitmap != NULL);
862
Brian Carlstroma663ea52011-08-19 23:33:41 -0700863 // reinit clases_ table
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700864 heap_bitmap->Walk(InitFromImageCallback, this);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700865
866 // reinit class_roots_
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700867 Object* class_roots_object = spaces[0]->GetImageHeader().GetImageRoot(ImageHeader::kClassRoots);
868 class_roots_ = class_roots_object->AsObjectArray<Class>();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700869
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800870 // reinit array_iftable_ from any array class instance, they should be ==
Elliott Hughes92f14b22011-10-06 12:29:54 -0700871 array_iftable_ = GetClassRoot(kObjectArrayClass)->GetIfTable();
872 DCHECK(array_iftable_ == GetClassRoot(kBooleanArrayClass)->GetIfTable());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800873 // String class root was set above
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700874 Field::SetClass(GetClassRoot(kJavaLangReflectField));
Elliott Hughes80609252011-09-23 17:24:51 -0700875 Method::SetClasses(GetClassRoot(kJavaLangReflectConstructor), GetClassRoot(kJavaLangReflectMethod));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700876 BooleanArray::SetArrayClass(GetClassRoot(kBooleanArrayClass));
877 ByteArray::SetArrayClass(GetClassRoot(kByteArrayClass));
878 CharArray::SetArrayClass(GetClassRoot(kCharArrayClass));
879 DoubleArray::SetArrayClass(GetClassRoot(kDoubleArrayClass));
880 FloatArray::SetArrayClass(GetClassRoot(kFloatArrayClass));
881 IntArray::SetArrayClass(GetClassRoot(kIntArrayClass));
882 LongArray::SetArrayClass(GetClassRoot(kLongArrayClass));
883 ShortArray::SetArrayClass(GetClassRoot(kShortArrayClass));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700884 PathClassLoader::SetClass(GetClassRoot(kDalvikSystemPathClassLoader));
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700885 StackTraceElement::SetClass(GetClassRoot(kJavaLangStackTraceElement));
Brian Carlstroma663ea52011-08-19 23:33:41 -0700886
887 FinishInit();
Brian Carlstrom0a5b14d2011-09-27 13:29:15 -0700888
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -0800889 VLOG(startup) << "ClassLinker::InitFromImage exiting";
Brian Carlstroma663ea52011-08-19 23:33:41 -0700890}
891
Brian Carlstrom78128a62011-09-15 17:21:19 -0700892void ClassLinker::InitFromImageCallback(Object* obj, void* arg) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700893 DCHECK(obj != NULL);
894 DCHECK(arg != NULL);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700895 ClassLinker* class_linker = reinterpret_cast<ClassLinker*>(arg);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700896
Elliott Hughesdbb40792011-11-18 17:05:22 -0800897 if (obj->GetClass()->IsStringClass()) {
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700898 class_linker->intern_table_->RegisterStrong(obj->AsString());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700899 return;
900 }
Brian Carlstromaded5f72011-10-07 17:15:04 -0700901 if (obj->IsClass()) {
902 // restore class to ClassLinker::classes_ table
903 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800904 ClassHelper kh(klass, class_linker);
Brian Carlstrom07bb8552012-01-18 22:10:50 -0800905 Class* existing = class_linker->InsertClass(kh.GetDescriptor(), klass, true);
906 DCHECK(existing == NULL) << kh.GetDescriptor();
Brian Carlstroma663ea52011-08-19 23:33:41 -0700907 return;
908 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700909}
910
911// Keep in sync with InitCallback. Anything we visit, we need to
912// reinit references to when reinitializing a ClassLinker from a
913// mapped image.
Elliott Hughes410c0c82011-09-01 17:58:25 -0700914void ClassLinker::VisitRoots(Heap::RootVisitor* visitor, void* arg) const {
915 visitor(class_roots_, arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700916
917 for (size_t i = 0; i < dex_caches_.size(); i++) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700918 visitor(dex_caches_[i], arg);
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700919 }
920
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700921 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -0700922 MutexLock mu(classes_lock_);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700923 typedef Table::const_iterator It; // TODO: C++0x auto
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700924 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
Elliott Hughes410c0c82011-09-01 17:58:25 -0700925 visitor(it->second, arg);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700926 }
Ian Rogers5d76c432011-10-31 21:42:49 -0700927 // Note. we deliberately ignore the class roots in the image (held in image_classes_)
Brian Carlstrom75cb3b42011-07-28 02:13:36 -0700928 }
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700929
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700930 visitor(array_iftable_, arg);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -0700931}
932
Elliott Hughesa2155262011-11-16 16:26:58 -0800933void ClassLinker::VisitClasses(ClassVisitor* visitor, void* arg) const {
934 MutexLock mu(classes_lock_);
935 typedef Table::const_iterator It; // TODO: C++0x auto
936 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
937 if (!visitor(it->second, arg)) {
938 return;
939 }
940 }
941 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
942 if (!visitor(it->second, arg)) {
943 return;
944 }
945 }
946}
947
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700948ClassLinker::~ClassLinker() {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700949 String::ResetClass();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700950 Field::ResetClass();
Elliott Hughes80609252011-09-23 17:24:51 -0700951 Method::ResetClasses();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700952 BooleanArray::ResetArrayClass();
953 ByteArray::ResetArrayClass();
954 CharArray::ResetArrayClass();
955 DoubleArray::ResetArrayClass();
956 FloatArray::ResetArrayClass();
957 IntArray::ResetArrayClass();
958 LongArray::ResetArrayClass();
959 ShortArray::ResetArrayClass();
960 PathClassLoader::ResetClass();
Shih-wei Liao55df06b2011-08-26 14:39:27 -0700961 StackTraceElement::ResetClass();
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700962 STLDeleteElements(&boot_class_path_);
963 STLDeleteElements(&oat_files_);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -0700964}
965
966DexCache* ClassLinker::AllocDexCache(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700967 SirtRef<DexCache> dex_cache(down_cast<DexCache*>(AllocObjectArray<Object>(DexCache::LengthAsArray())));
968 if (dex_cache.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700969 return NULL;
970 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700971 SirtRef<String> location(intern_table_->InternStrong(dex_file.GetLocation().c_str()));
972 if (location.get() == NULL) {
Elliott Hughes30646832011-10-13 16:59:46 -0700973 return NULL;
974 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700975 SirtRef<ObjectArray<String> > strings(AllocObjectArray<String>(dex_file.NumStringIds()));
976 if (strings.get() == NULL) {
977 return NULL;
978 }
979 SirtRef<ObjectArray<Class> > types(AllocClassArray(dex_file.NumTypeIds()));
980 if (types.get() == NULL) {
981 return NULL;
982 }
983 SirtRef<ObjectArray<Method> > methods(AllocObjectArray<Method>(dex_file.NumMethodIds()));
984 if (methods.get() == NULL) {
985 return NULL;
986 }
987 SirtRef<ObjectArray<Field> > fields(AllocObjectArray<Field>(dex_file.NumFieldIds()));
988 if (fields.get() == NULL) {
989 return NULL;
990 }
991 SirtRef<CodeAndDirectMethods> code_and_direct_methods(AllocCodeAndDirectMethods(dex_file.NumMethodIds()));
992 if (code_and_direct_methods.get() == NULL) {
993 return NULL;
994 }
995 SirtRef<ObjectArray<StaticStorageBase> > initialized_static_storage(AllocObjectArray<StaticStorageBase>(dex_file.NumTypeIds()));
996 if (initialized_static_storage.get() == NULL) {
997 return NULL;
998 }
999
1000 dex_cache->Init(location.get(),
1001 strings.get(),
1002 types.get(),
1003 methods.get(),
1004 fields.get(),
1005 code_and_direct_methods.get(),
1006 initialized_static_storage.get());
1007 return dex_cache.get();
Brian Carlstroma0808032011-07-18 00:39:23 -07001008}
1009
Brian Carlstrom9cc262e2011-08-28 12:45:30 -07001010CodeAndDirectMethods* ClassLinker::AllocCodeAndDirectMethods(size_t length) {
1011 return down_cast<CodeAndDirectMethods*>(IntArray::Alloc(CodeAndDirectMethods::LengthAsArray(length)));
Brian Carlstrom83db7722011-08-26 17:32:56 -07001012}
1013
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001014InterfaceEntry* ClassLinker::AllocInterfaceEntry(Class* interface) {
1015 DCHECK(interface->IsInterface());
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001016 SirtRef<ObjectArray<Object> > array(AllocObjectArray<Object>(InterfaceEntry::LengthAsArray()));
1017 SirtRef<InterfaceEntry> interface_entry(down_cast<InterfaceEntry*>(array.get()));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001018 interface_entry->SetInterface(interface);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001019 return interface_entry.get();
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001020}
1021
Brian Carlstrom4873d462011-08-21 15:23:39 -07001022Class* ClassLinker::AllocClass(Class* java_lang_Class, size_t class_size) {
1023 DCHECK_GE(class_size, sizeof(Class));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001024 SirtRef<Class> klass(Heap::AllocObject(java_lang_Class, class_size)->AsClass());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001025 klass->SetPrimitiveType(Primitive::kPrimNot); // default to not being primitive
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001026 klass->SetClassSize(class_size);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001027 return klass.get();
Brian Carlstrom75cb3b42011-07-28 02:13:36 -07001028}
1029
Brian Carlstrom4873d462011-08-21 15:23:39 -07001030Class* ClassLinker::AllocClass(size_t class_size) {
1031 return AllocClass(GetClassRoot(kJavaLangClass), class_size);
Brian Carlstroma0808032011-07-18 00:39:23 -07001032}
1033
Jesse Wilson35baaab2011-08-10 16:18:03 -04001034Field* ClassLinker::AllocField() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001035 return down_cast<Field*>(GetClassRoot(kJavaLangReflectField)->AllocObject());
Brian Carlstroma0808032011-07-18 00:39:23 -07001036}
1037
1038Method* ClassLinker::AllocMethod() {
Brian Carlstrom1f870082011-08-23 16:02:11 -07001039 return down_cast<Method*>(GetClassRoot(kJavaLangReflectMethod)->AllocObject());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001040}
1041
Shih-wei Liao55df06b2011-08-26 14:39:27 -07001042ObjectArray<StackTraceElement>* ClassLinker::AllocStackTraceElementArray(size_t length) {
1043 return ObjectArray<StackTraceElement>::Alloc(
1044 GetClassRoot(kJavaLangStackTraceElementArrayClass),
1045 length);
1046}
1047
Brian Carlstromaded5f72011-10-07 17:15:04 -07001048Class* EnsureResolved(Class* klass) {
1049 DCHECK(klass != NULL);
1050 // Wait for the class if it has not already been linked.
Carl Shapirob5573532011-07-12 18:22:59 -07001051 Thread* self = Thread::Current();
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001052 if (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001053 ObjectLock lock(klass);
1054 // Check for circular dependencies between classes.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001055 if (!klass->IsResolved() && klass->GetClinitThreadId() == self->GetTid()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07001056 self->ThrowNewException("Ljava/lang/ClassCircularityError;",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001057 PrettyDescriptor(klass).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001058 return NULL;
1059 }
1060 // Wait for the pending initialization to complete.
Elliott Hughes5fe594f2011-09-08 12:33:17 -07001061 while (!klass->IsResolved() && !klass->IsErroneous()) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001062 lock.Wait();
1063 }
1064 }
1065 if (klass->IsErroneous()) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001066 ThrowEarlierClassFailure(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001067 return NULL;
1068 }
1069 // Return the loaded class. No exceptions should be pending.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001070 CHECK(klass->IsResolved()) << PrettyClass(klass);
1071 CHECK(!self->IsExceptionPending())
1072 << PrettyClass(klass) << " " << PrettyTypeOf(self->GetException());
1073 return klass;
1074}
1075
Elliott Hughesdb7d5e92011-12-16 18:47:37 -08001076Class* ClassLinker::FindSystemClass(const char* descriptor) {
1077 return FindClass(descriptor, NULL);
1078}
1079
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001080Class* ClassLinker::FindClass(const char* descriptor, const ClassLoader* class_loader) {
1081 DCHECK(*descriptor != '\0') << "descriptor is empty string";
Brian Carlstromaded5f72011-10-07 17:15:04 -07001082 Thread* self = Thread::Current();
1083 DCHECK(self != NULL);
1084 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001085 if (descriptor[1] == '\0') {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001086 // only the descriptors of primitive types should be 1 character long, also avoid class lookup
1087 // for primitive classes that aren't backed by dex files.
1088 return FindPrimitiveClass(descriptor[0]);
1089 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001090 // Find the class in the loaded classes table.
1091 Class* klass = LookupClass(descriptor, class_loader);
1092 if (klass != NULL) {
1093 return EnsureResolved(klass);
1094 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001095 // Class is not yet loaded.
Elliott Hughesa7679b62012-01-24 17:15:23 -08001096 JNIEnv* env = self->GetJniEnv();
1097 ScopedLocalRef<jthrowable> cause(env, NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001098 if (descriptor[0] == '[') {
1099 return CreateArrayClass(descriptor, class_loader);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001100
Jesse Wilson47daf872011-11-23 11:42:45 -05001101 } else if (class_loader == NULL) {
1102 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, boot_class_path_);
1103 if (pair.second != NULL) {
1104 return DefineClass(descriptor, NULL, *pair.first, *pair.second);
1105 }
1106
1107 } else if (ClassLoader::UseCompileTimeClassPath()) {
1108 // first try the boot class path
1109 Class* system_class = FindSystemClass(descriptor);
1110 if (system_class != NULL) {
1111 return system_class;
1112 }
1113 CHECK(self->IsExceptionPending());
1114 self->ClearException();
1115
1116 // next try the compile time class path
Brian Carlstromaded5f72011-10-07 17:15:04 -07001117 const std::vector<const DexFile*>& class_path
1118 = ClassLoader::GetCompileTimeClassPath(class_loader);
1119 DexFile::ClassPathEntry pair = DexFile::FindInClassPath(descriptor, class_path);
Jesse Wilson47daf872011-11-23 11:42:45 -05001120 if (pair.second != NULL) {
1121 return DefineClass(descriptor, class_loader, *pair.first, *pair.second);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001122 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001123
1124 } else {
Elliott Hughes95572412011-12-13 18:14:20 -08001125 std::string class_name_string(DescriptorToDot(descriptor));
Jesse Wilson47daf872011-11-23 11:42:45 -05001126 ScopedThreadStateChange(self, Thread::kNative);
Jesse Wilson47daf872011-11-23 11:42:45 -05001127 ScopedLocalRef<jclass> c(env, AddLocalReference<jclass>(env, GetClassRoot(kJavaLangClassLoader)));
1128 CHECK(c.get() != NULL);
1129 // TODO: cache method?
1130 jmethodID mid = env->GetMethodID(c.get(), "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
1131 CHECK(mid != NULL);
1132 ScopedLocalRef<jobject> class_name_object(env, env->NewStringUTF(class_name_string.c_str()));
1133 if (class_name_object.get() == NULL) {
1134 return NULL;
1135 }
1136 ScopedLocalRef<jobject> class_loader_object(env, AddLocalReference<jobject>(env, class_loader));
Ian Rogers761bfa82012-01-11 10:14:05 -08001137 ScopedLocalRef<jobject> result(env, env->CallObjectMethod(class_loader_object.get(), mid,
1138 class_name_object.get()));
Elliott Hughesa7679b62012-01-24 17:15:23 -08001139 cause.reset(env->ExceptionOccurred());
1140 if (cause.get() != NULL) {
1141 env->ExceptionClear();
1142 // Failed to find class, so fall-through to throw NCDFE.
Ian Rogers761bfa82012-01-11 10:14:05 -08001143 } else if (result.get() == NULL) {
Ian Rogerscab01012012-01-10 17:35:46 -08001144 // broken loader - throw NPE to be compatible with Dalvik
1145 ThrowNullPointerException("ClassLoader.loadClass returned null for %s",
1146 class_name_string.c_str());
1147 return NULL;
Ian Rogers761bfa82012-01-11 10:14:05 -08001148 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08001149 // success, return Class*
Ian Rogers6b0870d2011-12-15 19:38:12 -08001150 return Decode<Class*>(env, result.get());
Ian Rogers6b0870d2011-12-15 19:38:12 -08001151 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001152 }
1153
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001154 ThrowNoClassDefFoundError("Class %s not found", PrintableString(StringPiece(descriptor)).c_str());
Elliott Hughesa7679b62012-01-24 17:15:23 -08001155 if (cause.get() != NULL) {
1156 // Initialize the cause of the NCDFE.
1157 ScopedLocalRef<jthrowable> ncdfe(env, env->ExceptionOccurred());
1158 env->ExceptionClear();
1159 static jclass Throwable_class = env->FindClass("java/lang/Throwable");
1160 static jmethodID initCause_mid = env->GetMethodID(Throwable_class, "initCause", "(Ljava/lang/Throwable;)Ljava/lang/Throwable;");
1161 env->CallObjectMethod(ncdfe.get(), initCause_mid, cause.get());
1162 env->Throw(ncdfe.get());
1163 }
Jesse Wilson47daf872011-11-23 11:42:45 -05001164 return NULL;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001165}
1166
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001167Class* ClassLinker::DefineClass(const StringPiece& descriptor,
Brian Carlstromaded5f72011-10-07 17:15:04 -07001168 const ClassLoader* class_loader,
1169 const DexFile& dex_file,
1170 const DexFile::ClassDef& dex_class_def) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001171 SirtRef<Class> klass(NULL);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001172 // Load the class from the dex file.
1173 if (!init_done_) {
1174 // finish up init of hand crafted class_roots_
1175 if (descriptor == "Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001176 klass.reset(GetClassRoot(kJavaLangObject));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001177 } else if (descriptor == "Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001178 klass.reset(GetClassRoot(kJavaLangClass));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001179 } else if (descriptor == "Ljava/lang/String;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001180 klass.reset(GetClassRoot(kJavaLangString));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001181 } else if (descriptor == "Ljava/lang/reflect/Constructor;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001182 klass.reset(GetClassRoot(kJavaLangReflectConstructor));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001183 } else if (descriptor == "Ljava/lang/reflect/Field;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001184 klass.reset(GetClassRoot(kJavaLangReflectField));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001185 } else if (descriptor == "Ljava/lang/reflect/Method;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001186 klass.reset(GetClassRoot(kJavaLangReflectMethod));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001187 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001188 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001189 }
1190 } else {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001191 klass.reset(AllocClass(SizeOfClass(dex_file, dex_class_def)));
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192 }
1193 klass->SetDexCache(FindDexCache(dex_file));
1194 LoadClass(dex_file, dex_class_def, klass, class_loader);
1195 // Check for a pending exception during load
1196 Thread* self = Thread::Current();
1197 if (self->IsExceptionPending()) {
1198 return NULL;
1199 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001200 ObjectLock lock(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001201 klass->SetClinitThreadId(self->GetTid());
1202 // Add the newly loaded class to the loaded classes table.
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001203 Class* existing = InsertClass(descriptor, klass.get(), false);
1204 if (existing != NULL) {
1205 // We failed to insert because we raced with another thread.
Brian Carlstromaded5f72011-10-07 17:15:04 -07001206 klass->SetClinitThreadId(0);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001207 klass.reset(existing);
1208 return EnsureResolved(klass.get());
Brian Carlstromaded5f72011-10-07 17:15:04 -07001209 }
1210 // Finish loading (if necessary) by finding parents
1211 CHECK(!klass->IsLoaded());
1212 if (!LoadSuperAndInterfaces(klass, dex_file)) {
1213 // Loading failed.
1214 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001215 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001216 lock.NotifyAll();
1217 return NULL;
1218 }
1219 CHECK(klass->IsLoaded());
1220 // Link the class (if necessary)
1221 CHECK(!klass->IsResolved());
Ian Rogersc2b44472011-12-14 21:17:17 -08001222 if (!LinkClass(klass, NULL)) {
Brian Carlstromaded5f72011-10-07 17:15:04 -07001223 // Linking failed.
1224 CHECK(self->IsExceptionPending());
Ian Rogers28ad40d2011-10-27 15:19:26 -07001225 klass->SetStatus(Class::kStatusError);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001226 lock.NotifyAll();
1227 return NULL;
1228 }
1229 CHECK(klass->IsResolved());
Elliott Hughes4740cdf2011-12-07 14:07:12 -08001230
1231 /*
1232 * We send CLASS_PREPARE events to the debugger from here. The
1233 * definition of "preparation" is creating the static fields for a
1234 * class and initializing them to the standard default values, but not
1235 * executing any code (that comes later, during "initialization").
1236 *
1237 * We did the static preparation in LinkClass.
1238 *
1239 * The class has been prepared and resolved but possibly not yet verified
1240 * at this point.
1241 */
1242 Dbg::PostClassPrepare(klass.get());
1243
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001244 return klass.get();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001245}
1246
Brian Carlstrom4873d462011-08-21 15:23:39 -07001247// Precomputes size that will be needed for Class, matching LinkStaticFields
1248size_t ClassLinker::SizeOfClass(const DexFile& dex_file,
1249 const DexFile::ClassDef& dex_class_def) {
1250 const byte* class_data = dex_file.GetClassData(dex_class_def);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001251 size_t num_ref = 0;
1252 size_t num_32 = 0;
1253 size_t num_64 = 0;
Ian Rogers0571d352011-11-03 19:51:38 -07001254 if (class_data != NULL) {
1255 for (ClassDataItemIterator it(dex_file, class_data); it.HasNextStaticField(); it.Next()) {
1256 const DexFile::FieldId& field_id = dex_file.GetFieldId(it.GetMemberIndex());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001257 const char* descriptor = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom4873d462011-08-21 15:23:39 -07001258 char c = descriptor[0];
1259 if (c == 'L' || c == '[') {
1260 num_ref++;
1261 } else if (c == 'J' || c == 'D') {
1262 num_64++;
1263 } else {
1264 num_32++;
1265 }
1266 }
1267 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07001268 // start with generic class data
1269 size_t size = sizeof(Class);
1270 // follow with reference fields which must be contiguous at start
1271 size += (num_ref * sizeof(uint32_t));
1272 // if there are 64-bit fields to add, make sure they are aligned
1273 if (num_64 != 0 && size != RoundUp(size, 8)) { // for 64-bit alignment
1274 if (num_32 != 0) {
1275 // use an available 32-bit field for padding
1276 num_32--;
1277 }
1278 size += sizeof(uint32_t); // either way, we are adding a word
1279 DCHECK_EQ(size, RoundUp(size, 8));
1280 }
1281 // tack on any 64-bit fields now that alignment is assured
1282 size += (num_64 * sizeof(uint64_t));
1283 // tack on any remaining 32-bit fields
1284 size += (num_32 * sizeof(uint32_t));
1285 return size;
1286}
1287
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001288void LinkCode(SirtRef<Method>& method, const OatFile::OatClass* oat_class, uint32_t method_index) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07001289 // Every kind of method should at least get an invoke stub from the oat_method.
1290 // non-abstract methods also get their code pointers.
1291 const OatFile::OatMethod oat_method = oat_class->GetOatMethod(method_index);
Brian Carlstromae826982011-11-09 01:33:42 -08001292 oat_method.LinkMethodPointers(method.get());
Brian Carlstrom92827a52011-10-10 15:50:01 -07001293
1294 if (method->IsAbstract()) {
1295 method->SetCode(Runtime::Current()->GetAbstractMethodErrorStubArray()->GetData());
1296 return;
1297 }
1298 if (method->IsNative()) {
1299 // unregistering restores the dlsym lookup stub
1300 method->UnregisterNative();
jeffhao26c0a1a2012-01-17 16:28:33 -08001301 }
1302
1303 if (Runtime::Current()->IsMethodTracingActive()) {
1304#if defined(__arm__)
1305 Trace* tracer = Runtime::Current()->GetTracer();
1306 void* trace_stub = reinterpret_cast<void*>(art_trace_entry_from_code);
1307 tracer->SaveAndUpdateCode(method.get(), trace_stub);
1308#else
1309 UNIMPLEMENTED(WARNING);
1310#endif
Brian Carlstrom92827a52011-10-10 15:50:01 -07001311 }
1312}
1313
Brian Carlstromf615a612011-07-23 12:50:34 -07001314void ClassLinker::LoadClass(const DexFile& dex_file,
1315 const DexFile::ClassDef& dex_class_def,
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001316 SirtRef<Class>& klass,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001317 const ClassLoader* class_loader) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001318 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001319 CHECK(klass->GetDexCache() != NULL);
1320 CHECK_EQ(Class::kStatusNotReady, klass->GetStatus());
Brian Carlstromf615a612011-07-23 12:50:34 -07001321 const char* descriptor = dex_file.GetClassDescriptor(dex_class_def);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001322 CHECK(descriptor != NULL);
1323
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001324 klass->SetClass(GetClassRoot(kJavaLangClass));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001325 uint32_t access_flags = dex_class_def.access_flags_;
Elliott Hughes582a7d12011-10-10 18:38:42 -07001326 // Make sure that none of our runtime-only flags are set.
1327 CHECK_EQ(access_flags & ~kAccJavaFlagsMask, 0U);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001328 klass->SetAccessFlags(access_flags);
1329 klass->SetClassLoader(class_loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001330 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001331 klass->SetStatus(Class::kStatusIdx);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001332
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001333 klass->SetDexTypeIndex(dex_class_def.class_idx_);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001334
Ian Rogers0571d352011-11-03 19:51:38 -07001335 // Load fields fields.
1336 const byte* class_data = dex_file.GetClassData(dex_class_def);
1337 if (class_data == NULL) {
1338 return; // no fields or methods - for example a marker interface
Brian Carlstrom934486c2011-07-12 23:42:50 -07001339 }
Ian Rogers0571d352011-11-03 19:51:38 -07001340 ClassDataItemIterator it(dex_file, class_data);
1341 if (it.NumStaticFields() != 0) {
1342 klass->SetSFields(AllocObjectArray<Field>(it.NumStaticFields()));
1343 }
1344 if (it.NumInstanceFields() != 0) {
1345 klass->SetIFields(AllocObjectArray<Field>(it.NumInstanceFields()));
1346 }
1347 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
1348 SirtRef<Field> sfield(AllocField());
1349 klass->SetStaticField(i, sfield.get());
1350 LoadField(dex_file, it, klass, sfield);
1351 }
1352 for (size_t i = 0; it.HasNextInstanceField(); i++, it.Next()) {
1353 SirtRef<Field> ifield(AllocField());
1354 klass->SetInstanceField(i, ifield.get());
1355 LoadField(dex_file, it, klass, ifield);
Brian Carlstrom934486c2011-07-12 23:42:50 -07001356 }
1357
Brian Carlstromaded5f72011-10-07 17:15:04 -07001358 UniquePtr<const OatFile::OatClass> oat_class;
1359 if (Runtime::Current()->IsStarted() && !ClassLoader::UseCompileTimeClassPath()) {
Brian Carlstromae826982011-11-09 01:33:42 -08001360 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001361 if (oat_file != NULL) {
1362 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1363 if (oat_dex_file != NULL) {
1364 uint32_t class_def_index;
1365 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1366 CHECK(found) << descriptor;
1367 oat_class.reset(oat_dex_file->GetOatClass(class_def_index));
Brian Carlstrom92827a52011-10-10 15:50:01 -07001368 CHECK(oat_class.get() != NULL) << descriptor;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001369 }
1370 }
1371 }
Ian Rogers0571d352011-11-03 19:51:38 -07001372 // Load methods.
1373 if (it.NumDirectMethods() != 0) {
Brian Carlstrom934486c2011-07-12 23:42:50 -07001374 // TODO: append direct methods to class object
Ian Rogers0571d352011-11-03 19:51:38 -07001375 klass->SetDirectMethods(AllocObjectArray<Method>(it.NumDirectMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001376 }
Ian Rogers0571d352011-11-03 19:51:38 -07001377 if (it.NumVirtualMethods() != 0) {
1378 // TODO: append direct methods to class object
1379 klass->SetVirtualMethods(AllocObjectArray<Method>(it.NumVirtualMethods()));
Brian Carlstrom934486c2011-07-12 23:42:50 -07001380 }
Ian Rogers0571d352011-11-03 19:51:38 -07001381 size_t method_index = 0;
1382 for (size_t i = 0; it.HasNextDirectMethod(); i++, it.Next()) {
1383 SirtRef<Method> method(AllocMethod());
1384 klass->SetDirectMethod(i, method.get());
1385 LoadMethod(dex_file, it, klass, method);
1386 if (oat_class.get() != NULL) {
1387 LinkCode(method, oat_class.get(), method_index);
1388 }
1389 method_index++;
1390 }
1391 for (size_t i = 0; it.HasNextVirtualMethod(); i++, it.Next()) {
1392 SirtRef<Method> method(AllocMethod());
1393 klass->SetVirtualMethod(i, method.get());
1394 LoadMethod(dex_file, it, klass, method);
1395 if (oat_class.get() != NULL) {
1396 LinkCode(method, oat_class.get(), method_index);
1397 }
1398 method_index++;
1399 }
1400 DCHECK(!it.HasNext());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001401}
1402
Ian Rogers0571d352011-11-03 19:51:38 -07001403void ClassLinker::LoadField(const DexFile& dex_file, const ClassDataItemIterator& it,
1404 SirtRef<Class>& klass, SirtRef<Field>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001405 uint32_t field_idx = it.GetMemberIndex();
1406 dst->SetDexFieldIndex(field_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001407 dst->SetDeclaringClass(klass.get());
Ian Rogers0571d352011-11-03 19:51:38 -07001408 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001409}
1410
Ian Rogers0571d352011-11-03 19:51:38 -07001411void ClassLinker::LoadMethod(const DexFile& dex_file, const ClassDataItemIterator& it,
1412 SirtRef<Class>& klass, SirtRef<Method>& dst) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001413 uint32_t method_idx = it.GetMemberIndex();
1414 dst->SetDexMethodIndex(method_idx);
1415 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001416 dst->SetDeclaringClass(klass.get());
Elliott Hughes20cde902011-10-04 17:37:27 -07001417
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001418
1419 StringPiece method_name(dex_file.GetMethodName(method_id));
1420 if (method_name == "<init>") {
Elliott Hughes80609252011-09-23 17:24:51 -07001421 dst->SetClass(GetClassRoot(kJavaLangReflectConstructor));
1422 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001423
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001424 if (method_name == "finalize") {
1425 // Create the prototype for a signature of "()V"
1426 const DexFile::StringId* void_string_id = dex_file.FindStringId("V");
1427 if (void_string_id != NULL) {
1428 const DexFile::TypeId* void_type_id =
1429 dex_file.FindTypeId(dex_file.GetIndexForStringId(*void_string_id));
1430 if (void_type_id != NULL) {
1431 std::vector<uint16_t> no_args;
1432 const DexFile::ProtoId* finalizer_proto =
1433 dex_file.FindProtoId(dex_file.GetIndexForTypeId(*void_type_id), no_args);
1434 if (finalizer_proto != NULL) {
1435 // We have the prototype in the dex file
1436 if (klass->GetClassLoader() != NULL) { // All non-boot finalizer methods are flagged
1437 klass->SetFinalizable();
1438 } else {
1439 StringPiece klass_descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
1440 // The Enum class declares a "final" finalize() method to prevent subclasses from
1441 // introducing a finalizer. We don't want to set the finalizable flag for Enum or its
1442 // subclasses, so we exclude it here.
1443 // We also want to avoid setting the flag on Object, where we know that finalize() is
1444 // empty.
1445 if (klass_descriptor != "Ljava/lang/Object;" &&
1446 klass_descriptor != "Ljava/lang/Enum;") {
1447 klass->SetFinalizable();
1448 }
1449 }
1450 }
1451 }
Elliott Hughes20cde902011-10-04 17:37:27 -07001452 }
Carl Shapiro419ec7b2011-08-03 14:48:33 -07001453 }
Ian Rogers0571d352011-11-03 19:51:38 -07001454 dst->SetCodeItemOffset(it.GetMethodCodeItemOffset());
Ian Rogers0571d352011-11-03 19:51:38 -07001455 dst->SetAccessFlags(it.GetMemberAccessFlags());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001456
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001457 dst->SetDexCacheStrings(klass->GetDexCache()->GetStrings());
1458 dst->SetDexCacheResolvedTypes(klass->GetDexCache()->GetResolvedTypes());
1459 dst->SetDexCacheResolvedMethods(klass->GetDexCache()->GetResolvedMethods());
1460 dst->SetDexCacheResolvedFields(klass->GetDexCache()->GetResolvedFields());
1461 dst->SetDexCacheCodeAndDirectMethods(klass->GetDexCache()->GetCodeAndDirectMethods());
1462 dst->SetDexCacheInitializedStaticStorage(klass->GetDexCache()->GetInitializedStaticStorage());
Brian Carlstrom934486c2011-07-12 23:42:50 -07001463}
1464
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001465void ClassLinker::AppendToBootClassPath(const DexFile& dex_file) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001466 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
1467 AppendToBootClassPath(dex_file, dex_cache);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001468}
1469
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001470void ClassLinker::AppendToBootClassPath(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
1471 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001472 boot_class_path_.push_back(&dex_file);
Brian Carlstroma663ea52011-08-19 23:33:41 -07001473 RegisterDexFile(dex_file, dex_cache);
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001474}
1475
Brian Carlstromaded5f72011-10-07 17:15:04 -07001476bool ClassLinker::IsDexFileRegisteredLocked(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001477 dex_lock_.AssertHeld();
Brian Carlstromaded5f72011-10-07 17:15:04 -07001478 for (size_t i = 0; i != dex_files_.size(); ++i) {
1479 if (dex_files_[i] == &dex_file) {
1480 return true;
1481 }
1482 }
1483 return false;
Brian Carlstroma663ea52011-08-19 23:33:41 -07001484}
1485
Brian Carlstromaded5f72011-10-07 17:15:04 -07001486bool ClassLinker::IsDexFileRegistered(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001487 MutexLock mu(dex_lock_);
Brian Carlstrom06918512011-10-16 23:39:12 -07001488 return IsDexFileRegisteredLocked(dex_file);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001489}
1490
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001491void ClassLinker::RegisterDexFileLocked(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001492 dex_lock_.AssertHeld();
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001493 CHECK(dex_cache.get() != NULL) << dex_file.GetLocation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001494 CHECK(dex_cache->GetLocation()->Equals(dex_file.GetLocation()));
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001495 dex_files_.push_back(&dex_file);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001496 dex_caches_.push_back(dex_cache.get());
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001497}
1498
Brian Carlstromaded5f72011-10-07 17:15:04 -07001499void ClassLinker::RegisterDexFile(const DexFile& dex_file) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001500 {
1501 MutexLock mu(dex_lock_);
1502 if (IsDexFileRegisteredLocked(dex_file)) {
1503 return;
1504 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001505 }
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001506 // Don't alloc while holding the lock, since allocation may need to
1507 // suspend all threads and another thread may need the dex_lock_ to
1508 // get to a suspend point.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001509 SirtRef<DexCache> dex_cache(AllocDexCache(dex_file));
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001510 {
1511 MutexLock mu(dex_lock_);
1512 if (IsDexFileRegisteredLocked(dex_file)) {
1513 return;
1514 }
1515 RegisterDexFileLocked(dex_file, dex_cache);
1516 }
Brian Carlstromaded5f72011-10-07 17:15:04 -07001517}
1518
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001519void ClassLinker::RegisterDexFile(const DexFile& dex_file, SirtRef<DexCache>& dex_cache) {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001520 MutexLock mu(dex_lock_);
Brian Carlstromaded5f72011-10-07 17:15:04 -07001521 RegisterDexFileLocked(dex_file, dex_cache);
1522}
1523
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001524const DexFile& ClassLinker::FindDexFile(const DexCache* dex_cache) const {
Ian Rogers466bb252011-10-14 03:29:56 -07001525 CHECK(dex_cache != NULL);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001526 MutexLock mu(dex_lock_);
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001527 for (size_t i = 0; i != dex_caches_.size(); ++i) {
1528 if (dex_caches_[i] == dex_cache) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001529 return *dex_files_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001530 }
1531 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001532 CHECK(false) << "Failed to find DexFile for DexCache " << dex_cache->GetLocation()->ToModifiedUtf8();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001533 return *dex_files_[-1];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001534}
1535
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001536DexCache* ClassLinker::FindDexCache(const DexFile& dex_file) const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001537 MutexLock mu(dex_lock_);
Brian Carlstromf615a612011-07-23 12:50:34 -07001538 for (size_t i = 0; i != dex_files_.size(); ++i) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07001539 if (dex_files_[i] == &dex_file) {
Brian Carlstrom7e49dca2011-07-22 18:07:34 -07001540 return dex_caches_[i];
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001541 }
1542 }
Brian Carlstrom69b15fb2011-09-03 12:25:21 -07001543 CHECK(false) << "Failed to find DexCache for DexFile " << dex_file.GetLocation();
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07001544 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001545}
1546
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001547Class* ClassLinker::InitializePrimitiveClass(Class* primitive_class,
1548 const char* descriptor,
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001549 Primitive::Type type) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001550 // TODO: deduce one argument from the other
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001551 CHECK(primitive_class != NULL);
1552 primitive_class->SetAccessFlags(kAccPublic | kAccFinal | kAccAbstract);
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001553 primitive_class->SetPrimitiveType(type);
1554 primitive_class->SetStatus(Class::kStatusInitialized);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001555 Class* existing = InsertClass(descriptor, primitive_class, false);
1556 CHECK(existing == NULL) << "InitPrimitiveClass(" << descriptor << ") failed";
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001557 return primitive_class;
Carl Shapiro565f5072011-07-10 13:39:43 -07001558}
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001559
Brian Carlstrombe977852011-07-19 14:54:54 -07001560// Create an array class (i.e. the class object for the array, not the
1561// array itself). "descriptor" looks like "[C" or "[[[[B" or
1562// "[Ljava/lang/String;".
1563//
1564// If "descriptor" refers to an array of primitives, look up the
1565// primitive type's internally-generated class object.
1566//
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001567// "class_loader" is the class loader of the class that's referring to
1568// us. It's used to ensure that we're looking for the element type in
1569// the right context. It does NOT become the class loader for the
1570// array class; that always comes from the base element class.
Brian Carlstrombe977852011-07-19 14:54:54 -07001571//
1572// Returns NULL with an exception raised on failure.
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001573Class* ClassLinker::CreateArrayClass(const std::string& descriptor, const ClassLoader* class_loader) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001574 CHECK_EQ('[', descriptor[0]);
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001575
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001576 // Identify the underlying component type
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001577 Class* component_type = FindClass(descriptor.substr(1).c_str(), class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001578 if (component_type == NULL) {
Brian Carlstrom5b8e4c82011-09-18 01:38:59 -07001579 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001580 return NULL;
1581 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001582
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001583 // See if the component type is already loaded. Array classes are
1584 // always associated with the class loader of their underlying
1585 // element type -- an array of Strings goes with the loader for
1586 // java/lang/String -- so we need to look for it there. (The
1587 // caller should have checked for the existence of the class
1588 // before calling here, but they did so with *their* class loader,
1589 // not the component type's loader.)
1590 //
1591 // If we find it, the caller adds "loader" to the class' initiating
1592 // loader list, which should prevent us from going through this again.
1593 //
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001594 // This call is unnecessary if "loader" and "component_type->GetClassLoader()"
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001595 // are the same, because our caller (FindClass) just did the
1596 // lookup. (Even if we get this wrong we still have correct behavior,
1597 // because we effectively do this lookup again when we add the new
1598 // class to the hash table --- necessary because of possible races with
1599 // other threads.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001600 if (class_loader != component_type->GetClassLoader()) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001601 Class* new_class = LookupClass(descriptor.c_str(), component_type->GetClassLoader());
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001602 if (new_class != NULL) {
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001603 return new_class;
1604 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001605 }
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001606
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001607 // Fill out the fields in the Class.
1608 //
1609 // It is possible to execute some methods against arrays, because
1610 // all arrays are subclasses of java_lang_Object_, so we need to set
1611 // up a vtable. We can just point at the one in java_lang_Object_.
1612 //
1613 // Array classes are simple enough that we don't need to do a full
1614 // link step.
1615
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001616 SirtRef<Class> new_class(NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001617 if (!init_done_) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001618 // Classes that were hand created, ie not by FindSystemClass
Elliott Hughes418d20f2011-09-22 14:00:39 -07001619 if (descriptor == "[Ljava/lang/Class;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001620 new_class.reset(GetClassRoot(kClassArrayClass));
Elliott Hughes418d20f2011-09-22 14:00:39 -07001621 } else if (descriptor == "[Ljava/lang/Object;") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001622 new_class.reset(GetClassRoot(kObjectArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001623 } else if (descriptor == "[C") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001624 new_class.reset(GetClassRoot(kCharArrayClass));
Elliott Hughesc1674ed2011-08-25 18:09:09 -07001625 } else if (descriptor == "[I") {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001626 new_class.reset(GetClassRoot(kIntArrayClass));
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001627 }
1628 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001629 if (new_class.get() == NULL) {
1630 new_class.reset(AllocClass(sizeof(Class)));
1631 if (new_class.get() == NULL) {
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001632 return NULL;
1633 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001634 new_class->SetComponentType(component_type);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001635 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001636 DCHECK(new_class->GetComponentType() != NULL);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001637 Class* java_lang_Object = GetClassRoot(kJavaLangObject);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001638 new_class->SetSuperClass(java_lang_Object);
1639 new_class->SetVTable(java_lang_Object->GetVTable());
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001640 new_class->SetPrimitiveType(Primitive::kPrimNot);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001641 new_class->SetClassLoader(component_type->GetClassLoader());
1642 new_class->SetStatus(Class::kStatusInitialized);
1643 // don't need to set new_class->SetObjectSize(..)
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001644 // because Object::SizeOf delegates to Array::SizeOf
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001645
1646
1647 // All arrays have java/lang/Cloneable and java/io/Serializable as
1648 // interfaces. We need to set that up here, so that stuff like
1649 // "instanceof" works right.
1650 //
1651 // Note: The GC could run during the call to FindSystemClass,
1652 // so we need to make sure the class object is GC-valid while we're in
1653 // there. Do this by clearing the interface list so the GC will just
1654 // think that the entries are null.
1655
1656
1657 // Use the single, global copies of "interfaces" and "iftable"
1658 // (remember not to free them for arrays).
Elliott Hughes92f14b22011-10-06 12:29:54 -07001659 CHECK(array_iftable_ != NULL);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07001660 new_class->SetIfTable(array_iftable_);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001661
1662 // Inherit access flags from the component type. Arrays can't be
1663 // used as a superclass or interface, so we want to add "final"
1664 // and remove "interface".
1665 //
1666 // Don't inherit any non-standard flags (e.g., kAccFinal)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001667 // from component_type. We assume that the array class does not
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001668 // override finalize().
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07001669 new_class->SetAccessFlags(((new_class->GetComponentType()->GetAccessFlags() &
1670 ~kAccInterface) | kAccFinal) & kAccJavaFlagsMask);
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001671
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001672 Class* existing = InsertClass(descriptor, new_class.get(), false);
1673 if (existing == NULL) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001674 return new_class.get();
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001675 }
1676 // Another thread must have loaded the class after we
1677 // started but before we finished. Abandon what we've
1678 // done.
1679 //
1680 // (Yes, this happens.)
1681
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001682 return existing;
Brian Carlstroma331b3c2011-07-18 17:47:56 -07001683}
1684
1685Class* ClassLinker::FindPrimitiveClass(char type) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001686 switch (Primitive::GetType(type)) {
1687 case Primitive::kPrimByte:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001688 return GetClassRoot(kPrimitiveByte);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001689 case Primitive::kPrimChar:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001690 return GetClassRoot(kPrimitiveChar);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001691 case Primitive::kPrimDouble:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001692 return GetClassRoot(kPrimitiveDouble);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001693 case Primitive::kPrimFloat:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001694 return GetClassRoot(kPrimitiveFloat);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001695 case Primitive::kPrimInt:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001696 return GetClassRoot(kPrimitiveInt);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001697 case Primitive::kPrimLong:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001698 return GetClassRoot(kPrimitiveLong);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001699 case Primitive::kPrimShort:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001700 return GetClassRoot(kPrimitiveShort);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001701 case Primitive::kPrimBoolean:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001702 return GetClassRoot(kPrimitiveBoolean);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001703 case Primitive::kPrimVoid:
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001704 return GetClassRoot(kPrimitiveVoid);
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07001705 case Primitive::kPrimNot:
1706 break;
Carl Shapiro744ad052011-08-06 15:53:36 -07001707 }
Elliott Hughesbd935992011-08-22 11:59:34 -07001708 std::string printable_type(PrintableChar(type));
Elliott Hughes4a2b4172011-09-20 17:08:25 -07001709 ThrowNoClassDefFoundError("Not a primitive type: %s", printable_type.c_str());
Elliott Hughesbd935992011-08-22 11:59:34 -07001710 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001711}
1712
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001713Class* ClassLinker::InsertClass(const StringPiece& descriptor, Class* klass, bool image_class) {
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08001714 if (VLOG_IS_ON(class_linker)) {
Brian Carlstromae826982011-11-09 01:33:42 -08001715 DexCache* dex_cache = klass->GetDexCache();
1716 std::string source;
1717 if (dex_cache != NULL) {
1718 source += " from ";
1719 source += dex_cache->GetLocation()->ToModifiedUtf8();
1720 }
1721 LOG(INFO) << "Loaded class " << descriptor << source;
1722 }
Brian Carlstrom9cff8e12011-08-18 16:47:29 -07001723 size_t hash = StringPieceHash()(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001724 MutexLock mu(classes_lock_);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001725 Table& classes = image_class ? image_classes_ : classes_;
1726 Class* existing = LookupClass(descriptor.data(), klass->GetClassLoader(), hash, classes);
1727#ifndef NDEBUG
1728 // Check we don't have the class in the other table in error
1729 Table& other_classes = image_class ? classes_ : image_classes_;
1730 CHECK(LookupClass(descriptor.data(), klass->GetClassLoader(), hash, other_classes) == NULL);
1731#endif
1732 if (existing != NULL) {
1733 return existing;
Ian Rogers5d76c432011-10-31 21:42:49 -07001734 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001735 classes.insert(std::make_pair(hash, klass));
1736 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001737}
1738
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001739bool ClassLinker::RemoveClass(const char* descriptor, const ClassLoader* class_loader) {
1740 size_t hash = Hash(descriptor);
Brian Carlstromae826982011-11-09 01:33:42 -08001741 MutexLock mu(classes_lock_);
Elliott Hughese5448b52012-01-18 16:44:06 -08001742 typedef Table::iterator It; // TODO: C++0x auto
Brian Carlstromae826982011-11-09 01:33:42 -08001743 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001744 ClassHelper kh;
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001745 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001746 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001747 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001748 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001749 classes_.erase(it);
1750 return true;
1751 }
1752 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001753 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Brian Carlstromae826982011-11-09 01:33:42 -08001754 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001755 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001756 if (strcmp(kh.GetDescriptor(), descriptor) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstromae826982011-11-09 01:33:42 -08001757 image_classes_.erase(it);
1758 return true;
1759 }
1760 }
1761 return false;
1762}
1763
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001764Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader) {
1765 size_t hash = Hash(descriptor);
Brian Carlstrom47d237a2011-10-18 15:08:33 -07001766 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07001767 // TODO: determine if its better to search classes_ or image_classes_ first
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001768 Class* klass = LookupClass(descriptor, class_loader, hash, classes_);
1769 if (klass != NULL) {
1770 return klass;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001771 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001772 return LookupClass(descriptor, class_loader, hash, image_classes_);
1773}
1774
1775Class* ClassLinker::LookupClass(const char* descriptor, const ClassLoader* class_loader,
1776 size_t hash, const Table& classes) {
1777 ClassHelper kh(NULL, this);
1778 typedef Table::const_iterator It; // TODO: C++0x auto
1779 for (It it = classes.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers5d76c432011-10-31 21:42:49 -07001780 Class* klass = it->second;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001781 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001782 if (strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader) {
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001783#ifndef NDEBUG
1784 for (++it; it != end && it->first == hash; ++it) {
1785 kh.ChangeClass(it->second);
1786 CHECK(!(strcmp(descriptor, kh.GetDescriptor()) == 0 && klass->GetClassLoader() == class_loader))
1787 << PrettyClass(klass) << " " << klass << " " << klass->GetClassLoader() << " "
1788 << PrettyClass(it->second) << " " << it->second << " " << it->second->GetClassLoader();
1789 }
1790#endif
Ian Rogers5d76c432011-10-31 21:42:49 -07001791 return klass;
1792 }
1793 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07001794 return NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07001795}
1796
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001797void ClassLinker::LookupClasses(const char* descriptor, std::vector<Class*>& classes) {
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001798 classes.clear();
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001799 size_t hash = Hash(descriptor);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001800 MutexLock mu(classes_lock_);
1801 typedef Table::const_iterator It; // TODO: C++0x auto
1802 // TODO: determine if its better to search classes_ or image_classes_ first
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001803 ClassHelper kh(NULL, this);
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001804 for (It it = classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001805 Class* klass = it->second;
1806 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001807 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001808 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001809 }
1810 }
Brian Carlstrom07bb8552012-01-18 22:10:50 -08001811 for (It it = image_classes_.lower_bound(hash), end = classes_.end(); it != end && it->first == hash; ++it) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001812 Class* klass = it->second;
1813 kh.ChangeClass(klass);
Elliott Hughesc3b77c72011-12-15 20:56:48 -08001814 if (strcmp(descriptor, kh.GetDescriptor()) == 0) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001815 classes.push_back(klass);
Elliott Hughes6fa602d2011-12-02 17:54:25 -08001816 }
1817 }
1818}
1819
Ian Rogersc20a83e2012-01-18 18:15:32 -08001820#ifndef NDEBUG
1821static void CheckMethodsHaveGcMaps(Class* klass) {
1822 if (!Runtime::Current()->IsStarted()) {
1823 return;
1824 }
1825 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1826 Method* method = klass->GetDirectMethod(i);
1827 if (!method->IsNative() && !method->IsAbstract()) {
1828 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1829 }
1830 }
1831 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1832 Method* method = klass->GetVirtualMethod(i);
1833 if (!method->IsNative() && !method->IsAbstract()) {
1834 CHECK(method->GetGcMap() != NULL) << PrettyMethod(method);
1835 }
1836 }
1837}
1838#else
1839static void CheckMethodsHaveGcMaps(Class* klass) {
1840}
1841#endif
1842
jeffhao98eacac2011-09-14 16:11:53 -07001843void ClassLinker::VerifyClass(Class* klass) {
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001844 // TODO: assert that the monitor on the Class is held
jeffhao98eacac2011-09-14 16:11:53 -07001845 if (klass->IsVerified()) {
1846 return;
1847 }
1848
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001849 CHECK_EQ(klass->GetStatus(), Class::kStatusResolved) << PrettyClass(klass);
jeffhao98eacac2011-09-14 16:11:53 -07001850 klass->SetStatus(Class::kStatusVerifying);
jeffhao98eacac2011-09-14 16:11:53 -07001851
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001852 // Try to use verification information from oat file, otherwise do runtime verification
1853 const DexFile& dex_file = FindDexFile(klass->GetDexCache());
1854 if (VerifyClassUsingOatFile(dex_file, klass) || verifier::DexVerifier::VerifyClass(klass)) {
1855 // Make sure all classes referenced by catch blocks are resolved
1856 ResolveClassExceptionHandlerTypes(dex_file, klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001857 klass->SetStatus(Class::kStatusVerified);
Ian Rogersc20a83e2012-01-18 18:15:32 -08001858 // Sanity check that a verified class has GC maps on all methods
1859 CheckMethodsHaveGcMaps(klass);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001860 } else {
1861 LOG(ERROR) << "Verification failed on class " << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001862 Thread* self = Thread::Current();
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001863 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException()) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001864 self->ThrowNewExceptionF("Ljava/lang/VerifyError;", "Verification of %s failed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001865 PrettyDescriptor(klass).c_str());
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001866 CHECK_EQ(klass->GetStatus(), Class::kStatusVerifying) << PrettyClass(klass);
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07001867 klass->SetStatus(Class::kStatusError);
jeffhao5cfd6fb2011-09-27 13:54:29 -07001868 }
jeffhao98eacac2011-09-14 16:11:53 -07001869}
1870
Brian Carlstrome7d856b2012-01-11 18:10:55 -08001871bool ClassLinker::VerifyClassUsingOatFile(const DexFile& dex_file, Class* klass) {
1872 if (!Runtime::Current()->IsStarted()) {
1873 return false;
1874 }
1875 if (ClassLoader::UseCompileTimeClassPath()) {
1876 return false;
1877 }
1878 const OatFile* oat_file = FindOatFileForDexFile(dex_file);
1879 if (oat_file == NULL) {
1880 return false;
1881 }
1882 const OatFile::OatDexFile* oat_dex_file = oat_file->GetOatDexFile(dex_file.GetLocation());
1883 CHECK(oat_dex_file != NULL) << PrettyClass(klass);
1884 const char* descriptor = ClassHelper(klass).GetDescriptor();
1885 uint32_t class_def_index;
1886 bool found = dex_file.FindClassDefIndex(descriptor, class_def_index);
1887 CHECK(found) << descriptor;
1888 UniquePtr<const OatFile::OatClass> oat_class(oat_dex_file->GetOatClass(class_def_index));
1889 CHECK(oat_class.get() != NULL) << descriptor;
1890 Class::Status status = oat_class->GetStatus();
1891 if (status == Class::kStatusError) {
1892 ThrowEarlierClassFailure(klass);
1893 klass->SetVerifyErrorClass(Thread::Current()->GetException()->GetClass());
1894 klass->SetStatus(Class::kStatusError);
1895 return true;
1896 }
1897 if (status == Class::kStatusVerified || status == Class::kStatusInitialized) {
1898 return true;
1899 }
1900 if (status == Class::kStatusNotReady) {
1901 return false;
1902 }
1903 LOG(FATAL) << "Unexpected class status: " << status;
1904 return false;
1905}
1906
1907void ClassLinker::ResolveClassExceptionHandlerTypes(const DexFile& dex_file, Class* klass) {
1908 for (size_t i = 0; i < klass->NumDirectMethods(); i++) {
1909 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetDirectMethod(i));
1910 }
1911 for (size_t i = 0; i < klass->NumVirtualMethods(); i++) {
1912 ResolveMethodExceptionHandlerTypes(dex_file, klass->GetVirtualMethod(i));
1913 }
1914}
1915
1916void ClassLinker::ResolveMethodExceptionHandlerTypes(const DexFile& dex_file, Method* method) {
1917 // similar to DexVerifier::ScanTryCatchBlocks and dex2oat's ResolveExceptionsForMethod.
1918 const DexFile::CodeItem* code_item = dex_file.GetCodeItem(method->GetCodeItemOffset());
1919 if (code_item == NULL) {
1920 return; // native or abstract method
1921 }
1922 if (code_item->tries_size_ == 0) {
1923 return; // nothing to process
1924 }
1925 const byte* handlers_ptr = DexFile::GetCatchHandlerData(*code_item, 0);
1926 uint32_t handlers_size = DecodeUnsignedLeb128(&handlers_ptr);
1927 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1928 for (uint32_t idx = 0; idx < handlers_size; idx++) {
1929 CatchHandlerIterator iterator(handlers_ptr);
1930 for (; iterator.HasNext(); iterator.Next()) {
1931 // Ensure exception types are resolved so that they don't need resolution to be delivered,
1932 // unresolved exception types will be ignored by exception delivery
1933 if (iterator.GetHandlerTypeIndex() != DexFile::kDexNoIndex16) {
1934 Class* exception_type = linker->ResolveType(iterator.GetHandlerTypeIndex(), method);
1935 if (exception_type == NULL) {
1936 DCHECK(Thread::Current()->IsExceptionPending());
1937 Thread::Current()->ClearException();
1938 }
1939 }
1940 }
1941 handlers_ptr = iterator.EndDataPointer();
1942 }
1943}
1944
Ian Rogersc2b44472011-12-14 21:17:17 -08001945static void CheckProxyConstructor(Method* constructor);
1946static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype);
1947
Jesse Wilson95caa792011-10-12 18:14:17 -04001948Class* ClassLinker::CreateProxyClass(String* name, ObjectArray<Class>* interfaces,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001949 ClassLoader* loader, ObjectArray<Method>* methods,
1950 ObjectArray<ObjectArray<Class> >* throws) {
Ian Rogersc2b44472011-12-14 21:17:17 -08001951 SirtRef<Class> klass(AllocClass(GetClassRoot(kJavaLangClass), sizeof(SynthesizedProxyClass)));
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001952 CHECK(klass.get() != NULL);
Ian Rogersc2b44472011-12-14 21:17:17 -08001953 DCHECK(klass->GetClass() != NULL);
Jesse Wilson95caa792011-10-12 18:14:17 -04001954 klass->SetObjectSize(sizeof(Proxy));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001955 klass->SetAccessFlags(kAccClassIsProxy | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001956 klass->SetClassLoader(loader);
Ian Rogersc2b44472011-12-14 21:17:17 -08001957 DCHECK_EQ(klass->GetPrimitiveType(), Primitive::kPrimNot);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001958 klass->SetName(name);
Ian Rogers466bb252011-10-14 03:29:56 -07001959 Class* proxy_class = GetClassRoot(kJavaLangReflectProxy);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001960 klass->SetDexCache(proxy_class->GetDexCache());
Ian Rogersc2b44472011-12-14 21:17:17 -08001961
1962 klass->SetStatus(Class::kStatusIdx);
1963
1964 klass->SetDexTypeIndex(DexFile::kDexNoIndex16);
1965
1966 // Create static field that holds throws, instance fields are inherited
1967 klass->SetSFields(AllocObjectArray<Field>(1));
1968 SirtRef<Field> sfield(AllocField());
1969 klass->SetStaticField(0, sfield.get());
1970 sfield->SetDexFieldIndex(-1);
1971 sfield->SetDeclaringClass(klass.get());
1972 sfield->SetAccessFlags(kAccStatic | kAccPublic | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04001973
Ian Rogers466bb252011-10-14 03:29:56 -07001974 // Proxies have 1 direct method, the constructor
Jesse Wilson95caa792011-10-12 18:14:17 -04001975 klass->SetDirectMethods(AllocObjectArray<Method>(1));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001976 klass->SetDirectMethod(0, CreateProxyConstructor(klass, proxy_class));
Jesse Wilson95caa792011-10-12 18:14:17 -04001977
Ian Rogers466bb252011-10-14 03:29:56 -07001978 // Create virtual method using specified prototypes
Jesse Wilson95caa792011-10-12 18:14:17 -04001979 size_t num_virtual_methods = methods->GetLength();
1980 klass->SetVirtualMethods(AllocObjectArray<Method>(num_virtual_methods));
1981 for (size_t i = 0; i < num_virtual_methods; ++i) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07001982 SirtRef<Method> prototype(methods->Get(i));
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08001983 klass->SetVirtualMethod(i, CreateProxyMethod(klass, prototype));
Jesse Wilson95caa792011-10-12 18:14:17 -04001984 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001985
1986 klass->SetSuperClass(proxy_class); // The super class is java.lang.reflect.Proxy
1987 klass->SetStatus(Class::kStatusLoaded); // Class is now effectively in the loaded state
1988 DCHECK(!Thread::Current()->IsExceptionPending());
1989
1990 // Link the fields and virtual methods, creating vtable and iftables
1991 if (!LinkClass(klass, interfaces)) {
Jesse Wilson95caa792011-10-12 18:14:17 -04001992 DCHECK(Thread::Current()->IsExceptionPending());
1993 return NULL;
1994 }
Ian Rogersc2b44472011-12-14 21:17:17 -08001995 sfield->SetObject(NULL, throws); // initialize throws field
1996 klass->SetStatus(Class::kStatusInitialized);
1997
1998 // sanity checks
1999#ifndef NDEBUG
2000 bool debug = true;
2001#else
2002 bool debug = false;
2003#endif
2004 if (debug) {
2005 CHECK(klass->GetIFields() == NULL);
2006 CheckProxyConstructor(klass->GetDirectMethod(0));
2007 for (size_t i = 0; i < num_virtual_methods; ++i) {
2008 SirtRef<Method> prototype(methods->Get(i));
2009 CheckProxyMethod(klass->GetVirtualMethod(i), prototype);
2010 }
Brian Carlstrom89521892011-12-07 22:05:07 -08002011 std::string throws_field_name("java.lang.Class[][] ");
Ian Rogersc2b44472011-12-14 21:17:17 -08002012 throws_field_name += name->ToModifiedUtf8();
2013 throws_field_name += ".throws";
2014 CHECK(PrettyField(klass->GetStaticField(0)) == throws_field_name);
2015
2016 SynthesizedProxyClass* synth_proxy_class = down_cast<SynthesizedProxyClass*>(klass.get());
2017 CHECK_EQ(synth_proxy_class->GetThrows(), throws);
2018 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002019 return klass.get();
Jesse Wilson95caa792011-10-12 18:14:17 -04002020}
2021
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002022std::string ClassLinker::GetDescriptorForProxy(const Class* proxy_class) {
2023 DCHECK(proxy_class->IsProxyClass());
2024 String* name = proxy_class->GetName();
2025 DCHECK(name != NULL);
2026 return DotToDescriptor(name->ToModifiedUtf8().c_str());
2027}
2028
2029
2030Method* ClassLinker::CreateProxyConstructor(SirtRef<Class>& klass, Class* proxy_class) {
Ian Rogers466bb252011-10-14 03:29:56 -07002031 // Create constructor for Proxy that must initialize h
Ian Rogers466bb252011-10-14 03:29:56 -07002032 ObjectArray<Method>* proxy_direct_methods = proxy_class->GetDirectMethods();
Jesse Wilsonecbce8f2011-10-21 19:57:36 -04002033 CHECK_EQ(proxy_direct_methods->GetLength(), 15);
Ian Rogers466bb252011-10-14 03:29:56 -07002034 Method* proxy_constructor = proxy_direct_methods->Get(2);
2035 // Clone the existing constructor of Proxy (our constructor would just invoke it so steal its
2036 // code_ too)
2037 Method* constructor = down_cast<Method*>(proxy_constructor->Clone());
2038 // Make this constructor public and fix the class to be our Proxy version
2039 constructor->SetAccessFlags((constructor->GetAccessFlags() & ~kAccProtected) | kAccPublic);
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002040 constructor->SetDeclaringClass(klass.get());
Ian Rogersc2b44472011-12-14 21:17:17 -08002041 return constructor;
2042}
2043
2044static void CheckProxyConstructor(Method* constructor) {
Ian Rogers466bb252011-10-14 03:29:56 -07002045 CHECK(constructor->IsConstructor());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002046 MethodHelper mh(constructor);
2047 CHECK_STREQ(mh.GetName(), "<init>");
2048 CHECK(mh.GetSignature() == "(Ljava/lang/reflect/InvocationHandler;)V");
Ian Rogers466bb252011-10-14 03:29:56 -07002049 DCHECK(constructor->IsPublic());
Jesse Wilson95caa792011-10-12 18:14:17 -04002050}
2051
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002052Method* ClassLinker::CreateProxyMethod(SirtRef<Class>& klass, SirtRef<Method>& prototype) {
2053 // Ensure prototype is in dex cache so that we can use the dex cache to look up the overridden
2054 // prototype method
2055 prototype->GetDexCacheResolvedMethods()->Set(prototype->GetDexMethodIndex(), prototype.get());
2056 // We steal everything from the prototype (such as DexCache, invoke stub, etc.) then specialize
Ian Rogers466bb252011-10-14 03:29:56 -07002057 // as necessary
2058 Method* method = down_cast<Method*>(prototype->Clone());
2059
2060 // Set class to be the concrete proxy class and clear the abstract flag, modify exceptions to
2061 // the intersection of throw exceptions as defined in Proxy
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002062 method->SetDeclaringClass(klass.get());
Ian Rogers466bb252011-10-14 03:29:56 -07002063 method->SetAccessFlags((method->GetAccessFlags() & ~kAccAbstract) | kAccFinal);
Jesse Wilson95caa792011-10-12 18:14:17 -04002064
Ian Rogers466bb252011-10-14 03:29:56 -07002065 // At runtime the method looks like a reference and argument saving method, clone the code
2066 // related parameters from this method.
2067 Method* refs_and_args = Runtime::Current()->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
2068 method->SetCoreSpillMask(refs_and_args->GetCoreSpillMask());
2069 method->SetFpSpillMask(refs_and_args->GetFpSpillMask());
2070 method->SetFrameSizeInBytes(refs_and_args->GetFrameSizeInBytes());
2071 method->SetCode(reinterpret_cast<void*>(art_proxy_invoke_handler));
Ian Rogersc2b44472011-12-14 21:17:17 -08002072 return method;
2073}
Jesse Wilson95caa792011-10-12 18:14:17 -04002074
Ian Rogersc2b44472011-12-14 21:17:17 -08002075static void CheckProxyMethod(Method* method, SirtRef<Method>& prototype) {
Ian Rogers466bb252011-10-14 03:29:56 -07002076 // Basic sanity
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002077 CHECK(!prototype->IsFinal());
2078 CHECK(method->IsFinal());
2079 CHECK(!method->IsAbstract());
2080 MethodHelper mh(method);
2081 const char* method_name = mh.GetName();
2082 const char* method_shorty = mh.GetShorty();
2083 Class* method_return = mh.GetReturnType();
2084
2085 mh.ChangeMethod(prototype.get());
2086
2087 CHECK_STREQ(mh.GetName(), method_name);
2088 CHECK_STREQ(mh.GetShorty(), method_shorty);
Ian Rogers466bb252011-10-14 03:29:56 -07002089
2090 // More complex sanity - via dex cache
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002091 CHECK_EQ(mh.GetReturnType(), method_return);
Jesse Wilson95caa792011-10-12 18:14:17 -04002092}
2093
Brian Carlstrom25c33252011-09-18 15:58:35 -07002094bool ClassLinker::InitializeClass(Class* klass, bool can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002095 CHECK(klass->IsResolved() || klass->IsErroneous())
2096 << PrettyClass(klass) << " is " << klass->GetStatus();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002097
Carl Shapirob5573532011-07-12 18:22:59 -07002098 Thread* self = Thread::Current();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002099
Brian Carlstrom25c33252011-09-18 15:58:35 -07002100 Method* clinit = NULL;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002101 {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002102 // see JLS 3rd edition, 12.4.2 "Detailed Initialization Procedure" for the locking protocol
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002103 ObjectLock lock(klass);
2104
Brian Carlstromd1422f82011-09-28 11:37:09 -07002105 if (klass->GetStatus() == Class::kStatusInitialized) {
2106 return true;
2107 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002108
Brian Carlstromd1422f82011-09-28 11:37:09 -07002109 if (klass->IsErroneous()) {
2110 ThrowEarlierClassFailure(klass);
2111 return false;
2112 }
2113
2114 if (klass->GetStatus() == Class::kStatusResolved) {
jeffhao98eacac2011-09-14 16:11:53 -07002115 VerifyClass(klass);
2116 if (klass->GetStatus() != Class::kStatusVerified) {
Ian Rogers595799e2012-01-11 17:32:51 -08002117 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002118 return false;
2119 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002120 }
2121
Brian Carlstrom25c33252011-09-18 15:58:35 -07002122 clinit = klass->FindDeclaredDirectMethod("<clinit>", "()V");
2123 if (clinit != NULL && !can_run_clinit) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002124 // if the class has a <clinit> but we can't run it during compilation,
Ian Rogers595799e2012-01-11 17:32:51 -08002125 // don't bother going to kStatusInitializing. We return true to maintain
2126 // the invariant that a false result implies there is a pending exception.
2127 return true;
Brian Carlstrom25c33252011-09-18 15:58:35 -07002128 }
2129
Brian Carlstromd1422f82011-09-28 11:37:09 -07002130 // If the class is kStatusInitializing, either this thread is
2131 // initializing higher up the stack or another thread has beat us
2132 // to initializing and we need to wait. Either way, this
2133 // invocation of InitializeClass will not be responsible for
2134 // running <clinit> and will return.
2135 if (klass->GetStatus() == Class::kStatusInitializing) {
Elliott Hughes005ab2e2011-09-11 17:15:31 -07002136 // We caught somebody else in the act; was it us?
Elliott Hughesdcc24742011-09-07 14:02:44 -07002137 if (klass->GetClinitThreadId() == self->GetTid()) {
Brian Carlstromd1422f82011-09-28 11:37:09 -07002138 // Yes. That's fine. Return so we can continue initializing.
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002139 return true;
2140 }
Brian Carlstromd1422f82011-09-28 11:37:09 -07002141 // No. That's fine. Wait for another thread to finish initializing.
2142 return WaitForInitializeClass(klass, self, lock);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002143 }
2144
2145 if (!ValidateSuperClassDescriptors(klass)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002146 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002147 klass->SetStatus(Class::kStatusError);
2148 return false;
2149 }
2150
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002151 DCHECK_EQ(klass->GetStatus(), Class::kStatusVerified) << PrettyClass(klass);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002152
Elliott Hughesdcc24742011-09-07 14:02:44 -07002153 klass->SetClinitThreadId(self->GetTid());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002154 klass->SetStatus(Class::kStatusInitializing);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002155 }
2156
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002157 uint64_t t0 = NanoTime();
2158
Brian Carlstrom25c33252011-09-18 15:58:35 -07002159 if (!InitializeSuperClass(klass, can_run_clinit)) {
Ian Rogers595799e2012-01-11 17:32:51 -08002160 CHECK(self->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002161 return false;
2162 }
2163
2164 InitializeStaticFields(klass);
2165
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002166 if (clinit != NULL) {
Elliott Hughesf5ecf062011-09-06 17:37:59 -07002167 clinit->Invoke(self, NULL, NULL, NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002168 }
2169
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002170 uint64_t t1 = NanoTime();
2171
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002172 bool success = true;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002173 {
2174 ObjectLock lock(klass);
2175
2176 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002177 WrapExceptionInInitializer();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002178 klass->SetStatus(Class::kStatusError);
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002179 success = false;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002180 } else {
Elliott Hughes83df2ac2011-10-11 16:37:54 -07002181 RuntimeStats* global_stats = Runtime::Current()->GetStats();
2182 RuntimeStats* thread_stats = self->GetStats();
2183 ++global_stats->class_init_count;
2184 ++thread_stats->class_init_count;
2185 global_stats->class_init_time_ns += (t1 - t0);
2186 thread_stats->class_init_time_ns += (t1 - t0);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002187 klass->SetStatus(Class::kStatusInitialized);
Elliott Hughes4dd9b4d2011-12-12 18:29:24 -08002188 if (VLOG_IS_ON(class_linker)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002189 ClassHelper kh(klass);
2190 LOG(INFO) << "Initialized class " << kh.GetDescriptor() << " from " << kh.GetLocation();
Brian Carlstromae826982011-11-09 01:33:42 -08002191 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002192 }
2193 lock.NotifyAll();
2194 }
Ian Rogersbdfb1a52012-01-12 14:05:22 -08002195 return success;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002196}
2197
Brian Carlstromd1422f82011-09-28 11:37:09 -07002198bool ClassLinker::WaitForInitializeClass(Class* klass, Thread* self, ObjectLock& lock) {
2199 while (true) {
Elliott Hughesd9cdfe92011-10-06 16:09:04 -07002200 CHECK(!self->IsExceptionPending()) << PrettyTypeOf(self->GetException());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002201 lock.Wait();
2202
2203 // When we wake up, repeat the test for init-in-progress. If
2204 // there's an exception pending (only possible if
2205 // "interruptShouldThrow" was set), bail out.
2206 if (self->IsExceptionPending()) {
Elliott Hughes4d0207c2011-10-03 19:14:34 -07002207 WrapExceptionInInitializer();
Brian Carlstromd1422f82011-09-28 11:37:09 -07002208 klass->SetStatus(Class::kStatusError);
2209 return false;
2210 }
2211 // Spurious wakeup? Go back to waiting.
2212 if (klass->GetStatus() == Class::kStatusInitializing) {
2213 continue;
2214 }
2215 if (klass->IsErroneous()) {
2216 // The caller wants an exception, but it was thrown in a
2217 // different thread. Synthesize one here.
Brian Carlstromdf143242011-10-10 18:05:34 -07002218 ThrowNoClassDefFoundError("<clinit> failed for class %s; see exception in other thread",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002219 PrettyDescriptor(klass).c_str());
Brian Carlstromd1422f82011-09-28 11:37:09 -07002220 return false;
2221 }
2222 if (klass->IsInitialized()) {
2223 return true;
2224 }
2225 LOG(FATAL) << "Unexpected class status. " << PrettyClass(klass) << " is " << klass->GetStatus();
2226 }
2227 LOG(FATAL) << "Not Reached" << PrettyClass(klass);
2228}
2229
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002230bool ClassLinker::ValidateSuperClassDescriptors(const Class* klass) {
2231 if (klass->IsInterface()) {
2232 return true;
2233 }
2234 // begin with the methods local to the superclass
2235 if (klass->HasSuperClass() &&
2236 klass->GetClassLoader() != klass->GetSuperClass()->GetClassLoader()) {
2237 const Class* super = klass->GetSuperClass();
Ian Rogers595799e2012-01-11 17:32:51 -08002238 for (int i = super->GetVTable()->GetLength() - 1; i >= 0; --i) {
2239 const Method* method = klass->GetVTable()->Get(i);
2240 if (method != super->GetVTable()->Get(i) &&
2241 !IsSameMethodSignatureInDifferentClassContexts(method, super, klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002242 ThrowLinkageError("Class %s method %s resolves differently in superclass %s",
2243 PrettyDescriptor(klass).c_str(), PrettyMethod(method).c_str(),
2244 PrettyDescriptor(super).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002245 return false;
2246 }
2247 }
2248 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002249 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
2250 InterfaceEntry* interface_entry = klass->GetIfTable()->Get(i);
2251 Class* interface = interface_entry->GetInterface();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002252 if (klass->GetClassLoader() != interface->GetClassLoader()) {
2253 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002254 const Method* method = interface_entry->GetMethodArray()->Get(j);
Ian Rogers595799e2012-01-11 17:32:51 -08002255 if (!IsSameMethodSignatureInDifferentClassContexts(method, interface,
2256 method->GetDeclaringClass())) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002257 ThrowLinkageError("Class %s method %s resolves differently in interface %s",
2258 PrettyDescriptor(method->GetDeclaringClass()).c_str(),
2259 PrettyMethod(method).c_str(),
2260 PrettyDescriptor(interface).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002261 return false;
2262 }
2263 }
2264 }
2265 }
2266 return true;
2267}
2268
Ian Rogers595799e2012-01-11 17:32:51 -08002269// Returns true if classes referenced by the signature of the method are the
2270// same classes in klass1 as they are in klass2.
2271bool ClassLinker::IsSameMethodSignatureInDifferentClassContexts(const Method* method,
2272 const Class* klass1,
2273 const Class* klass2) {
Ian Rogers9074b992011-10-26 17:41:55 -07002274 if (klass1 == klass2) {
2275 return true;
Brian Carlstrome10b6972011-09-26 13:49:03 -07002276 }
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002277 const DexFile& dex_file = FindDexFile(method->GetDeclaringClass()->GetDexCache());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002278 const DexFile::ProtoId& proto_id =
2279 dex_file.GetMethodPrototype(dex_file.GetMethodId(method->GetDexMethodIndex()));
Ian Rogers0571d352011-11-03 19:51:38 -07002280 for (DexFileParameterIterator it(dex_file, proto_id); it.HasNext(); it.Next()) {
2281 const char* descriptor = it.GetDescriptor();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002282 if (descriptor == NULL) {
2283 break;
2284 }
2285 if (descriptor[0] == 'L' || descriptor[0] == '[') {
2286 // Found a non-primitive type.
Ian Rogers595799e2012-01-11 17:32:51 -08002287 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002288 return false;
2289 }
2290 }
2291 }
2292 // Check the return type
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002293 const char* descriptor = dex_file.GetReturnTypeDescriptor(proto_id);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002294 if (descriptor[0] == 'L' || descriptor[0] == '[') {
Ian Rogers595799e2012-01-11 17:32:51 -08002295 if (!IsSameDescriptorInDifferentClassContexts(descriptor, klass1, klass2)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002296 return false;
2297 }
2298 }
2299 return true;
2300}
2301
Ian Rogers595799e2012-01-11 17:32:51 -08002302// Returns true if the descriptor resolves to the same class in the context of klass1 and klass2.
2303bool ClassLinker::IsSameDescriptorInDifferentClassContexts(const char* descriptor,
2304 const Class* klass1,
2305 const Class* klass2) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002306 CHECK(descriptor != NULL);
2307 CHECK(klass1 != NULL);
2308 CHECK(klass2 != NULL);
Ian Rogers9074b992011-10-26 17:41:55 -07002309 if (klass1 == klass2) {
2310 return true;
2311 }
Brian Carlstrom578bbdc2011-07-21 14:07:47 -07002312 Class* found1 = FindClass(descriptor, klass1->GetClassLoader());
Ian Rogers595799e2012-01-11 17:32:51 -08002313 if (found1 == NULL) {
Carl Shapirob5573532011-07-12 18:22:59 -07002314 Thread::Current()->ClearException();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002315 }
Ian Rogers595799e2012-01-11 17:32:51 -08002316 Class* found2 = FindClass(descriptor, klass2->GetClassLoader());
2317 if (found2 == NULL) {
2318 Thread::Current()->ClearException();
2319 }
2320 return found1 == found2;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002321}
2322
Brian Carlstrom25c33252011-09-18 15:58:35 -07002323bool ClassLinker::InitializeSuperClass(Class* klass, bool can_run_clinit) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002324 CHECK(klass != NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002325 if (!klass->IsInterface() && klass->HasSuperClass()) {
2326 Class* super_class = klass->GetSuperClass();
2327 if (super_class->GetStatus() != Class::kStatusInitialized) {
2328 CHECK(!super_class->IsInterface());
Elliott Hughes5f791332011-09-15 17:45:30 -07002329 Thread* self = Thread::Current();
2330 klass->MonitorEnter(self);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002331 bool super_initialized = InitializeClass(super_class, can_run_clinit);
Elliott Hughes5f791332011-09-15 17:45:30 -07002332 klass->MonitorExit(self);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002333 // TODO: check for a pending exception
2334 if (!super_initialized) {
Brian Carlstrom25c33252011-09-18 15:58:35 -07002335 if (!can_run_clinit) {
2336 // Don't set status to error when we can't run <clinit>.
Brian Carlstrome7d856b2012-01-11 18:10:55 -08002337 CHECK_EQ(klass->GetStatus(), Class::kStatusInitializing) << PrettyClass(klass);
Brian Carlstrom25c33252011-09-18 15:58:35 -07002338 klass->SetStatus(Class::kStatusVerified);
2339 return false;
2340 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002341 klass->SetStatus(Class::kStatusError);
2342 klass->NotifyAll();
2343 return false;
2344 }
2345 }
2346 }
2347 return true;
2348}
2349
Brian Carlstrom25c33252011-09-18 15:58:35 -07002350bool ClassLinker::EnsureInitialized(Class* c, bool can_run_clinit) {
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002351 CHECK(c != NULL);
2352 if (c->IsInitialized()) {
2353 return true;
2354 }
2355
Elliott Hughes5f791332011-09-15 17:45:30 -07002356 Thread* self = Thread::Current();
Elliott Hughes4681c802011-09-25 18:04:37 -07002357 ScopedThreadStateChange tsc(self, Thread::kRunnable);
Ian Rogers595799e2012-01-11 17:32:51 -08002358 bool success = InitializeClass(c, can_run_clinit);
2359 if (!success) {
2360 CHECK(self->IsExceptionPending());
2361 }
2362 return success;
Elliott Hughesf4c21c92011-08-19 17:31:31 -07002363}
2364
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002365void ClassLinker::ConstructFieldMap(const DexFile& dex_file, const DexFile::ClassDef& dex_class_def,
Ian Rogers0571d352011-11-03 19:51:38 -07002366 Class* c, std::map<uint32_t, Field*>& field_map) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002367 const ClassLoader* cl = c->GetClassLoader();
2368 const byte* class_data = dex_file.GetClassData(dex_class_def);
Ian Rogers0571d352011-11-03 19:51:38 -07002369 ClassDataItemIterator it(dex_file, class_data);
2370 for (size_t i = 0; it.HasNextStaticField(); i++, it.Next()) {
2371 field_map[i] = ResolveField(dex_file, it.GetMemberIndex(), c->GetDexCache(), cl, true);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002372 }
2373}
2374
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002375void ClassLinker::InitializeStaticFields(Class* klass) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002376 size_t num_static_fields = klass->NumStaticFields();
2377 if (num_static_fields == 0) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002378 return;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002379 }
Brian Carlstromf615a612011-07-23 12:50:34 -07002380 DexCache* dex_cache = klass->GetDexCache();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002381 // TODO: this seems like the wrong check. do we really want !IsPrimitive && !IsArray?
Brian Carlstromf615a612011-07-23 12:50:34 -07002382 if (dex_cache == NULL) {
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002383 return;
2384 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002385 ClassHelper kh(klass);
2386 const DexFile::ClassDef* dex_class_def = kh.GetClassDef();
Brian Carlstromf615a612011-07-23 12:50:34 -07002387 CHECK(dex_class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002388 const DexFile& dex_file = kh.GetDexFile();
Ian Rogers0571d352011-11-03 19:51:38 -07002389 EncodedStaticFieldValueIterator it(dex_file, dex_cache, this, *dex_class_def);
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002390
Ian Rogers0571d352011-11-03 19:51:38 -07002391 if (it.HasNext()) {
2392 // We reordered the fields, so we need to be able to map the field indexes to the right fields.
2393 std::map<uint32_t, Field*> field_map;
2394 ConstructFieldMap(dex_file, *dex_class_def, klass, field_map);
2395 for (size_t i = 0; it.HasNext(); i++, it.Next()) {
2396 it.ReadValueToField(field_map[i]);
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07002397 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002398 }
2399}
2400
Ian Rogersc2b44472011-12-14 21:17:17 -08002401bool ClassLinker::LinkClass(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002402 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002403 if (!LinkSuperClass(klass)) {
2404 return false;
2405 }
Ian Rogersc2b44472011-12-14 21:17:17 -08002406 if (!LinkMethods(klass, interfaces)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002407 return false;
2408 }
2409 if (!LinkInstanceFields(klass)) {
2410 return false;
2411 }
Brian Carlstrom4873d462011-08-21 15:23:39 -07002412 if (!LinkStaticFields(klass)) {
2413 return false;
2414 }
2415 CreateReferenceInstanceOffsets(klass);
2416 CreateReferenceStaticOffsets(klass);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002417 CHECK_EQ(Class::kStatusLoaded, klass->GetStatus());
2418 klass->SetStatus(Class::kStatusResolved);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002419 return true;
2420}
2421
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002422bool ClassLinker::LoadSuperAndInterfaces(SirtRef<Class>& klass, const DexFile& dex_file) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002423 CHECK_EQ(Class::kStatusIdx, klass->GetStatus());
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002424 StringPiece descriptor(dex_file.StringByTypeIdx(klass->GetDexTypeIndex()));
2425 const DexFile::ClassDef* class_def = dex_file.FindClassDef(descriptor);
Ian Rogerscab01012012-01-10 17:35:46 -08002426 CHECK(class_def != NULL);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002427 uint16_t super_class_idx = class_def->superclass_idx_;
2428 if (super_class_idx != DexFile::kDexNoIndex16) {
2429 Class* super_class = ResolveType(dex_file, super_class_idx, klass.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002430 if (super_class == NULL) {
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002431 DCHECK(Thread::Current()->IsExceptionPending());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002432 return false;
2433 }
Ian Rogersbe125a92012-01-11 15:19:49 -08002434 // Verify
2435 if (!klass->CanAccess(super_class)) {
2436 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2437 "Class %s extended by class %s is inaccessible",
2438 PrettyDescriptor(super_class).c_str(),
2439 PrettyDescriptor(klass.get()).c_str());
2440 return false;
2441 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002442 klass->SetSuperClass(super_class);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002443 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002444 const DexFile::TypeList* interfaces = dex_file.GetInterfacesList(*class_def);
2445 if (interfaces != NULL) {
2446 for (size_t i = 0; i < interfaces->Size(); i++) {
2447 uint16_t idx = interfaces->GetTypeItem(i).type_idx_;
2448 Class* interface = ResolveType(dex_file, idx, klass.get());
2449 if (interface == NULL) {
2450 DCHECK(Thread::Current()->IsExceptionPending());
2451 return false;
2452 }
2453 // Verify
2454 if (!klass->CanAccess(interface)) {
2455 // TODO: the RI seemed to ignore this in my testing.
2456 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
2457 "Interface %s implemented by class %s is inaccessible",
2458 PrettyDescriptor(interface).c_str(),
2459 PrettyDescriptor(klass.get()).c_str());
2460 return false;
2461 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002462 }
2463 }
Brian Carlstrom74eb46a2011-08-02 20:10:14 -07002464 // Mark the class as loaded.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002465 klass->SetStatus(Class::kStatusLoaded);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002466 return true;
2467}
2468
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002469bool ClassLinker::LinkSuperClass(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002470 CHECK(!klass->IsPrimitive());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002471 Class* super = klass->GetSuperClass();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002472 if (klass.get() == GetClassRoot(kJavaLangObject)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002473 if (super != NULL) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002474 Thread::Current()->ThrowNewExceptionF("Ljava/lang/ClassFormatError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002475 "java.lang.Object must not have a superclass");
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002476 return false;
2477 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002478 return true;
2479 }
2480 if (super == NULL) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002481 ThrowLinkageError("No superclass defined for class %s", PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002482 return false;
2483 }
2484 // Verify
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002485 if (super->IsFinal() || super->IsInterface()) {
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002486 Thread* thread = Thread::Current();
2487 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002488 "Superclass %s of %s is %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002489 PrettyDescriptor(super).c_str(),
2490 PrettyDescriptor(klass.get()).c_str(),
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002491 super->IsFinal() ? "declared final" : "an interface");
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002492 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002493 return false;
2494 }
2495 if (!klass->CanAccess(super)) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002496 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughese555dc02011-09-25 10:46:35 -07002497 "Superclass %s is inaccessible by %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002498 PrettyDescriptor(super).c_str(),
2499 PrettyDescriptor(klass.get()).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002500 return false;
2501 }
Elliott Hughes20cde902011-10-04 17:37:27 -07002502
2503 // Inherit kAccClassIsFinalizable from the superclass in case this class doesn't override finalize.
2504 if (super->IsFinalizable()) {
2505 klass->SetFinalizable();
2506 }
2507
Elliott Hughes2da50362011-10-10 16:57:08 -07002508 // Inherit reference flags (if any) from the superclass.
2509 int reference_flags = (super->GetAccessFlags() & kAccReferenceFlagsMask);
2510 if (reference_flags != 0) {
2511 klass->SetAccessFlags(klass->GetAccessFlags() | reference_flags);
2512 }
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002513 // Disallow custom direct subclasses of java.lang.ref.Reference.
Elliott Hughesbf61ba32011-10-11 10:53:09 -07002514 if (init_done_ && super == GetClassRoot(kJavaLangRefReference)) {
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002515 ThrowLinkageError("Class %s attempts to subclass java.lang.ref.Reference, which is not allowed",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002516 PrettyDescriptor(klass.get()).c_str());
Elliott Hughes72ee0ae2011-10-10 17:31:28 -07002517 return false;
2518 }
Elliott Hughes2da50362011-10-10 16:57:08 -07002519
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002520#ifndef NDEBUG
2521 // Ensure super classes are fully resolved prior to resolving fields..
2522 while (super != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002523 CHECK(super->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002524 super = super->GetSuperClass();
2525 }
2526#endif
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002527 return true;
2528}
2529
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002530// Populate the class vtable and itable. Compute return type indices.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002531bool ClassLinker::LinkMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002532 if (klass->IsInterface()) {
2533 // No vtable.
2534 size_t count = klass->NumVirtualMethods();
2535 if (!IsUint(16, count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002536 ThrowClassFormatError("Too many methods on interface: %zd", count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002537 return false;
2538 }
Carl Shapiro565f5072011-07-10 13:39:43 -07002539 for (size_t i = 0; i < count; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002540 klass->GetVirtualMethodDuringLinking(i)->SetMethodIndex(i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002541 }
jeffhaobdb76512011-09-07 11:43:16 -07002542 // Link interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002543 return LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002544 } else {
Elliott Hughesbc258fa2011-10-06 14:45:21 -07002545 // Link virtual and interface method tables
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002546 return LinkVirtualMethods(klass) && LinkInterfaceMethods(klass, interfaces);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002547 }
2548 return true;
2549}
2550
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002551bool ClassLinker::LinkVirtualMethods(SirtRef<Class>& klass) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002552 if (klass->HasSuperClass()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002553 uint32_t max_count = klass->NumVirtualMethods() + klass->GetSuperClass()->GetVTable()->GetLength();
2554 size_t actual_count = klass->GetSuperClass()->GetVTable()->GetLength();
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002555 CHECK_LE(actual_count, max_count);
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002556 // TODO: do not assign to the vtable field until it is fully constructed.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002557 ObjectArray<Method>* vtable = klass->GetSuperClass()->GetVTable()->CopyOf(max_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002558 // See if any of our virtual methods override the superclass.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002559 MethodHelper local_mh(NULL, this);
2560 MethodHelper super_mh(NULL, this);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002561 for (size_t i = 0; i < klass->NumVirtualMethods(); ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002562 Method* local_method = klass->GetVirtualMethodDuringLinking(i);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002563 local_mh.ChangeMethod(local_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002564 size_t j = 0;
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002565 for (; j < actual_count; ++j) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002566 Method* super_method = vtable->Get(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002567 super_mh.ChangeMethod(super_method);
2568 if (local_mh.HasSameNameAndSignature(&super_mh)) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002569 // Verify
2570 if (super_method->IsFinal()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002571 MethodHelper mh(local_method);
Elliott Hughese555dc02011-09-25 10:46:35 -07002572 ThrowLinkageError("Method %s.%s overrides final method in class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002573 PrettyDescriptor(klass.get()).c_str(),
2574 mh.GetName(), mh.GetDeclaringClassDescriptor());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002575 return false;
2576 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002577 vtable->Set(j, local_method);
2578 local_method->SetMethodIndex(j);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002579 break;
2580 }
2581 }
Brian Carlstrom4a96b602011-07-26 16:40:23 -07002582 if (j == actual_count) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002583 // Not overriding, append.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002584 vtable->Set(actual_count, local_method);
2585 local_method->SetMethodIndex(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002586 actual_count += 1;
2587 }
2588 }
2589 if (!IsUint(16, actual_count)) {
Elliott Hughes92cb4982011-12-16 16:57:28 -08002590 ThrowClassFormatError("Too many methods defined on class: %zd", actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002591 return false;
2592 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002593 // Shrink vtable if possible
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002594 CHECK_LE(actual_count, max_count);
2595 if (actual_count < max_count) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002596 vtable = vtable->CopyOf(actual_count);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002597 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002598 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002599 } else {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002600 CHECK(klass.get() == GetClassRoot(kJavaLangObject));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002601 uint32_t num_virtual_methods = klass->NumVirtualMethods();
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002602 if (!IsUint(16, num_virtual_methods)) {
Elliott Hughese555dc02011-09-25 10:46:35 -07002603 ThrowClassFormatError("Too many methods: %d", num_virtual_methods);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002604 return false;
2605 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002606 SirtRef<ObjectArray<Method> > vtable(AllocObjectArray<Method>(num_virtual_methods));
Brian Carlstroma40f9bc2011-07-26 21:26:07 -07002607 for (size_t i = 0; i < num_virtual_methods; ++i) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002608 Method* virtual_method = klass->GetVirtualMethodDuringLinking(i);
2609 vtable->Set(i, virtual_method);
2610 virtual_method->SetMethodIndex(i & 0xFFFF);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002611 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002612 klass->SetVTable(vtable.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002613 }
2614 return true;
2615}
2616
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002617bool ClassLinker::LinkInterfaceMethods(SirtRef<Class>& klass, ObjectArray<Class>* interfaces) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002618 size_t super_ifcount;
2619 if (klass->HasSuperClass()) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002620 super_ifcount = klass->GetSuperClass()->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002621 } else {
2622 super_ifcount = 0;
2623 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002624 size_t ifcount = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002625 ClassHelper kh(klass.get(), this);
2626 uint32_t num_interfaces = interfaces == NULL ? kh.NumInterfaces() : interfaces->GetLength();
2627 ifcount += num_interfaces;
2628 for (size_t i = 0; i < num_interfaces; i++) {
2629 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
2630 ifcount += interface->GetIfTableCount();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002631 }
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002632 if (ifcount == 0) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002633 // TODO: enable these asserts with klass status validation
Elliott Hughesf5a7a472011-10-07 14:31:02 -07002634 // DCHECK_EQ(klass->GetIfTableCount(), 0);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002635 // DCHECK(klass->GetIfTable() == NULL);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002636 return true;
2637 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002638 SirtRef<ObjectArray<InterfaceEntry> > iftable(AllocObjectArray<InterfaceEntry>(ifcount));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002639 if (super_ifcount != 0) {
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002640 ObjectArray<InterfaceEntry>* super_iftable = klass->GetSuperClass()->GetIfTable();
2641 for (size_t i = 0; i < super_ifcount; i++) {
Ian Rogersb52b01a2012-01-12 17:01:38 -08002642 Class* super_interface = super_iftable->Get(i)->GetInterface();
2643 iftable->Set(i, AllocInterfaceEntry(super_interface));
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002644 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002645 }
2646 // Flatten the interface inheritance hierarchy.
2647 size_t idx = super_ifcount;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002648 for (size_t i = 0; i < num_interfaces; i++) {
2649 Class* interface = interfaces == NULL ? kh.GetInterface(i) : interfaces->Get(i);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002650 DCHECK(interface != NULL);
2651 if (!interface->IsInterface()) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002652 ClassHelper ih(interface);
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002653 Thread* thread = Thread::Current();
2654 thread->ThrowNewExceptionF("Ljava/lang/IncompatibleClassChangeError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002655 "Class %s implements non-interface class %s",
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002656 PrettyDescriptor(klass.get()).c_str(),
2657 PrettyDescriptor(ih.GetDescriptor()).c_str());
Ian Rogers5fc5a0c2011-12-13 10:39:49 -08002658 klass->SetVerifyErrorClass(thread->GetException()->GetClass());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002659 return false;
2660 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002661 // Check if interface is already in iftable
2662 bool duplicate = false;
2663 for (size_t j = 0; j < idx; j++) {
2664 Class* existing_interface = iftable->Get(j)->GetInterface();
2665 if (existing_interface == interface) {
2666 duplicate = true;
2667 break;
2668 }
2669 }
2670 if (!duplicate) {
2671 // Add this non-duplicate interface.
2672 iftable->Set(idx++, AllocInterfaceEntry(interface));
2673 // Add this interface's non-duplicate super-interfaces.
2674 for (int32_t j = 0; j < interface->GetIfTableCount(); j++) {
2675 Class* super_interface = interface->GetIfTable()->Get(j)->GetInterface();
2676 bool super_duplicate = false;
2677 for (size_t k = 0; k < idx; k++) {
2678 Class* existing_interface = iftable->Get(k)->GetInterface();
2679 if (existing_interface == super_interface) {
2680 super_duplicate = true;
2681 break;
2682 }
2683 }
2684 if (!super_duplicate) {
2685 iftable->Set(idx++, AllocInterfaceEntry(super_interface));
2686 }
2687 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002688 }
2689 }
Ian Rogersb52b01a2012-01-12 17:01:38 -08002690 // Shrink iftable in case duplicates were found
2691 if (idx < ifcount) {
2692 iftable.reset(iftable->CopyOf(idx));
2693 ifcount = idx;
2694 } else {
2695 CHECK_EQ(idx, ifcount);
2696 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002697 klass->SetIfTable(iftable.get());
Elliott Hughes4681c802011-09-25 18:04:37 -07002698
2699 // If we're an interface, we don't need the vtable pointers, so we're done.
2700 if (klass->IsInterface() /*|| super_ifcount == ifcount*/) {
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002701 return true;
2702 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002703 std::vector<Method*> miranda_list;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002704 MethodHelper vtable_mh(NULL, this);
2705 MethodHelper interface_mh(NULL, this);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002706 for (size_t i = 0; i < ifcount; ++i) {
2707 InterfaceEntry* interface_entry = iftable->Get(i);
2708 Class* interface = interface_entry->GetInterface();
2709 ObjectArray<Method>* method_array = AllocObjectArray<Method>(interface->NumVirtualMethods());
2710 interface_entry->SetMethodArray(method_array);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002711 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002712 for (size_t j = 0; j < interface->NumVirtualMethods(); ++j) {
2713 Method* interface_method = interface->GetVirtualMethod(j);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002714 interface_mh.ChangeMethod(interface_method);
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002715 int32_t k;
Elliott Hughes4681c802011-09-25 18:04:37 -07002716 // For each method listed in the interface's method list, find the
2717 // matching method in our class's method list. We want to favor the
2718 // subclass over the superclass, which just requires walking
2719 // back from the end of the vtable. (This only matters if the
2720 // superclass defines a private method and this class redefines
2721 // it -- otherwise it would use the same vtable slot. In .dex files
2722 // those don't end up in the virtual method table, so it shouldn't
2723 // matter which direction we go. We walk it backward anyway.)
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002724 for (k = vtable->GetLength() - 1; k >= 0; --k) {
2725 Method* vtable_method = vtable->Get(k);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002726 vtable_mh.ChangeMethod(vtable_method);
2727 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Carl Shapiro8860c0e2011-08-04 17:36:16 -07002728 if (!vtable_method->IsPublic()) {
Elliott Hughes5cb5ad22011-10-02 12:13:39 -07002729 Thread::Current()->ThrowNewExceptionF("Ljava/lang/IllegalAccessError;",
Elliott Hughes4a2b4172011-09-20 17:08:25 -07002730 "Implementation not public: %s", PrettyMethod(vtable_method).c_str());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002731 return false;
2732 }
Brian Carlstrom4b620ff2011-09-11 01:11:01 -07002733 method_array->Set(j, vtable_method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002734 break;
2735 }
2736 }
2737 if (k < 0) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002738 SirtRef<Method> miranda_method(NULL);
Elliott Hughes4681c802011-09-25 18:04:37 -07002739 for (size_t mir = 0; mir < miranda_list.size(); mir++) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002740 Method* mir_method = miranda_list[mir];
2741 vtable_mh.ChangeMethod(mir_method);
2742 if (interface_mh.HasSameNameAndSignature(&vtable_mh)) {
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002743 miranda_method.reset(miranda_list[mir]);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002744 break;
2745 }
2746 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002747 if (miranda_method.get() == NULL) {
Elliott Hughes4681c802011-09-25 18:04:37 -07002748 // point the interface table at a phantom slot
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002749 miranda_method.reset(AllocMethod());
2750 memcpy(miranda_method.get(), interface_method, sizeof(Method));
2751 miranda_list.push_back(miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002752 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002753 method_array->Set(j, miranda_method.get());
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002754 }
2755 }
2756 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002757 if (!miranda_list.empty()) {
Brian Carlstrom913af1b2011-07-23 21:41:13 -07002758 int old_method_count = klass->NumVirtualMethods();
Elliott Hughes4681c802011-09-25 18:04:37 -07002759 int new_method_count = old_method_count + miranda_list.size();
Brian Carlstrom27ec9612011-09-19 20:20:38 -07002760 klass->SetVirtualMethods((old_method_count == 0)
2761 ? AllocObjectArray<Method>(new_method_count)
2762 : klass->GetVirtualMethods()->CopyOf(new_method_count));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002763
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002764 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2765 CHECK(vtable != NULL);
2766 int old_vtable_count = vtable->GetLength();
Elliott Hughes4681c802011-09-25 18:04:37 -07002767 int new_vtable_count = old_vtable_count + miranda_list.size();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002768 vtable = vtable->CopyOf(new_vtable_count);
Elliott Hughes4681c802011-09-25 18:04:37 -07002769 for (size_t i = 0; i < miranda_list.size(); ++i) {
Brian Carlstrom92827a52011-10-10 15:50:01 -07002770 Method* method = miranda_list[i];
Ian Rogers9074b992011-10-26 17:41:55 -07002771 // Leave the declaring class alone as type indices are relative to it
Brian Carlstrom92827a52011-10-10 15:50:01 -07002772 method->SetAccessFlags(method->GetAccessFlags() | kAccMiranda);
2773 method->SetMethodIndex(0xFFFF & (old_vtable_count + i));
2774 klass->SetVirtualMethod(old_method_count + i, method);
2775 vtable->Set(old_vtable_count + i, method);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002776 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002777 // TODO: do not assign to the vtable field until it is fully constructed.
2778 klass->SetVTable(vtable);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002779 }
Elliott Hughes4681c802011-09-25 18:04:37 -07002780
2781 ObjectArray<Method>* vtable = klass->GetVTableDuringLinking();
2782 for (int i = 0; i < vtable->GetLength(); ++i) {
2783 CHECK(vtable->Get(i) != NULL);
2784 }
2785
2786// klass->DumpClass(std::cerr, Class::kDumpClassFullDetail);
2787
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002788 return true;
2789}
2790
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002791bool ClassLinker::LinkInstanceFields(SirtRef<Class>& klass) {
2792 CHECK(klass.get() != NULL);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002793 return LinkFields(klass, false);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002794}
2795
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002796bool ClassLinker::LinkStaticFields(SirtRef<Class>& klass) {
2797 CHECK(klass.get() != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002798 size_t allocated_class_size = klass->GetClassSize();
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002799 bool success = LinkFields(klass, true);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002800 CHECK_EQ(allocated_class_size, klass->GetClassSize());
Brian Carlstrom4873d462011-08-21 15:23:39 -07002801 return success;
2802}
2803
Brian Carlstromdbc05252011-09-09 01:59:59 -07002804struct LinkFieldsComparator {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002805 LinkFieldsComparator(FieldHelper* fh) : fh_(fh) {}
Elliott Hughes3b6baaa2011-10-14 19:13:56 -07002806 bool operator()(const Field* field1, const Field* field2) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002807 // First come reference fields, then 64-bit, and finally 32-bit
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002808 fh_->ChangeField(field1);
2809 Primitive::Type type1 = fh_->GetTypeAsPrimitiveType();
2810 fh_->ChangeField(field2);
2811 Primitive::Type type2 = fh_->GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002812 bool isPrimitive1 = type1 != Primitive::kPrimNot;
2813 bool isPrimitive2 = type2 != Primitive::kPrimNot;
2814 bool is64bit1 = isPrimitive1 && (type1 == Primitive::kPrimLong || type1 == Primitive::kPrimDouble);
2815 bool is64bit2 = isPrimitive2 && (type2 == Primitive::kPrimLong || type2 == Primitive::kPrimDouble);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002816 int order1 = (!isPrimitive1 ? 0 : (is64bit1 ? 1 : 2));
2817 int order2 = (!isPrimitive2 ? 0 : (is64bit2 ? 1 : 2));
2818 if (order1 != order2) {
2819 return order1 < order2;
2820 }
2821
2822 // same basic group? then sort by string.
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002823 fh_->ChangeField(field1);
2824 StringPiece name1(fh_->GetName());
2825 fh_->ChangeField(field2);
2826 StringPiece name2(fh_->GetName());
Brian Carlstromdbc05252011-09-09 01:59:59 -07002827 return name1 < name2;
2828 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002829
2830 FieldHelper* fh_;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002831};
2832
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002833bool ClassLinker::LinkFields(SirtRef<Class>& klass, bool is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002834 size_t num_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002835 is_static ? klass->NumStaticFields() : klass->NumInstanceFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002836
2837 ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002838 is_static ? klass->GetSFields() : klass->GetIFields();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002839
2840 // Initialize size and field_offset
Brian Carlstrom693267a2011-09-06 09:25:34 -07002841 size_t size;
2842 MemberOffset field_offset(0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002843 if (is_static) {
2844 size = klass->GetClassSize();
2845 field_offset = Class::FieldsOffset();
2846 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002847 Class* super_class = klass->GetSuperClass();
2848 if (super_class != NULL) {
Elliott Hughes5fe594f2011-09-08 12:33:17 -07002849 CHECK(super_class->IsResolved());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002850 field_offset = MemberOffset(super_class->GetObjectSize());
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002851 }
2852 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002853 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002854
Brian Carlstromdbc05252011-09-09 01:59:59 -07002855 CHECK_EQ(num_fields == 0, fields == NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002856
Brian Carlstromdbc05252011-09-09 01:59:59 -07002857 // we want a relatively stable order so that adding new fields
Elliott Hughesadb460d2011-10-05 17:02:34 -07002858 // minimizes disruption of C++ version such as Class and Method.
Brian Carlstromdbc05252011-09-09 01:59:59 -07002859 std::deque<Field*> grouped_and_sorted_fields;
2860 for (size_t i = 0; i < num_fields; i++) {
2861 grouped_and_sorted_fields.push_back(fields->Get(i));
2862 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002863 FieldHelper fh(NULL, this);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002864 std::sort(grouped_and_sorted_fields.begin(),
2865 grouped_and_sorted_fields.end(),
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002866 LinkFieldsComparator(&fh));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002867
2868 // References should be at the front.
2869 size_t current_field = 0;
2870 size_t num_reference_fields = 0;
2871 for (; current_field < num_fields; current_field++) {
2872 Field* field = grouped_and_sorted_fields.front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002873 fh.ChangeField(field);
2874 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002875 bool isPrimitive = type != Primitive::kPrimNot;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002876 if (isPrimitive) {
2877 break; // past last reference, move on to the next phase
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002878 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002879 grouped_and_sorted_fields.pop_front();
2880 num_reference_fields++;
2881 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002882 field->SetOffset(field_offset);
2883 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002884 }
2885
2886 // Now we want to pack all of the double-wide fields together. If
2887 // we're not aligned, though, we want to shuffle one 32-bit field
2888 // into place. If we can't find one, we'll have to pad it.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002889 if (current_field != num_fields && !IsAligned<8>(field_offset.Uint32Value())) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002890 for (size_t i = 0; i < grouped_and_sorted_fields.size(); i++) {
2891 Field* field = grouped_and_sorted_fields[i];
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002892 fh.ChangeField(field);
2893 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002894 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
2895 if (type == Primitive::kPrimLong || type == Primitive::kPrimDouble) {
Brian Carlstromdbc05252011-09-09 01:59:59 -07002896 continue;
2897 }
2898 fields->Set(current_field++, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002899 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002900 // drop the consumed field
2901 grouped_and_sorted_fields.erase(grouped_and_sorted_fields.begin() + i);
2902 break;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002903 }
Brian Carlstromdbc05252011-09-09 01:59:59 -07002904 // whether we found a 32-bit field for padding or not, we advance
2905 field_offset = MemberOffset(field_offset.Uint32Value() + sizeof(uint32_t));
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002906 }
2907
2908 // Alignment is good, shuffle any double-wide fields forward, and
2909 // finish assigning field offsets to all fields.
Elliott Hughes06b37d92011-10-16 11:51:29 -07002910 DCHECK(current_field == num_fields || IsAligned<8>(field_offset.Uint32Value()));
Brian Carlstromdbc05252011-09-09 01:59:59 -07002911 while (!grouped_and_sorted_fields.empty()) {
2912 Field* field = grouped_and_sorted_fields.front();
2913 grouped_and_sorted_fields.pop_front();
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002914 fh.ChangeField(field);
2915 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002916 CHECK(type != Primitive::kPrimNot); // should only be working on primitive types
Brian Carlstromdbc05252011-09-09 01:59:59 -07002917 fields->Set(current_field, field);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002918 field->SetOffset(field_offset);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002919 field_offset = MemberOffset(field_offset.Uint32Value() +
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002920 ((type == Primitive::kPrimLong || type == Primitive::kPrimDouble)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002921 ? sizeof(uint64_t)
2922 : sizeof(uint32_t)));
2923 current_field++;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002924 }
2925
Elliott Hughesadb460d2011-10-05 17:02:34 -07002926 // 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 -08002927 std::string descriptor(ClassHelper(klass.get(), this).GetDescriptor());
2928 if (!is_static && descriptor == "Ljava/lang/ref/Reference;") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002929 // We know there are no non-reference fields in the Reference classes, and we know
2930 // that 'referent' is alphabetically last, so this is easy...
2931 CHECK_EQ(num_reference_fields, num_fields);
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002932 fh.ChangeField(fields->Get(num_fields - 1));
2933 StringPiece name(fh.GetName());
2934 CHECK(name == "referent");
Elliott Hughesadb460d2011-10-05 17:02:34 -07002935 --num_reference_fields;
2936 }
2937
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002938#ifndef NDEBUG
Brian Carlstrombe977852011-07-19 14:54:54 -07002939 // Make sure that all reference fields appear before
2940 // non-reference fields, and all double-wide fields are aligned.
2941 bool seen_non_ref = false;
Brian Carlstromdbc05252011-09-09 01:59:59 -07002942 for (size_t i = 0; i < num_fields; i++) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002943 Field* field = fields->Get(i);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002944 if (false) { // enable to debug field layout
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002945 LOG(INFO) << "LinkFields: " << (is_static ? "static" : "instance")
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002946 << " class=" << PrettyClass(klass.get())
Brian Carlstrom65ca0772011-09-24 16:03:08 -07002947 << " field=" << PrettyField(field)
Brian Carlstromdbc05252011-09-09 01:59:59 -07002948 << " offset=" << field->GetField32(MemberOffset(Field::OffsetOffset()), false);
2949 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002950 fh.ChangeField(field);
2951 Primitive::Type type = fh.GetTypeAsPrimitiveType();
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07002952 bool is_primitive = type != Primitive::kPrimNot;
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08002953 if (descriptor == "Ljava/lang/ref/Reference;" && StringPiece(fh.GetName()) == "referent") {
Elliott Hughesadb460d2011-10-05 17:02:34 -07002954 is_primitive = true; // We lied above, so we have to expect a lie here.
2955 }
2956 if (is_primitive) {
Brian Carlstrombe977852011-07-19 14:54:54 -07002957 if (!seen_non_ref) {
2958 seen_non_ref = true;
Brian Carlstrom4873d462011-08-21 15:23:39 -07002959 DCHECK_EQ(num_reference_fields, i);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002960 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002961 } else {
2962 DCHECK(!seen_non_ref);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002963 }
2964 }
Brian Carlstrombe977852011-07-19 14:54:54 -07002965 if (!seen_non_ref) {
Brian Carlstrom4873d462011-08-21 15:23:39 -07002966 DCHECK_EQ(num_fields, num_reference_fields);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002967 }
2968#endif
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002969 size = field_offset.Uint32Value();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002970 // Update klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002971 if (is_static) {
2972 klass->SetNumReferenceStaticFields(num_reference_fields);
2973 klass->SetClassSize(size);
2974 } else {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002975 klass->SetNumReferenceInstanceFields(num_reference_fields);
Brian Carlstromdbc05252011-09-09 01:59:59 -07002976 if (!klass->IsVariableSize()) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002977 klass->SetObjectSize(size);
2978 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002979 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002980 return true;
2981}
2982
2983// Set the bitmap of reference offsets, refOffsets, from the ifields
2984// list.
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002985void ClassLinker::CreateReferenceInstanceOffsets(SirtRef<Class>& klass) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002986 uint32_t reference_offsets = 0;
2987 Class* super_class = klass->GetSuperClass();
2988 if (super_class != NULL) {
2989 reference_offsets = super_class->GetReferenceInstanceOffsets();
Brian Carlstrom4873d462011-08-21 15:23:39 -07002990 // If our superclass overflowed, we don't stand a chance.
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07002991 if (reference_offsets == CLASS_WALK_SUPER) {
2992 klass->SetReferenceInstanceOffsets(reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002993 return;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002994 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07002995 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002996 CreateReferenceOffsets(klass, false, reference_offsets);
Brian Carlstrom4873d462011-08-21 15:23:39 -07002997}
2998
Brian Carlstrom40381fb2011-10-19 14:13:40 -07002999void ClassLinker::CreateReferenceStaticOffsets(SirtRef<Class>& klass) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003000 CreateReferenceOffsets(klass, true, 0);
Brian Carlstrom4873d462011-08-21 15:23:39 -07003001}
3002
Brian Carlstrom40381fb2011-10-19 14:13:40 -07003003void ClassLinker::CreateReferenceOffsets(SirtRef<Class>& klass, bool is_static,
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003004 uint32_t reference_offsets) {
3005 size_t num_reference_fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003006 is_static ? klass->NumReferenceStaticFieldsDuringLinking()
3007 : klass->NumReferenceInstanceFieldsDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003008 const ObjectArray<Field>* fields =
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003009 is_static ? klass->GetSFields() : klass->GetIFields();
Brian Carlstrom4873d462011-08-21 15:23:39 -07003010 // All of the fields that contain object references are guaranteed
3011 // to be at the beginning of the fields list.
3012 for (size_t i = 0; i < num_reference_fields; ++i) {
3013 // Note that byte_offset is the offset from the beginning of
3014 // object, not the offset into instance data
3015 const Field* field = fields->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003016 MemberOffset byte_offset = field->GetOffsetDuringLinking();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003017 CHECK_EQ(byte_offset.Uint32Value() & (CLASS_OFFSET_ALIGNMENT - 1), 0U);
3018 if (CLASS_CAN_ENCODE_OFFSET(byte_offset.Uint32Value())) {
3019 uint32_t new_bit = CLASS_BIT_FROM_OFFSET(byte_offset.Uint32Value());
Brian Carlstrom4873d462011-08-21 15:23:39 -07003020 CHECK_NE(new_bit, 0U);
3021 reference_offsets |= new_bit;
3022 } else {
3023 reference_offsets = CLASS_WALK_SUPER;
3024 break;
3025 }
3026 }
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003027 // Update fields in klass
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003028 if (is_static) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003029 klass->SetReferenceStaticOffsets(reference_offsets);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07003030 } else {
3031 klass->SetReferenceInstanceOffsets(reference_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003032 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003033}
3034
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003035String* ClassLinker::ResolveString(const DexFile& dex_file,
Elliott Hughescf4c6c42011-09-01 15:16:42 -07003036 uint32_t string_idx, DexCache* dex_cache) {
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003037 String* resolved = dex_cache->GetResolvedString(string_idx);
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003038 if (resolved != NULL) {
3039 return resolved;
3040 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003041 const DexFile::StringId& string_id = dex_file.GetStringId(string_idx);
3042 int32_t utf16_length = dex_file.GetStringLength(string_id);
3043 const char* utf8_data = dex_file.GetStringData(string_id);
Brian Carlstrom928bf022011-10-11 02:48:14 -07003044 String* string = intern_table_->InternStrong(utf16_length, utf8_data);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003045 dex_cache->SetResolvedString(string_idx, string);
3046 return string;
3047}
3048
3049Class* ClassLinker::ResolveType(const DexFile& dex_file,
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003050 uint16_t type_idx,
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003051 DexCache* dex_cache,
3052 const ClassLoader* class_loader) {
3053 Class* resolved = dex_cache->GetResolvedType(type_idx);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003054 if (resolved == NULL) {
Ian Rogers0571d352011-11-03 19:51:38 -07003055 const char* descriptor = dex_file.StringByTypeIdx(type_idx);
Brian Carlstromaded5f72011-10-07 17:15:04 -07003056 resolved = FindClass(descriptor, class_loader);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003057 if (resolved != NULL) {
Jesse Wilson254db0f2011-11-16 16:44:11 -05003058 // TODO: we used to throw here if resolved's class loader was not the
3059 // boot class loader. This was to permit different classes with the
3060 // same name to be loaded simultaneously by different loaders
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003061 dex_cache->SetResolvedType(type_idx, resolved);
3062 } else {
Ian Rogerscab01012012-01-10 17:35:46 -08003063 CHECK(Thread::Current()->IsExceptionPending())
3064 << "Expected pending exception for failed resolution of: " << descriptor;
Ian Rogers0cfe1fb2011-08-26 03:29:44 -07003065 }
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003066 }
3067 return resolved;
3068}
3069
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003070Method* ClassLinker::ResolveMethod(const DexFile& dex_file,
3071 uint32_t method_idx,
3072 DexCache* dex_cache,
3073 const ClassLoader* class_loader,
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003074 bool is_direct) {
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003075 Method* resolved = dex_cache->GetResolvedMethod(method_idx);
3076 if (resolved != NULL) {
3077 return resolved;
3078 }
3079 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3080 Class* klass = ResolveType(dex_file, method_id.class_idx_, dex_cache, class_loader);
3081 if (klass == NULL) {
Elliott Hughescc5f9a92011-09-28 19:17:29 -07003082 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003083 return NULL;
3084 }
3085
Ian Rogers0571d352011-11-03 19:51:38 -07003086 const char* name = dex_file.StringDataByIdx(method_id.name_idx_);
3087 std::string signature(dex_file.CreateMethodSignature(method_id.proto_idx_, NULL));
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003088 if (is_direct) {
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003089 resolved = klass->FindDirectMethod(name, signature);
Brian Carlstrom7540ff42011-09-04 16:38:46 -07003090 } else if (klass->IsInterface()) {
3091 resolved = klass->FindInterfaceMethod(name, signature);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003092 } else {
3093 resolved = klass->FindVirtualMethod(name, signature);
3094 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003095 if (resolved != NULL) {
3096 dex_cache->SetResolvedMethod(method_idx, resolved);
3097 } else {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003098 ThrowNoSuchMethodError(is_direct, klass, name, signature);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003099 }
3100 return resolved;
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003101}
3102
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003103Field* ClassLinker::ResolveField(const DexFile& dex_file,
3104 uint32_t field_idx,
3105 DexCache* dex_cache,
3106 const ClassLoader* class_loader,
3107 bool is_static) {
3108 Field* resolved = dex_cache->GetResolvedField(field_idx);
3109 if (resolved != NULL) {
3110 return resolved;
3111 }
3112 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3113 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3114 if (klass == NULL) {
Ian Rogers9f1ab122011-12-12 08:52:43 -08003115 DCHECK(Thread::Current()->IsExceptionPending());
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003116 return NULL;
3117 }
3118
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003119 const char* name = dex_file.GetFieldName(field_id);
3120 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003121 if (is_static) {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003122 resolved = klass->FindStaticField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003123 } else {
Brian Carlstrom6b4ef022011-10-23 14:59:04 -07003124 resolved = klass->FindInstanceField(name, type);
Brian Carlstrom20cfffa2011-08-26 02:31:27 -07003125 }
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003126 if (resolved != NULL) {
Elliott Hughes4a2b4172011-09-20 17:08:25 -07003127 dex_cache->SetResolvedField(field_idx, resolved);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003128 } else {
Ian Rogersb067ac22011-12-13 18:05:09 -08003129 ThrowNoSuchFieldError(is_static ? "static " : "instance ", klass, type, name);
3130 }
3131 return resolved;
3132}
3133
3134Field* ClassLinker::ResolveFieldJLS(const DexFile& dex_file,
3135 uint32_t field_idx,
3136 DexCache* dex_cache,
3137 const ClassLoader* class_loader) {
3138 Field* resolved = dex_cache->GetResolvedField(field_idx);
3139 if (resolved != NULL) {
3140 return resolved;
3141 }
3142 const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
3143 Class* klass = ResolveType(dex_file, field_id.class_idx_, dex_cache, class_loader);
3144 if (klass == NULL) {
3145 DCHECK(Thread::Current()->IsExceptionPending());
3146 return NULL;
3147 }
3148
3149 const char* name = dex_file.GetFieldName(field_id);
3150 const char* type = dex_file.GetFieldTypeDescriptor(field_id);
3151 resolved = klass->FindField(name, type);
3152 if (resolved != NULL) {
3153 dex_cache->SetResolvedField(field_idx, resolved);
3154 } else {
3155 ThrowNoSuchFieldError("", klass, type, name);
Brian Carlstrom9ea1cb12011-08-24 23:18:18 -07003156 }
3157 return resolved;
Carl Shapiro5fafe2b2011-07-09 15:34:41 -07003158}
3159
Ian Rogersad25ac52011-10-04 19:13:33 -07003160const char* ClassLinker::MethodShorty(uint32_t method_idx, Method* referrer) {
3161 Class* declaring_class = referrer->GetDeclaringClass();
3162 DexCache* dex_cache = declaring_class->GetDexCache();
3163 const DexFile& dex_file = FindDexFile(dex_cache);
3164 const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
3165 return dex_file.GetShorty(method_id.proto_idx_);
3166}
3167
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003168void ClassLinker::DumpAllClasses(int flags) const {
3169 // TODO: at the time this was written, it wasn't safe to call PrettyField with the ClassLinker
3170 // lock held, because it might need to resolve a field's type, which would try to take the lock.
3171 std::vector<Class*> all_classes;
3172 {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003173 MutexLock mu(classes_lock_);
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003174 typedef Table::const_iterator It; // TODO: C++0x auto
3175 for (It it = classes_.begin(), end = classes_.end(); it != end; ++it) {
3176 all_classes.push_back(it->second);
3177 }
Ian Rogers5d76c432011-10-31 21:42:49 -07003178 for (It it = image_classes_.begin(), end = image_classes_.end(); it != end; ++it) {
3179 all_classes.push_back(it->second);
3180 }
Elliott Hughes9d5ccec2011-09-19 13:19:50 -07003181 }
3182
3183 for (size_t i = 0; i < all_classes.size(); ++i) {
3184 all_classes[i]->DumpClass(std::cerr, flags);
3185 }
3186}
3187
Elliott Hughescac6cc72011-11-03 20:31:21 -07003188void ClassLinker::DumpForSigQuit(std::ostream& os) const {
3189 MutexLock mu(classes_lock_);
3190 os << "Loaded classes: " << image_classes_.size() << " image classes; "
3191 << classes_.size() << " allocated classes\n";
3192}
3193
Elliott Hughese27955c2011-08-26 15:21:24 -07003194size_t ClassLinker::NumLoadedClasses() const {
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003195 MutexLock mu(classes_lock_);
Ian Rogers5d76c432011-10-31 21:42:49 -07003196 return classes_.size() + image_classes_.size();
Elliott Hughese27955c2011-08-26 15:21:24 -07003197}
3198
Brian Carlstrom47d237a2011-10-18 15:08:33 -07003199pid_t ClassLinker::GetClassesLockOwner() {
3200 return classes_lock_.GetOwner();
3201}
3202
3203pid_t ClassLinker::GetDexLockOwner() {
3204 return dex_lock_.GetOwner();
Brian Carlstrom24a3c2e2011-10-17 18:07:52 -07003205}
3206
Ian Rogers6d4d9fc2011-11-30 16:24:48 -08003207void ClassLinker::SetClassRoot(ClassRoot class_root, Class* klass) {
3208 DCHECK(!init_done_);
3209
3210 DCHECK(klass != NULL);
3211 DCHECK(klass->GetClassLoader() == NULL);
3212
3213 DCHECK(class_roots_ != NULL);
3214 DCHECK(class_roots_->Get(class_root) == NULL);
3215 class_roots_->Set(class_root, klass);
3216}
3217
Carl Shapiro0e5d75d2011-07-06 18:28:37 -07003218} // namespace art